broadcast.go 7.4 KB

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