startup.flags.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "flag"
  6. "net/http"
  7. "strings"
  8. prout "imuslab.com/arozos/mod/prouter"
  9. "imuslab.com/arozos/mod/utils"
  10. )
  11. /*
  12. Startup Flags Manager
  13. This script is design to provide interface for editing the boot flags
  14. during the system is running.
  15. Changes are applied to the runtime and persisted to the system database,
  16. so they survive a restart. On boot, StartupFlagsRestore loads the stored
  17. values into the runtime, except for the ones given explicitly as start
  18. parameters: those win, and overwrite the stored value.
  19. */
  20. const bootFlagsTable = "bootflags"
  21. const bootFlagsKey = "config"
  22. // bootFlags is the persisted and editable subset of the startup parameters.
  23. // MaxUploadSize and MaxFileUploadBuff are in MB, FileIOBuffer in bytes.
  24. type bootFlags struct {
  25. Hostname string
  26. MaxUploadSize int
  27. MaxFileUploadBuff int
  28. FileIOBuffer int
  29. DisableIPResolver bool
  30. EnableHomePage bool
  31. EnableDirListing bool
  32. EnableGzip bool
  33. }
  34. // bootFlagNames maps each bootFlags field to the command line flag it mirrors
  35. var bootFlagNames = map[string]string{
  36. "Hostname": "hostname",
  37. "MaxUploadSize": "max_upload_size",
  38. "MaxFileUploadBuff": "upload_buf",
  39. "FileIOBuffer": "iobuf",
  40. "DisableIPResolver": "disable_ip_resolver",
  41. "EnableHomePage": "homepage",
  42. "EnableDirListing": "dir_list",
  43. "EnableGzip": "gzip",
  44. }
  45. // currentBootFlags reads the boot flags from the runtime globals
  46. func currentBootFlags() bootFlags {
  47. return bootFlags{
  48. Hostname: *host_name,
  49. MaxUploadSize: int(max_upload_size >> 20),
  50. MaxFileUploadBuff: *upload_buf,
  51. FileIOBuffer: *file_opr_buff,
  52. DisableIPResolver: *disable_ip_resolve_services,
  53. EnableHomePage: *allow_homepage,
  54. EnableDirListing: *enable_dir_listing,
  55. EnableGzip: *enable_gzip,
  56. }
  57. }
  58. // applyBootFlags writes the boot flags into the runtime globals
  59. func applyBootFlags(c bootFlags) {
  60. *host_name = c.Hostname
  61. *max_upload = c.MaxUploadSize
  62. max_upload_size = int64(c.MaxUploadSize) << 20
  63. *upload_buf = c.MaxFileUploadBuff
  64. *file_opr_buff = c.FileIOBuffer
  65. *disable_ip_resolve_services = c.DisableIPResolver
  66. *allow_homepage = c.EnableHomePage
  67. *enable_dir_listing = c.EnableDirListing
  68. *enable_gzip = c.EnableGzip
  69. }
  70. // validateBootFlags normalises and checks a config before it is applied
  71. func validateBootFlags(c *bootFlags) error {
  72. c.Hostname = strings.TrimSpace(c.Hostname)
  73. if c.Hostname == "" {
  74. return errors.New("host name cannot be empty")
  75. }
  76. if c.MaxUploadSize <= 0 {
  77. return errors.New("max upload size must be larger than zero")
  78. }
  79. if c.MaxFileUploadBuff <= 0 {
  80. return errors.New("file upload buffer must be larger than zero")
  81. }
  82. if c.FileIOBuffer <= 0 {
  83. return errors.New("file IO buffer must be larger than zero")
  84. }
  85. return nil
  86. }
  87. // explicitStartFlags returns the names of the flags given on the command line
  88. func explicitStartFlags() map[string]bool {
  89. set := map[string]bool{}
  90. flag.Visit(func(f *flag.Flag) {
  91. set[f.Name] = true
  92. })
  93. return set
  94. }
  95. /*
  96. mergeBootFlags decides the boot flags to run with. Fields whose flag was given
  97. explicitly keep the runtime value, other fields take the stored value when one
  98. exists (and is valid), and fall back to the runtime default otherwise. stored
  99. is kept as raw fields so a config saved by an older version, missing some
  100. fields, only restores the ones it has.
  101. */
  102. func mergeBootFlags(runtime bootFlags, stored map[string]json.RawMessage, explicit map[string]bool) bootFlags {
  103. merged := runtime
  104. restore := func(field string, target interface{}) {
  105. raw, ok := stored[field]
  106. if !ok || explicit[bootFlagNames[field]] {
  107. return
  108. }
  109. json.Unmarshal(raw, target)
  110. }
  111. restore("Hostname", &merged.Hostname)
  112. restore("MaxUploadSize", &merged.MaxUploadSize)
  113. restore("MaxFileUploadBuff", &merged.MaxFileUploadBuff)
  114. restore("FileIOBuffer", &merged.FileIOBuffer)
  115. restore("DisableIPResolver", &merged.DisableIPResolver)
  116. restore("EnableHomePage", &merged.EnableHomePage)
  117. restore("EnableDirListing", &merged.EnableDirListing)
  118. restore("EnableGzip", &merged.EnableGzip)
  119. //A damaged stored value must not stop the system from booting
  120. if strings.TrimSpace(merged.Hostname) == "" {
  121. merged.Hostname = runtime.Hostname
  122. }
  123. if merged.MaxUploadSize <= 0 {
  124. merged.MaxUploadSize = runtime.MaxUploadSize
  125. }
  126. if merged.MaxFileUploadBuff <= 0 {
  127. merged.MaxFileUploadBuff = runtime.MaxFileUploadBuff
  128. }
  129. if merged.FileIOBuffer <= 0 {
  130. merged.FileIOBuffer = runtime.FileIOBuffer
  131. }
  132. return merged
  133. }
  134. /*
  135. StartupFlagsRestore loads the persisted boot flags into the runtime. It must
  136. run right after the system database opens and before any service reads these
  137. flags (e.g. the host name is captured by several modules at init).
  138. */
  139. func StartupFlagsRestore() {
  140. sysdb.NewTable(bootFlagsTable)
  141. stored := map[string]json.RawMessage{}
  142. if sysdb.KeyExists(bootFlagsTable, bootFlagsKey) {
  143. if err := sysdb.Read(bootFlagsTable, bootFlagsKey, &stored); err != nil {
  144. systemWideLogger.PrintAndLog("System", "Unable to read stored startup parameters, using defaults", err)
  145. stored = map[string]json.RawMessage{}
  146. }
  147. }
  148. merged := mergeBootFlags(currentBootFlags(), stored, explicitStartFlags())
  149. applyBootFlags(merged)
  150. //Write back so the start flags given this boot overwrite the stored values
  151. if err := sysdb.Write(bootFlagsTable, bootFlagsKey, merged); err != nil {
  152. systemWideLogger.PrintAndLog("System", "Unable to persist startup parameters", err)
  153. }
  154. }
  155. func StartupFlagsInit() {
  156. //Create a admin permission router for handling requests
  157. //Register a boot flag modifier
  158. registerSetting(settingModule{
  159. Name: "Runtime",
  160. Desc: "Change startup parameters at runtime",
  161. IconPath: "SystemAO/info/img/runtime.png",
  162. Group: "Info",
  163. StartDir: "SystemAO/boot/bootflags.html",
  164. RequireAdmin: true,
  165. })
  166. adminRouter := prout.NewModuleRouter(prout.RouterOption{
  167. AdminOnly: true,
  168. UserHandler: userHandler,
  169. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  170. utils.SendErrorResponse(w, "Permission Denied")
  171. },
  172. })
  173. adminRouter.HandleFunc("/system/bootflags", handleBootFlagsFunction)
  174. }
  175. func handleBootFlagsFunction(w http.ResponseWriter, r *http.Request) {
  176. opr, _ := utils.PostPara(r, "opr")
  177. if opr == "" {
  178. //List the current boot flags, together with the fields that were
  179. //given as start parameters this boot (they override the stored value)
  180. explicit := explicitStartFlags()
  181. fromStartFlag := []string{}
  182. for field, name := range bootFlagNames {
  183. if explicit[name] {
  184. fromStartFlag = append(fromStartFlag, field)
  185. }
  186. }
  187. js, _ := json.Marshal(struct {
  188. bootFlags
  189. FromStartFlag []string
  190. }{currentBootFlags(), fromStartFlag})
  191. utils.SendJSONResponse(w, string(js))
  192. } else if opr == "set" {
  193. //Set and update the boot flags
  194. newSettings, err := utils.PostPara(r, "value")
  195. if err != nil {
  196. utils.SendErrorResponse(w, "Invalid new seting value")
  197. return
  198. }
  199. //Fields missing from the request keep their current value
  200. newConfig := currentBootFlags()
  201. err = json.Unmarshal([]byte(newSettings), &newConfig)
  202. if err != nil {
  203. utils.SendErrorResponse(w, err.Error())
  204. return
  205. }
  206. if err = validateBootFlags(&newConfig); err != nil {
  207. utils.SendErrorResponse(w, err.Error())
  208. return
  209. }
  210. //Update the current global flags and persist them for the next boot
  211. systemWideLogger.PrintAndLog("System", "Updating boot flag to:"+newSettings, nil)
  212. applyBootFlags(newConfig)
  213. if err = sysdb.Write(bootFlagsTable, bootFlagsKey, newConfig); err != nil {
  214. systemWideLogger.PrintAndLog("System", "Unable to persist startup parameters", err)
  215. utils.SendErrorResponse(w, "Applied to runtime but failed to save: "+err.Error())
  216. return
  217. }
  218. utils.SendOK(w)
  219. } else {
  220. utils.SendErrorResponse(w, "Unknown operation")
  221. }
  222. }