config.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. res, _ := json.Marshal(containerState)
  118. logger.Info(fmt.Sprintf("%s:%s", name, string(res)))
  119. }
  120. // get the current container state
  121. func GetContainerState() map[string]structs.ContainerState {
  122. contMutex.Lock()
  123. defer contMutex.Unlock()
  124. return GSContainers
  125. }
  126. // write a default conf to disk
  127. func createDefaultConf() error {
  128. defaultConfig := structs.SysConfig{
  129. Setup: "start",
  130. EndpointUrl: "api.startram.io",
  131. ApiVersion: "v1",
  132. Piers: []string{},
  133. NetCheck: "1.1.1.1:53",
  134. UpdateMode: "auto",
  135. UpdateUrl: "https://version.groundseg.app",
  136. UpdateBranch: "latest",
  137. SwapVal: 16,
  138. SwapFile: filepath.Join(BasePath, "settings", "swapfile"),
  139. KeyFile: filepath.Join(BasePath, "settings", "session.key"),
  140. Sessions: struct {
  141. Authorized map[string]structs.SessionInfo `json:"authorized"`
  142. Unauthorized map[string]structs.SessionInfo `json:"unauthorized"`
  143. }{
  144. Authorized: make(map[string]structs.SessionInfo),
  145. Unauthorized: make(map[string]structs.SessionInfo),
  146. },
  147. LinuxUpdates: struct {
  148. Value int `json:"value"`
  149. Interval string `json:"interval"`
  150. Previous bool `json:"previous"`
  151. }{
  152. Value: 1,
  153. Interval: "week",
  154. Previous: false,
  155. },
  156. DockerData: "/var/lib/docker",
  157. WgOn: false,
  158. WgRegistered: false,
  159. PwHash: "",
  160. C2cInterval: 0,
  161. FirstBoot: false,
  162. WgRegisterd: false,
  163. GsVersion: Version,
  164. CfgDir: "",
  165. UpdateInterval: 0,
  166. BinHash: "",
  167. Pubkey: "",
  168. Privkey: "",
  169. Salt: "",
  170. }
  171. path := filepath.Join(BasePath, "settings", "system.json")
  172. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  173. return err
  174. }
  175. file, err := os.Create(path)
  176. if err != nil {
  177. return err
  178. }
  179. defer file.Close()
  180. encoder := json.NewEncoder(file)
  181. encoder.SetIndent("", " ")
  182. if err := encoder.Encode(&defaultConfig); err != nil {
  183. return err
  184. }
  185. return nil
  186. }
  187. // check outbound tcp connectivity
  188. // takes ip:port
  189. func NetCheck(netCheck string) bool {
  190. logger.Info("Checking internet access")
  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. // check the version server and return unmarshaled result
  204. func CheckVersion() (structs.Version, bool) {
  205. versMutex.Lock()
  206. defer versMutex.Unlock()
  207. const retries = 10
  208. const delay = time.Second
  209. url := globalConfig.UpdateUrl
  210. for i := 0; i < retries; i++ {
  211. resp, err := http.Get(url)
  212. if err != nil {
  213. errmsg := fmt.Sprintf("Unable to connect to update server: %v", err)
  214. logger.Warn(errmsg)
  215. if i < retries-1 {
  216. time.Sleep(delay)
  217. continue
  218. } else {
  219. return VersionInfo, false
  220. }
  221. }
  222. // read the body bytes
  223. body, err := ioutil.ReadAll(resp.Body)
  224. resp.Body.Close()
  225. if err != nil {
  226. errmsg := fmt.Sprintf("Error reading version info: %v", err)
  227. logger.Warn(errmsg)
  228. if i < retries-1 {
  229. time.Sleep(delay)
  230. continue
  231. } else {
  232. return VersionInfo, false
  233. }
  234. }
  235. // unmarshal values into Version struct
  236. err = json.Unmarshal(body, &VersionInfo)
  237. if err != nil {
  238. errmsg := fmt.Sprintf("Error unmarshalling JSON: %v", err)
  239. logger.Warn(errmsg)
  240. if i < retries-1 {
  241. time.Sleep(delay)
  242. continue
  243. } else {
  244. return VersionInfo, false
  245. }
  246. }
  247. // debug: re-marshal and write to disk
  248. confPath := filepath.Join(BasePath, "settings", "version_info.json")
  249. file, err := os.Create(confPath)
  250. if err != nil {
  251. errmsg := fmt.Sprintf("Failed to create file: %v", err)
  252. logger.Error(errmsg)
  253. return VersionInfo, false
  254. }
  255. defer file.Close()
  256. encoder := json.NewEncoder(file)
  257. encoder.SetIndent("", " ")
  258. if err := encoder.Encode(&VersionInfo); err != nil {
  259. errmsg := fmt.Sprintf("Failed to write JSON: %v", err)
  260. logger.Error(errmsg)
  261. }
  262. return VersionInfo, true
  263. }
  264. return VersionInfo, false
  265. }
  266. func CheckVersionLoop() {
  267. ticker := time.NewTicker(checkInterval)
  268. for {
  269. select {
  270. case <-ticker.C:
  271. latestVersion, _ := CheckVersion()
  272. currentVersion := VersionInfo
  273. if latestVersion != currentVersion {
  274. fmt.Printf("New version available! Current: %s, Latest: %s\n", currentVersion, latestVersion)
  275. // Handle the update logic here
  276. }
  277. }
  278. }
  279. }