config.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "goseg/structs"
  6. "io/ioutil"
  7. "log/slog"
  8. "net"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "sync"
  14. "time"
  15. )
  16. var (
  17. globalConfig structs.SysConfig
  18. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  19. BasePath = "/opt/nativeplanet/groundseg"
  20. Version = "v2.0.0"
  21. Architecture string
  22. Ready = false
  23. VersionServerReady = false
  24. VersionInfo structs.Version
  25. GSContainers = make(map[string]structs.ContainerState)
  26. checkInterval = 5 * time.Minute
  27. confMutex sync.Mutex
  28. contMutex sync.Mutex
  29. versMutex sync.Mutex
  30. )
  31. // try initializing from system.json on disk
  32. func init() {
  33. pathMsg := fmt.Sprintf("Loading configs from %s", BasePath)
  34. logger.Info(pathMsg)
  35. confPath := filepath.Join(BasePath, "settings", "system.json")
  36. file, err := os.Open(confPath)
  37. if err != nil {
  38. // create a default if it doesn't exist
  39. err = createDefaultConf()
  40. if err != nil {
  41. errmsg := fmt.Sprintf("Unable to create config! %v", err)
  42. logger.Error(errmsg)
  43. }
  44. }
  45. defer file.Close()
  46. decoder := json.NewDecoder(file)
  47. err = decoder.Decode(&globalConfig)
  48. if err != nil {
  49. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  50. logger.Error(errmsg)
  51. }
  52. Architecture = getArchitecture()
  53. }
  54. // return the global conf var
  55. func Conf() structs.SysConfig {
  56. confMutex.Lock()
  57. defer confMutex.Unlock()
  58. return globalConfig
  59. }
  60. // tell if we're amd64 or arm64
  61. func getArchitecture() string {
  62. switch runtime.GOARCH {
  63. case "arm64", "aarch64":
  64. return "arm64"
  65. default:
  66. return "amd64"
  67. }
  68. }
  69. // update by passing in a map of key:values you want to modify
  70. func UpdateConf(values map[string]interface{}) error {
  71. // mutex lock to avoid race conditions
  72. confMutex.Lock()
  73. defer confMutex.Unlock()
  74. confPath := filepath.Join(BasePath, "settings", "system.json")
  75. file, err := ioutil.ReadFile(confPath)
  76. if err != nil {
  77. errmsg := fmt.Sprintf("Unable to load config: %v", err)
  78. logger.Error(errmsg)
  79. return err
  80. }
  81. // unmarshal the config to struct
  82. var configMap map[string]interface{}
  83. if err := json.Unmarshal(file, &configMap); err != nil {
  84. errmsg := fmt.Sprintf("Error decoding JSON: %v", err)
  85. logger.Error(errmsg)
  86. return err
  87. }
  88. // update our unmarshaled struct
  89. for key, value := range values {
  90. configMap[key] = value
  91. }
  92. // marshal and persist it
  93. updatedJSON, err := json.MarshalIndent(configMap, "", " ")
  94. if err != nil {
  95. errmsg := fmt.Sprintf("Error encoding JSON: %v", err)
  96. logger.Error(errmsg)
  97. return err
  98. }
  99. // update the globalConfig var
  100. if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
  101. errmsg := fmt.Sprintf("Error updating global config: %v", err)
  102. logger.Error(errmsg)
  103. return err
  104. }
  105. if err := ioutil.WriteFile(confPath, updatedJSON, 0644); err != nil {
  106. errmsg := fmt.Sprintf("Error writing to file: %v", err)
  107. logger.Error(errmsg)
  108. return err
  109. }
  110. return nil
  111. }
  112. // modify the desired/actual state of containers
  113. func UpdateContainerState(name string, containerState structs.ContainerState) {
  114. contMutex.Lock()
  115. defer contMutex.Unlock()
  116. GSContainers[name] = containerState
  117. }
  118. // get the current container state
  119. func GetContainerState() map[string]structs.ContainerState {
  120. contMutex.Lock()
  121. defer contMutex.Unlock()
  122. return GSContainers
  123. }
  124. // write a default conf to disk
  125. func createDefaultConf() error {
  126. defaultConfig := structs.SysConfig{
  127. Setup: "start",
  128. EndpointUrl: "api.startram.io",
  129. ApiVersion: "v1",
  130. Piers: []string{},
  131. NetCheck: "1.1.1.1:53",
  132. UpdateMode: "auto",
  133. UpdateUrl: "https://version.groundseg.app",
  134. UpdateBranch: "latest",
  135. SwapVal: 16,
  136. SwapFile: filepath.Join(BasePath, "settings", "swapfile"),
  137. KeyFile: filepath.Join(BasePath, "settings", "session.key"),
  138. Sessions: struct {
  139. Authorized map[string]structs.SessionInfo `json:"authorized"`
  140. Unauthorized map[string]structs.SessionInfo `json:"unauthorized"`
  141. }{
  142. Authorized: make(map[string]structs.SessionInfo),
  143. Unauthorized: make(map[string]structs.SessionInfo),
  144. },
  145. LinuxUpdates: struct {
  146. Value int `json:"value"`
  147. Interval string `json:"interval"`
  148. Previous bool `json:"previous"`
  149. }{
  150. Value: 1,
  151. Interval: "week",
  152. Previous: false,
  153. },
  154. DockerData: "/var/lib/docker",
  155. WgOn: false,
  156. WgRegistered: false,
  157. PwHash: "",
  158. C2cInterval: 0,
  159. FirstBoot: false,
  160. WgRegisterd: false,
  161. GsVersion: Version,
  162. CfgDir: "",
  163. UpdateInterval: 0,
  164. BinHash: "",
  165. Pubkey: "",
  166. Privkey: "",
  167. Salt: "",
  168. }
  169. path := filepath.Join(BasePath, "settings", "system.json")
  170. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  171. return err
  172. }
  173. file, err := os.Create(path)
  174. if err != nil {
  175. return err
  176. }
  177. defer file.Close()
  178. encoder := json.NewEncoder(file)
  179. encoder.SetIndent("", " ")
  180. if err := encoder.Encode(&defaultConfig); err != nil {
  181. return err
  182. }
  183. return nil
  184. }
  185. // check outbound tcp connectivity
  186. // takes ip:port
  187. func NetCheck(netCheck string) bool {
  188. logger.Info("Checking internet access")
  189. internet := false
  190. timeout := 3 * time.Second
  191. conn, err := net.DialTimeout("tcp", netCheck, timeout)
  192. if err != nil {
  193. errmsg := fmt.Sprintf("Check internet access error: %v", err)
  194. logger.Error(errmsg)
  195. } else {
  196. internet = true
  197. _ = conn.Close()
  198. }
  199. return internet
  200. }
  201. // check the version server and return unmarshaled result
  202. func CheckVersion() (structs.Version, bool) {
  203. versMutex.Lock()
  204. defer versMutex.Unlock()
  205. const retries = 10
  206. const delay = time.Second
  207. url := globalConfig.UpdateUrl
  208. for i := 0; i < retries; i++ {
  209. resp, err := http.Get(url)
  210. if err != nil {
  211. errmsg := fmt.Sprintf("Unable to connect to update server: %v", err)
  212. logger.Warn(errmsg)
  213. if i < retries-1 {
  214. time.Sleep(delay)
  215. continue
  216. } else {
  217. return VersionInfo, false
  218. }
  219. }
  220. // read the body bytes
  221. body, err := ioutil.ReadAll(resp.Body)
  222. resp.Body.Close()
  223. if err != nil {
  224. errmsg := fmt.Sprintf("Error reading version info: %v", err)
  225. logger.Warn(errmsg)
  226. if i < retries-1 {
  227. time.Sleep(delay)
  228. continue
  229. } else {
  230. return VersionInfo, false
  231. }
  232. }
  233. // unmarshal values into Version struct
  234. err = json.Unmarshal(body, &VersionInfo)
  235. if err != nil {
  236. errmsg := fmt.Sprintf("Error unmarshalling JSON: %v", err)
  237. logger.Warn(errmsg)
  238. if i < retries-1 {
  239. time.Sleep(delay)
  240. continue
  241. } else {
  242. return VersionInfo, false
  243. }
  244. }
  245. // debug: re-marshal and write to disk
  246. confPath := filepath.Join(BasePath, "settings", "version_info.json")
  247. file, err := os.Create(confPath)
  248. if err != nil {
  249. errmsg := fmt.Sprintf("Failed to create file: %v", err)
  250. logger.Error(errmsg)
  251. return VersionInfo, false
  252. }
  253. defer file.Close()
  254. encoder := json.NewEncoder(file)
  255. encoder.SetIndent("", " ")
  256. if err := encoder.Encode(&VersionInfo); err != nil {
  257. errmsg := fmt.Sprintf("Failed to write JSON: %v", err)
  258. logger.Error(errmsg)
  259. }
  260. return VersionInfo, true
  261. }
  262. return VersionInfo, false
  263. }
  264. func CheckVersionLoop() {
  265. ticker := time.NewTicker(checkInterval)
  266. for {
  267. select {
  268. case <-ticker.C:
  269. latestVersion, _ := CheckVersion()
  270. currentVersion := VersionInfo
  271. if latestVersion != currentVersion {
  272. fmt.Printf("New version available! Current: %s, Latest: %s\n", currentVersion, latestVersion)
  273. // Handle the update logic here
  274. }
  275. }
  276. }
  277. }