broadcast.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package broadcast
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "goseg/auth"
  6. "goseg/config"
  7. "goseg/docker"
  8. "goseg/startram"
  9. "goseg/structs"
  10. "goseg/system"
  11. "log/slog"
  12. "math"
  13. "os"
  14. "reflect"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/gorilla/websocket"
  19. )
  20. var (
  21. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  22. clients = make(map[*websocket.Conn]bool)
  23. hostInfoInterval = 3 * time.Second // how often we refresh system info
  24. shipInfoInterval = 3 * time.Second // how often we refresh ship info
  25. broadcastState structs.AuthBroadcast
  26. unauthState structs.UnauthBroadcast
  27. mu sync.RWMutex // synchronize access to broadcastState
  28. )
  29. func init() {
  30. // initialize broadcastState global var
  31. config := config.Conf()
  32. broadcast, err := bootstrapBroadcastState(config)
  33. if err != nil {
  34. errmsg := fmt.Sprintf("Unable to initialize broadcast: %v", err)
  35. panic(errmsg)
  36. }
  37. broadcastState = broadcast
  38. }
  39. // adds ws client
  40. func RegisterClient(conn *websocket.Conn) {
  41. clients[conn] = true
  42. broadcastJson, err := GetStateJson()
  43. if err != nil {
  44. return
  45. }
  46. // when a new ws client registers, send them the current broadcast
  47. if err := conn.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  48. fmt.Println("Error writing response:", err)
  49. return
  50. }
  51. }
  52. // remove ws client
  53. func UnregisterClient(conn *websocket.Conn) {
  54. delete(clients, conn)
  55. }
  56. // take in config file and addt'l info to initialize broadcast
  57. func bootstrapBroadcastState(config structs.SysConfig) (structs.AuthBroadcast, error) {
  58. logger.Info("Bootstrapping state")
  59. var res structs.AuthBroadcast
  60. // get a list of piers from config
  61. piers := config.Piers
  62. // this returns a map of ship:running status
  63. logger.Info("Resolving pier status")
  64. updates, err := constructPierInfo(piers)
  65. if err != nil {
  66. return res, err
  67. }
  68. // update broadcastState
  69. err = UpdateBroadcastState(map[string]interface{}{
  70. "Urbits": updates,
  71. })
  72. if err != nil {
  73. errmsg := fmt.Sprintf("Unable to update broadcast state: %v", err)
  74. logger.Error(errmsg)
  75. return res, err
  76. }
  77. // wgRegistered := config.WgRegistered
  78. // wgOn := config.WgOn
  79. // get startram regions
  80. logger.Info("Retrieving StarTram region info")
  81. regions, err := startram.GetRegions()
  82. if err != nil {
  83. logger.Warn("Couldn't get StarTram regions")
  84. } else {
  85. updates := map[string]interface{}{
  86. "Profile": map[string]interface{}{
  87. "Startram": map[string]interface{}{
  88. "Info": map[string]interface{}{
  89. "Regions": regions,
  90. },
  91. },
  92. },
  93. }
  94. err := UpdateBroadcastState(updates)
  95. if err != nil {
  96. errmsg := fmt.Sprintf("Error updating broadcast state:", err)
  97. logger.Error(errmsg)
  98. }
  99. }
  100. // update with system state
  101. sysInfo := constructSystemInfo()
  102. err = UpdateBroadcastState(sysInfo)
  103. if err != nil {
  104. errmsg := fmt.Sprintf("Error updating broadcast state:", err)
  105. logger.Error(errmsg)
  106. }
  107. // start looping info refreshes
  108. go hostStatusLoop()
  109. go shipStatusLoop()
  110. // return the boostrapped result
  111. res = GetState()
  112. return res, nil
  113. }
  114. // this is for building the broadcast objects describing piers
  115. func constructPierInfo(piers []string) (map[string]structs.Urbit, error) {
  116. updates := make(map[string]structs.Urbit)
  117. // load fresh broadcast state
  118. currentState := GetState()
  119. // get the networks containers are attached to
  120. shipNetworks := GetContainerNetworks(piers)
  121. // find out whether they're running
  122. pierStatus, err := docker.GetShipStatus(piers)
  123. if err != nil {
  124. errmsg := fmt.Sprintf("Unable to bootstrap urbit states: %v", err)
  125. logger.Error(errmsg)
  126. return updates, err
  127. }
  128. hostName, err := os.Hostname()
  129. if err != nil {
  130. errmsg := fmt.Sprintf("Error getting hostname, defaulting to `nativeplanet`: %v", err)
  131. logger.Warn(errmsg)
  132. hostName = "nativeplanet"
  133. }
  134. // convert the running status into bools
  135. for pier, status := range pierStatus {
  136. // pull urbit info from json
  137. err := config.LoadUrbitConfig(pier)
  138. if err != nil {
  139. errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
  140. logger.Error(errmsg)
  141. continue
  142. }
  143. dockerConfig := config.UrbitConf(pier)
  144. // get container stats from docker
  145. var dockerStats structs.ContainerStats
  146. dockerStats, err = docker.GetContainerStats(pier)
  147. if err != nil {
  148. errmsg := fmt.Sprintf("Unable to load %s stats: %v", pier, err)
  149. logger.Error(errmsg)
  150. continue
  151. }
  152. urbit := structs.Urbit{}
  153. if existingUrbit, exists := currentState.Urbits[pier]; exists {
  154. // If the ship already exists in broadcastState, use its current state
  155. urbit = existingUrbit
  156. }
  157. isRunning := (status == "Up" || strings.HasPrefix(status, "Up "))
  158. bootStatus := true
  159. if dockerConfig.BootStatus == "ignore" {
  160. bootStatus = false
  161. }
  162. setRemote := false
  163. if dockerConfig.Network == "wireguard" {
  164. setRemote = true
  165. }
  166. // collate all the info from our sources into the struct
  167. urbit.Info.Running = isRunning
  168. urbit.Info.Network = shipNetworks[pier]
  169. urbit.Info.URL = fmt.Sprintf("http://%s.local:%d", hostName, dockerConfig.HTTPPort)
  170. urbit.Info.LoomSize = int(math.Pow(2, float64(dockerConfig.LoomSize)) / math.Pow(1024, 2))
  171. urbit.Info.DiskUsage = dockerStats.DiskUsage
  172. urbit.Info.MemUsage = dockerStats.MemoryUsage
  173. urbit.Info.DevMode = dockerConfig.DevMode
  174. urbit.Info.Vere = dockerConfig.UrbitVersion
  175. urbit.Info.DetectBootStatus = bootStatus
  176. urbit.Info.Remote = setRemote
  177. urbit.Info.Vere = dockerConfig.UrbitVersion
  178. // and insert the struct into the map we will use as input for the broadcast struct
  179. updates[pier] = urbit
  180. }
  181. return updates, nil
  182. }
  183. // put together the system[usage] subobject
  184. func constructSystemInfo() map[string]interface{} {
  185. var res map[string]interface{}
  186. var ramObj []uint64
  187. var diskObj []uint64
  188. usedRam, totalRam := system.GetMemory()
  189. ramObj = append(ramObj, usedRam, totalRam)
  190. cpuUsage := system.GetCPU()
  191. cpuTemp := system.GetTemp()
  192. usedDisk, freeDisk := system.GetDisk()
  193. diskObj = append(diskObj, usedDisk, freeDisk)
  194. swapVal := system.HasSwap()
  195. res = map[string]interface{}{
  196. "System": map[string]interface{}{
  197. "Usage": map[string]interface{}{
  198. "RAM": ramObj,
  199. "CPU": cpuUsage,
  200. "CPUTemp": cpuTemp,
  201. "Disk": diskObj,
  202. "SwapFile": swapVal,
  203. },
  204. },
  205. }
  206. return res
  207. }
  208. // return a map of ships and their networks
  209. func GetContainerNetworks(containers []string) map[string]string {
  210. res := make(map[string]string)
  211. for _, container := range containers {
  212. network, err := docker.GetContainerNetwork(container)
  213. if err != nil {
  214. errmsg := fmt.Sprintf("Error getting container network: %v", err)
  215. logger.Error(errmsg)
  216. continue
  217. } else {
  218. res[container] = network
  219. }
  220. }
  221. return res
  222. }
  223. // update broadcastState with a map of items
  224. func UpdateBroadcastState(values map[string]interface{}) error {
  225. mu.Lock()
  226. defer mu.Unlock()
  227. v := reflect.ValueOf(&broadcastState).Elem()
  228. for key, value := range values {
  229. field := v.FieldByName(key)
  230. if !field.IsValid() || !field.CanSet() {
  231. return fmt.Errorf("field %s does not exist or is not settable", key)
  232. }
  233. val := reflect.ValueOf(value)
  234. if val.Kind() == reflect.Interface {
  235. val = val.Elem() // Extract the underlying value from the interface
  236. }
  237. if err := recursiveUpdate(field, val); err != nil {
  238. return err
  239. }
  240. }
  241. BroadcastToClients()
  242. return nil
  243. }
  244. // this allows us to insert stuff into nested structs/keys and not overwrite the existing contents
  245. func recursiveUpdate(dst, src reflect.Value) error {
  246. if !dst.CanSet() {
  247. return fmt.Errorf("field is not settable")
  248. }
  249. // If dst is a struct and src is a map, handle them field by field
  250. if dst.Kind() == reflect.Struct && src.Kind() == reflect.Map {
  251. for _, key := range src.MapKeys() {
  252. dstField := dst.FieldByName(key.String())
  253. if !dstField.IsValid() {
  254. return fmt.Errorf("field %s does not exist in the struct", key.String())
  255. }
  256. // Initialize the map if it's nil and we're trying to set a map
  257. if dstField.Kind() == reflect.Map && dstField.IsNil() && src.MapIndex(key).Kind() == reflect.Map {
  258. dstField.Set(reflect.MakeMap(dstField.Type()))
  259. }
  260. if !dstField.CanSet() {
  261. return fmt.Errorf("field %s is not settable in the struct", key.String())
  262. }
  263. srcVal := src.MapIndex(key)
  264. if srcVal.Kind() == reflect.Interface {
  265. srcVal = srcVal.Elem()
  266. }
  267. if err := recursiveUpdate(dstField, srcVal); err != nil {
  268. return err
  269. }
  270. }
  271. return nil
  272. }
  273. // If both dst and src are maps, handle them recursively
  274. if dst.Kind() == reflect.Map && src.Kind() == reflect.Map {
  275. for _, key := range src.MapKeys() {
  276. srcVal := src.MapIndex(key)
  277. // If the key doesn't exist in dst, initialize it
  278. dstVal := dst.MapIndex(key)
  279. if !dstVal.IsValid() {
  280. dstVal = reflect.New(dst.Type().Elem()).Elem()
  281. }
  282. // Recursive call to handle potential nested maps or structs
  283. if err := recursiveUpdate(dstVal, srcVal); err != nil {
  284. return err
  285. }
  286. // Initialize the map if it's nil
  287. if dst.IsNil() {
  288. dst.Set(reflect.MakeMap(dst.Type()))
  289. }
  290. dst.SetMapIndex(key, dstVal)
  291. }
  292. return nil
  293. }
  294. // For non-map or non-struct fields, or for direct updates
  295. if dst.Type() != src.Type() {
  296. return fmt.Errorf("type mismatch: expected %s, got %s", dst.Type(), src.Type())
  297. }
  298. dst.Set(src)
  299. return nil
  300. }
  301. // return broadcast state
  302. func GetState() structs.AuthBroadcast {
  303. mu.Lock()
  304. defer mu.Unlock()
  305. return broadcastState
  306. }
  307. // return json string of current broadcast state
  308. func GetStateJson() ([]byte, error) {
  309. mu.Lock()
  310. defer mu.Unlock()
  311. bState := GetState()
  312. broadcastJson, err := json.Marshal(bState)
  313. if err != nil {
  314. errmsg := fmt.Sprintf("Error marshalling response: %v", err)
  315. logger.Error(errmsg)
  316. return nil, err
  317. }
  318. return broadcastJson, nil
  319. }
  320. // broadcast the global state to auth'd clients
  321. func BroadcastToClients() error {
  322. authJson, err := GetStateJson()
  323. if err != nil {
  324. errmsg := fmt.Errorf("Error marshalling auth broadcast:", err)
  325. return errmsg
  326. }
  327. auth.AuthenticatedClients.Lock()
  328. defer auth.AuthenticatedClients.Unlock()
  329. for client := range auth.AuthenticatedClients.Conns {
  330. if err := client.WriteMessage(websocket.TextMessage, authJson); err != nil {
  331. logger.Error(fmt.Sprintf("Error writing response: %v", err))
  332. return err
  333. }
  334. }
  335. return nil
  336. }
  337. // refresh loop for host info
  338. func hostStatusLoop() {
  339. ticker := time.NewTicker(hostInfoInterval)
  340. for {
  341. select {
  342. case <-ticker.C:
  343. update := constructSystemInfo()
  344. err := UpdateBroadcastState(update)
  345. if err != nil {
  346. logger.Warn(fmt.Sprintf("Error updating system status: %v", err))
  347. }
  348. }
  349. }
  350. }
  351. // refresh loop for ship info
  352. func shipStatusLoop() {
  353. ticker := time.NewTicker(hostInfoInterval)
  354. for {
  355. select {
  356. case <-ticker.C:
  357. updates, err := constructPierInfo(piers)
  358. if err != nil {
  359. return res, err
  360. }
  361. // update broadcastState
  362. err = UpdateBroadcastState(map[string]interface{}{
  363. "Urbits": updates,
  364. })
  365. if err != nil {
  366. errmsg := fmt.Sprintf("Unable to update ship state: %v", err)
  367. logger.Error(errmsg)
  368. return res, err
  369. }
  370. }
  371. }
  372. }