broadcast.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. "os"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. "github.com/gorilla/websocket"
  15. )
  16. var (
  17. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  18. clients = make(map[*websocket.Conn]bool)
  19. broadcastState structs.AuthBroadcast
  20. mu sync.RWMutex // synchronize access to broadcastState
  21. )
  22. func init() {
  23. // initialize broadcastState global var
  24. config := config.Conf()
  25. broadcast, err := bootstrapBroadcastState(config)
  26. if err != nil {
  27. errmsg := fmt.Sprintf("Unable to initialize broadcast: %v", err)
  28. panic(errmsg)
  29. }
  30. broadcastState = broadcast
  31. }
  32. // adds ws client
  33. func RegisterClient(conn *websocket.Conn) {
  34. clients[conn] = true
  35. broadcastJson, err := GetStateJson()
  36. if err != nil {
  37. return
  38. }
  39. // when a new ws client registers, send them the current broadcast
  40. if err := conn.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  41. fmt.Println("Error writing response:", err)
  42. return
  43. }
  44. }
  45. // remove ws client
  46. func UnregisterClient(conn *websocket.Conn) {
  47. delete(clients, conn)
  48. }
  49. // take in config file and addt'l info to initialize broadcast
  50. func bootstrapBroadcastState(config structs.SysConfig) (structs.AuthBroadcast, error) {
  51. logger.Info("Bootstrapping state")
  52. var res structs.AuthBroadcast
  53. currentState := GetState()
  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. pierStatus, err := docker.GetShipStatus(piers)
  59. if err != nil {
  60. errmsg := fmt.Sprintf("Unable to bootstrap urbit states: %v", err)
  61. logger.Error(errmsg)
  62. return res, err
  63. }
  64. updates := make(map[string]structs.Urbit)
  65. // convert the running status into bools
  66. for pier, status := range pierStatus {
  67. urbit := structs.Urbit{}
  68. if existingUrbit, exists := currentState.Urbits[pier]; exists {
  69. // If the ship already exists in broadcastState, use its current state
  70. urbit = existingUrbit
  71. }
  72. isRunning := (status == "Up" || strings.HasPrefix(status, "Up "))
  73. urbit.Info.Running = isRunning
  74. updates[pier] = urbit
  75. }
  76. // update broadcastState
  77. err = UpdateBroadcastState(map[string]interface{}{
  78. "Urbits": updates,
  79. })
  80. if err != nil {
  81. errmsg := fmt.Sprintf("Unable to update broadcast state: %v", err)
  82. logger.Error(errmsg)
  83. return res, err
  84. }
  85. currentState = GetState()
  86. // get startram regions
  87. logger.Info("Retrieving StarTram region info")
  88. regions, err := startram.GetRegions()
  89. if err != nil {
  90. logger.Warn("Couldn't get StarTram regions")
  91. } else {
  92. updates := map[string]interface{}{
  93. "Profile": map[string]interface{}{
  94. "Startram": map[string]interface{}{
  95. "Info": map[string]interface{}{
  96. "Regions": regions,
  97. },
  98. },
  99. },
  100. }
  101. err := UpdateBroadcastState(updates)
  102. if err != nil {
  103. errmsg := fmt.Sprintf("Error updating broadcast state:", err)
  104. logger.Error(errmsg)
  105. }
  106. }
  107. // return the boostrapped result
  108. res = GetState()
  109. return res, nil
  110. }
  111. // update broadcastState with a map of items
  112. func UpdateBroadcastState(values map[string]interface{}) error {
  113. mu.Lock()
  114. defer mu.Unlock()
  115. v := reflect.ValueOf(&broadcastState).Elem()
  116. for key, value := range values {
  117. field := v.FieldByName(key)
  118. if !field.IsValid() || !field.CanSet() {
  119. return fmt.Errorf("field %s does not exist or is not settable", key)
  120. }
  121. val := reflect.ValueOf(value)
  122. if val.Kind() == reflect.Interface {
  123. val = val.Elem() // Extract the underlying value from the interface
  124. }
  125. if err := recursiveUpdate(field, val); err != nil {
  126. return err
  127. }
  128. }
  129. BroadcastToClients()
  130. return nil
  131. }
  132. // this allows us to insert stuff into nested vals and not overwrite the existing contents
  133. func recursiveUpdate(dst, src reflect.Value) error {
  134. if !dst.CanSet() {
  135. return fmt.Errorf("field is not settable")
  136. }
  137. // If dst is a struct and src is a map, handle them field by field
  138. if dst.Kind() == reflect.Struct && src.Kind() == reflect.Map {
  139. for _, key := range src.MapKeys() {
  140. dstField := dst.FieldByName(key.String())
  141. if !dstField.IsValid() {
  142. return fmt.Errorf("field %s does not exist in the struct", key.String())
  143. }
  144. // Initialize the map if it's nil and we're trying to set a map
  145. if dstField.Kind() == reflect.Map && dstField.IsNil() && src.MapIndex(key).Kind() == reflect.Map {
  146. dstField.Set(reflect.MakeMap(dstField.Type()))
  147. }
  148. if !dstField.CanSet() {
  149. return fmt.Errorf("field %s is not settable in the struct", key.String())
  150. }
  151. srcVal := src.MapIndex(key)
  152. if srcVal.Kind() == reflect.Interface {
  153. srcVal = srcVal.Elem()
  154. }
  155. if err := recursiveUpdate(dstField, srcVal); err != nil {
  156. return err
  157. }
  158. }
  159. return nil
  160. }
  161. // If both dst and src are maps, handle them recursively
  162. if dst.Kind() == reflect.Map && src.Kind() == reflect.Map {
  163. for _, key := range src.MapKeys() {
  164. srcVal := src.MapIndex(key)
  165. // If the key doesn't exist in dst, initialize it
  166. dstVal := dst.MapIndex(key)
  167. if !dstVal.IsValid() {
  168. dstVal = reflect.New(dst.Type().Elem()).Elem()
  169. }
  170. // Recursive call to handle potential nested maps or structs
  171. if err := recursiveUpdate(dstVal, srcVal); err != nil {
  172. return err
  173. }
  174. // Initialize the map if it's nil
  175. if dst.IsNil() {
  176. dst.Set(reflect.MakeMap(dst.Type()))
  177. }
  178. dst.SetMapIndex(key, dstVal)
  179. }
  180. return nil
  181. }
  182. // For non-map or non-struct fields, or for direct updates
  183. if dst.Type() != src.Type() {
  184. return fmt.Errorf("type mismatch: expected %s, got %s", dst.Type(), src.Type())
  185. }
  186. dst.Set(src)
  187. return nil
  188. }
  189. // return broadcast state
  190. func GetState() structs.AuthBroadcast {
  191. mu.Lock()
  192. defer mu.Unlock()
  193. return broadcastState
  194. }
  195. // return json string of current broadcast state
  196. func GetStateJson() ([]byte, error) {
  197. mu.Lock()
  198. defer mu.Unlock()
  199. broadcastJson, err := json.Marshal(broadcastState)
  200. if err != nil {
  201. errmsg := fmt.Sprintf("Error marshalling response: %v", err)
  202. logger.Error(errmsg)
  203. return nil, err
  204. }
  205. return broadcastJson, nil
  206. }
  207. // broadcast the global state to all clients
  208. func BroadcastToClients() error {
  209. broadcastJson, err := json.Marshal(broadcastState)
  210. if err != nil {
  211. logger.Error("Error marshalling response:", err)
  212. return err
  213. }
  214. for client := range clients {
  215. if err := client.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  216. logger.Error("Error writing response:", err)
  217. return err
  218. }
  219. }
  220. return nil
  221. }