config.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. }
  95. // return the global conf var
  96. func Conf() structs.SysConfig {
  97. confMutex.Lock()
  98. defer confMutex.Unlock()
  99. return globalConfig
  100. }
  101. // tell if we're amd64 or arm64
  102. func getArchitecture() string {
  103. switch runtime.GOARCH {
  104. case "arm64", "aarch64":
  105. return "arm64"
  106. default:
  107. return "amd64"
  108. }
  109. }
  110. // update by passing in a map of key:values you want to modify
  111. func UpdateConf(values map[string]interface{}) error {
  112. // mutex lock to avoid race conditions
  113. confMutex.Lock()
  114. defer confMutex.Unlock()
  115. file, err := ioutil.ReadFile(confPath)
  116. if err != nil {
  117. return fmt.Errorf("Unable to load config: %v", err)
  118. }
  119. // unmarshal the config to struct
  120. var configMap map[string]interface{}
  121. if err := json.Unmarshal(file, &configMap); err != nil {
  122. return fmt.Errorf("Error decoding JSON: %v", err)
  123. }
  124. // update our unmarshaled struct
  125. for key, value := range values {
  126. configMap[key] = value
  127. }
  128. if err = persistConf(configMap); err != nil {
  129. return fmt.Errorf("Unable to persist config update: %v", err)
  130. }
  131. return nil
  132. }
  133. func persistConf(configMap map[string]interface{}) error {
  134. // marshal and persist it
  135. updatedJSON, err := json.MarshalIndent(configMap, "", " ")
  136. if err != nil {
  137. return fmt.Errorf("Error encoding JSON: %v", err)
  138. }
  139. // update the globalConfig var
  140. if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
  141. return fmt.Errorf("Error updating global config: %v", err)
  142. }
  143. // write to disk
  144. if err := ioutil.WriteFile(confPath, updatedJSON, 0644); err != nil {
  145. return fmt.Errorf("Error writing to file: %v", err)
  146. }
  147. return nil
  148. }
  149. // we keep map[string]structs.ContainerState in memory to keep track of the containers
  150. // eg if they're running and whether they should be
  151. // modify the desired/actual state of containers
  152. func UpdateContainerState(name string, containerState structs.ContainerState) {
  153. contMutex.Lock()
  154. defer contMutex.Unlock()
  155. GSContainers[name] = containerState
  156. logMsg := "<hidden>"
  157. if DebugMode {
  158. res, _ := json.Marshal(containerState)
  159. logMsg = string(res)
  160. }
  161. Logger.Info(fmt.Sprintf("%s state:%s", name, logMsg))
  162. }
  163. // get the current container state
  164. func GetContainerState() map[string]structs.ContainerState {
  165. contMutex.Lock()
  166. defer contMutex.Unlock()
  167. return GSContainers
  168. }
  169. // write a default conf to disk
  170. func createDefaultConf() error {
  171. defaultConfig := defaults.SysConfig(BasePath)
  172. path := filepath.Join(BasePath, "settings", "system.json")
  173. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  174. return err
  175. }
  176. file, err := os.Create(path)
  177. if err != nil {
  178. return err
  179. }
  180. defer file.Close()
  181. encoder := json.NewEncoder(file)
  182. encoder.SetIndent("", " ")
  183. if err := encoder.Encode(&defaultConfig); err != nil {
  184. return err
  185. }
  186. return nil
  187. }
  188. // check outbound tcp connectivity
  189. // takes ip:port
  190. func NetCheck(netCheck string) bool {
  191. internet := false
  192. timeout := 3 * time.Second
  193. conn, err := net.DialTimeout("tcp", netCheck, timeout)
  194. if err != nil {
  195. errmsg := fmt.Sprintf("Check internet access error: %v", err)
  196. Logger.Error(errmsg)
  197. } else {
  198. internet = true
  199. _ = conn.Close()
  200. }
  201. return internet
  202. }
  203. // generates a random secret string of the input length
  204. func RandString(length int) string {
  205. randBytes := make([]byte, length)
  206. _, err := rand.Read(randBytes)
  207. if err != nil {
  208. Logger.Warn("Random error :s")
  209. return ""
  210. }
  211. return base64.URLEncoding.EncodeToString(randBytes)
  212. }