broadcast.go 8.2 KB

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