config.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package config
  2. // code for managing groundseg and container configurations
  3. import (
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "goseg/defaults"
  8. "goseg/structs"
  9. "io/ioutil"
  10. "log/slog"
  11. "math/rand"
  12. "net"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "sync"
  17. "time"
  18. )
  19. var (
  20. Logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  21. // global settings config (accessed via funcs)
  22. globalConfig structs.SysConfig
  23. // base path for installation (override default with env var)
  24. BasePath = os.Getenv("GS_BASE_PATH")
  25. // only amd64 or arm64
  26. Architecture = getArchitecture()
  27. // struct of /retrieve blob
  28. StartramConfig structs.StartramRetrieve
  29. // unused for now, set with `./groundseg dev`
  30. DebugMode = false
  31. Ready = false
  32. // representation of desired/actual container states
  33. GSContainers = make(map[string]structs.ContainerState)
  34. DockerDir = "/var/lib/docker/volumes/"
  35. // version server check
  36. checkInterval = 5 * time.Minute
  37. confPath = filepath.Join(BasePath, "settings", "system.json")
  38. confMutex sync.Mutex
  39. contMutex sync.Mutex
  40. versMutex sync.Mutex
  41. )
  42. // try initializing from system.json on disk
  43. func init() {
  44. Logger.Info("Starting GroundSeg")
  45. Logger.Info("Urbit is love <3")
  46. for _, arg := range os.Args[1:] {
  47. // trigger this with `./groundseg dev`
  48. if arg == "dev" {
  49. Logger.Info("Starting GroundSeg in debug mode")
  50. DebugMode = true
  51. }
  52. }
  53. if BasePath == "" {
  54. // default base path
  55. BasePath = "/opt/nativeplanet/groundseg"
  56. }
  57. pathMsg := fmt.Sprintf("Loading configs from %s", BasePath)
  58. Logger.Info(pathMsg)
  59. confPath := filepath.Join(BasePath, "settings", "system.json")
  60. file, err := os.Open(confPath)
  61. if err != nil {
  62. // create a default if it doesn't exist
  63. err = createDefaultConf()
  64. if err != nil {
  65. // panic if we can't create it
  66. errmsg := fmt.Sprintf("Unable to create config! Please elevate permissions. %v", err)
  67. Logger.Error(errmsg)
  68. panic(errmsg)
  69. }
  70. // generate and insert wireguard keys
  71. wgPriv, wgPub, err := WgKeyGen()
  72. salt := RandString(32)
  73. if err != nil {
  74. Logger.Error(fmt.Sprintf("%v", err))
  75. } else {
  76. err = UpdateConf(map[string]interface{}{
  77. "Pubkey": wgPub,
  78. "Privkey": wgPriv,
  79. "Salt": salt,
  80. })
  81. if err != nil {
  82. Logger.Error(fmt.Sprintf("%v", err))
  83. }
  84. }
  85. }
  86. defer file.Close()
  87. // read the sysconfig to memory
  88. decoder := json.NewDecoder(file)
  89. err = decoder.Decode(&globalConfig)
  90. if err != nil {
  91. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  92. Logger.Error(errmsg)
  93. }
  94. // wipe the sessions on each startup
  95. globalConfig.Sessions.Authorized = make(map[string]structs.SessionInfo)
  96. globalConfig.Sessions.Unauthorized = make(map[string]structs.SessionInfo)
  97. configMap := make(map[string]interface{})
  98. configBytes, err := json.Marshal(globalConfig)
  99. if err != nil {
  100. errmsg := fmt.Sprintf("Error marshaling JSON: %v", err)
  101. Logger.Error(errmsg)
  102. }
  103. err = json.Unmarshal(configBytes, &configMap)
  104. if err != nil {
  105. errmsg := fmt.Sprintf("Error unmarshaling JSON: %v", err)
  106. Logger.Error(errmsg)
  107. }
  108. err = persistConf(configMap)
  109. if err != nil {
  110. errmsg := fmt.Sprintf("Error persisting JSON: %v", err)
  111. Logger.Error(errmsg)
  112. }
  113. file, err = os.Open(confPath)
  114. if err != nil {
  115. errmsg := fmt.Sprintf("Error opening JSON: %v", err)
  116. Logger.Error(errmsg)
  117. }
  118. decoder = json.NewDecoder(file)
  119. err = decoder.Decode(&globalConfig)
  120. if err != nil {
  121. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  122. Logger.Error(errmsg)
  123. }
  124. }
  125. // return the global conf var
  126. func Conf() structs.SysConfig {
  127. confMutex.Lock()
  128. defer confMutex.Unlock()
  129. return globalConfig
  130. }
  131. // tell if we're amd64 or arm64
  132. func getArchitecture() string {
  133. switch runtime.GOARCH {
  134. case "arm64", "aarch64":
  135. return "arm64"
  136. default:
  137. return "amd64"
  138. }
  139. }
  140. // update by passing in a map of key:values you want to modify
  141. func UpdateConf(values map[string]interface{}) error {
  142. // mutex lock to avoid race conditions
  143. confMutex.Lock()
  144. defer confMutex.Unlock()
  145. file, err := ioutil.ReadFile(confPath)
  146. if err != nil {
  147. return fmt.Errorf("Unable to load config: %v", err)
  148. }
  149. // unmarshal the config to struct
  150. var configMap map[string]interface{}
  151. if err := json.Unmarshal(file, &configMap); err != nil {
  152. return fmt.Errorf("Error decoding JSON: %v", err)
  153. }
  154. // update our unmarshaled struct
  155. for key, value := range values {
  156. configMap[key] = value
  157. }
  158. if err = persistConf(configMap); err != nil {
  159. return fmt.Errorf("Unable to persist config update: %v", err)
  160. }
  161. return nil
  162. }
  163. func persistConf(configMap map[string]interface{}) error {
  164. // marshal and persist it
  165. updatedJSON, err := json.MarshalIndent(configMap, "", " ")
  166. if err != nil {
  167. return fmt.Errorf("Error encoding JSON: %v", err)
  168. }
  169. // update the globalConfig var
  170. if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
  171. return fmt.Errorf("Error updating global config: %v", err)
  172. }
  173. // write to disk
  174. Logger.Info("Persisting configuration to disk %v",string(updatedJson))
  175. if err := ioutil.WriteFile(confPath, updatedJSON, 0644); err != nil {
  176. return fmt.Errorf("Error writing to file: %v", err)
  177. }
  178. return nil
  179. }
  180. // we keep map[string]structs.ContainerState in memory to keep track of the containers
  181. // eg if they're running and whether they should be
  182. // modify the desired/actual state of containers
  183. func UpdateContainerState(name string, containerState structs.ContainerState) {
  184. contMutex.Lock()
  185. defer contMutex.Unlock()
  186. GSContainers[name] = containerState
  187. logMsg := "<hidden>"
  188. if DebugMode {
  189. res, _ := json.Marshal(containerState)
  190. logMsg = string(res)
  191. }
  192. Logger.Info(fmt.Sprintf("%s state:%s", name, logMsg))
  193. }
  194. // get the current container state
  195. func GetContainerState() map[string]structs.ContainerState {
  196. contMutex.Lock()
  197. defer contMutex.Unlock()
  198. return GSContainers
  199. }
  200. // write a default conf to disk
  201. func createDefaultConf() error {
  202. defaultConfig := defaults.SysConfig(BasePath)
  203. path := filepath.Join(BasePath, "settings", "system.json")
  204. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  205. return err
  206. }
  207. file, err := os.Create(path)
  208. if err != nil {
  209. return err
  210. }
  211. defer file.Close()
  212. encoder := json.NewEncoder(file)
  213. encoder.SetIndent("", " ")
  214. if err := encoder.Encode(&defaultConfig); err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. // check outbound tcp connectivity
  220. // takes ip:port
  221. func NetCheck(netCheck string) bool {
  222. internet := false
  223. timeout := 3 * time.Second
  224. conn, err := net.DialTimeout("tcp", netCheck, timeout)
  225. if err != nil {
  226. errmsg := fmt.Sprintf("Check internet access error: %v", err)
  227. Logger.Error(errmsg)
  228. } else {
  229. internet = true
  230. _ = conn.Close()
  231. }
  232. return internet
  233. }
  234. // generates a random secret string of the input length
  235. func RandString(length int) string {
  236. randBytes := make([]byte, length)
  237. _, err := rand.Read(randBytes)
  238. if err != nil {
  239. Logger.Warn("Random error :s")
  240. return ""
  241. }
  242. return base64.URLEncoding.EncodeToString(randBytes)
  243. }