broadcast.go 9.5 KB

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