broadcast.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. err := docker.LoadConfig(pier)
  118. if err != nil {
  119. errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
  120. logger.Error(errmsg)
  121. continue
  122. }
  123. dockerConfig := docker.Conf(pier)
  124. // pull docker info from json
  125. var dockerStats structs.ContainerStats
  126. dockerStats, err := docker.GetContainerStats(pier)
  127. if err != nil {
  128. errmsg := fmt.Sprintf("Unable to load %s stats: %v", pier, err)
  129. logger.Error(errmsg)
  130. continue
  131. }
  132. urbit := structs.Urbit{}
  133. if existingUrbit, exists := currentState.Urbits[pier]; exists {
  134. // If the ship already exists in broadcastState, use its current state
  135. urbit = existingUrbit
  136. }
  137. isRunning := (status == "Up" || strings.HasPrefix(status, "Up "))
  138. bootStatus := true
  139. if dockerConfig.BootStatus == "ignore" {
  140. bootStatus = false
  141. }
  142. setRemote := false
  143. if dockerConfig.Network == "wireguard" {
  144. setRemote = true
  145. }
  146. urbit.Info.Running = isRunning
  147. urbit.Info.Network = shipNetworks[pier]
  148. urbit.Info.URL = fmt.Sprintf("http://%s.local:%d", hostName, dockerConfig.HTTPPort)
  149. urbit.Info.LoomSize = int(math.Pow(2, float64(dockerConfig.LoomSize)) / math.Pow(1024, 2))
  150. urbit.Info.DiskUsage = dockerStats.DiskUsage
  151. urbit.Info.MemUsage = dockerStats.MemoryUsage
  152. urbit.Info.DevMode = dockerConfig.DevMode
  153. urbit.Info.Vere = dockerConfig.UrbitVersion
  154. urbit.Info.DetectBootStatus = bootStatus
  155. urbit.Info.Remote = setRemote
  156. urbit.Info.Vere = dockerConfig.UrbitVersion
  157. updates[pier] = urbit
  158. }
  159. return updates, nil
  160. }
  161. // return a map of ships and their networks
  162. func GetContainerNetworks(containers []string) map[string]string {
  163. res := make(map[string]string)
  164. for _, container := range containers {
  165. network, err := docker.GetContainerNetwork(container)
  166. if err != nil {
  167. errmsg := fmt.Sprintf("Error getting container network: %v", err)
  168. logger.Error(errmsg)
  169. continue
  170. } else {
  171. res[container] = network
  172. }
  173. }
  174. return res
  175. }
  176. // update broadcastState with a map of items
  177. func UpdateBroadcastState(values map[string]interface{}) error {
  178. mu.Lock()
  179. defer mu.Unlock()
  180. v := reflect.ValueOf(&broadcastState).Elem()
  181. for key, value := range values {
  182. field := v.FieldByName(key)
  183. if !field.IsValid() || !field.CanSet() {
  184. return fmt.Errorf("field %s does not exist or is not settable", key)
  185. }
  186. val := reflect.ValueOf(value)
  187. if val.Kind() == reflect.Interface {
  188. val = val.Elem() // Extract the underlying value from the interface
  189. }
  190. if err := recursiveUpdate(field, val); err != nil {
  191. return err
  192. }
  193. }
  194. BroadcastToClients()
  195. return nil
  196. }
  197. // this allows us to insert stuff into nested structs/keys and not overwrite the existing contents
  198. func recursiveUpdate(dst, src reflect.Value) error {
  199. if !dst.CanSet() {
  200. return fmt.Errorf("field is not settable")
  201. }
  202. // If dst is a struct and src is a map, handle them field by field
  203. if dst.Kind() == reflect.Struct && src.Kind() == reflect.Map {
  204. for _, key := range src.MapKeys() {
  205. dstField := dst.FieldByName(key.String())
  206. if !dstField.IsValid() {
  207. return fmt.Errorf("field %s does not exist in the struct", key.String())
  208. }
  209. // Initialize the map if it's nil and we're trying to set a map
  210. if dstField.Kind() == reflect.Map && dstField.IsNil() && src.MapIndex(key).Kind() == reflect.Map {
  211. dstField.Set(reflect.MakeMap(dstField.Type()))
  212. }
  213. if !dstField.CanSet() {
  214. return fmt.Errorf("field %s is not settable in the struct", key.String())
  215. }
  216. srcVal := src.MapIndex(key)
  217. if srcVal.Kind() == reflect.Interface {
  218. srcVal = srcVal.Elem()
  219. }
  220. if err := recursiveUpdate(dstField, srcVal); err != nil {
  221. return err
  222. }
  223. }
  224. return nil
  225. }
  226. // If both dst and src are maps, handle them recursively
  227. if dst.Kind() == reflect.Map && src.Kind() == reflect.Map {
  228. for _, key := range src.MapKeys() {
  229. srcVal := src.MapIndex(key)
  230. // If the key doesn't exist in dst, initialize it
  231. dstVal := dst.MapIndex(key)
  232. if !dstVal.IsValid() {
  233. dstVal = reflect.New(dst.Type().Elem()).Elem()
  234. }
  235. // Recursive call to handle potential nested maps or structs
  236. if err := recursiveUpdate(dstVal, srcVal); err != nil {
  237. return err
  238. }
  239. // Initialize the map if it's nil
  240. if dst.IsNil() {
  241. dst.Set(reflect.MakeMap(dst.Type()))
  242. }
  243. dst.SetMapIndex(key, dstVal)
  244. }
  245. return nil
  246. }
  247. // For non-map or non-struct fields, or for direct updates
  248. if dst.Type() != src.Type() {
  249. return fmt.Errorf("type mismatch: expected %s, got %s", dst.Type(), src.Type())
  250. }
  251. dst.Set(src)
  252. return nil
  253. }
  254. // return broadcast state
  255. func GetState() structs.AuthBroadcast {
  256. mu.Lock()
  257. defer mu.Unlock()
  258. return broadcastState
  259. }
  260. // return json string of current broadcast state
  261. func GetStateJson() ([]byte, error) {
  262. mu.Lock()
  263. defer mu.Unlock()
  264. broadcastJson, err := json.Marshal(broadcastState)
  265. if err != nil {
  266. errmsg := fmt.Sprintf("Error marshalling response: %v", err)
  267. logger.Error(errmsg)
  268. return nil, err
  269. }
  270. return broadcastJson, nil
  271. }
  272. // broadcast the global state to all clients
  273. func BroadcastToClients() error {
  274. broadcastJson, err := json.Marshal(broadcastState)
  275. if err != nil {
  276. logger.Error("Error marshalling response:", err)
  277. return err
  278. }
  279. for client := range clients {
  280. if err := client.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  281. logger.Error("Error writing response:", err)
  282. return err
  283. }
  284. }
  285. return nil
  286. }