broadcast.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. //wgRegistered := config.WgRegistered
  89. //wgOn := config.WgOn
  90. regions, err := startram.GetRegions()
  91. if err != nil {
  92. logger.Warn("Couldn't get StarTram regions")
  93. } else {
  94. updates := map[string]interface{}{
  95. "Profile": map[string]interface{}{
  96. "Startram": map[string]interface{}{
  97. "Info": map[string]interface{}{
  98. "Regions": regions,
  99. },
  100. },
  101. },
  102. }
  103. err := UpdateBroadcastState(updates)
  104. if err != nil {
  105. errmsg := fmt.Sprintf("Error updating broadcast state:", err)
  106. logger.Error(errmsg)
  107. }
  108. }
  109. // return the boostrapped result
  110. res = GetState()
  111. return res, nil
  112. }
  113. // update broadcastState with a map of items
  114. func UpdateBroadcastState(values map[string]interface{}) error {
  115. mu.Lock()
  116. defer mu.Unlock()
  117. v := reflect.ValueOf(&broadcastState).Elem()
  118. for key, value := range values {
  119. field := v.FieldByName(key)
  120. if !field.IsValid() || !field.CanSet() {
  121. return fmt.Errorf("field %s does not exist or is not settable", key)
  122. }
  123. val := reflect.ValueOf(value)
  124. if val.Kind() == reflect.Interface {
  125. val = val.Elem() // Extract the underlying value from the interface
  126. }
  127. if err := recursiveUpdate(field, val); err != nil {
  128. return err
  129. }
  130. }
  131. BroadcastToClients()
  132. return nil
  133. }
  134. // this allows us to insert stuff into nested structs/keys and not overwrite the existing contents
  135. func recursiveUpdate(dst, src reflect.Value) error {
  136. if !dst.CanSet() {
  137. return fmt.Errorf("field is not settable")
  138. }
  139. // If dst is a struct and src is a map, handle them field by field
  140. if dst.Kind() == reflect.Struct && src.Kind() == reflect.Map {
  141. for _, key := range src.MapKeys() {
  142. dstField := dst.FieldByName(key.String())
  143. if !dstField.IsValid() {
  144. return fmt.Errorf("field %s does not exist in the struct", key.String())
  145. }
  146. // Initialize the map if it's nil and we're trying to set a map
  147. if dstField.Kind() == reflect.Map && dstField.IsNil() && src.MapIndex(key).Kind() == reflect.Map {
  148. dstField.Set(reflect.MakeMap(dstField.Type()))
  149. }
  150. if !dstField.CanSet() {
  151. return fmt.Errorf("field %s is not settable in the struct", key.String())
  152. }
  153. srcVal := src.MapIndex(key)
  154. if srcVal.Kind() == reflect.Interface {
  155. srcVal = srcVal.Elem()
  156. }
  157. if err := recursiveUpdate(dstField, srcVal); err != nil {
  158. return err
  159. }
  160. }
  161. return nil
  162. }
  163. // If both dst and src are maps, handle them recursively
  164. if dst.Kind() == reflect.Map && src.Kind() == reflect.Map {
  165. for _, key := range src.MapKeys() {
  166. srcVal := src.MapIndex(key)
  167. // If the key doesn't exist in dst, initialize it
  168. dstVal := dst.MapIndex(key)
  169. if !dstVal.IsValid() {
  170. dstVal = reflect.New(dst.Type().Elem()).Elem()
  171. }
  172. // Recursive call to handle potential nested maps or structs
  173. if err := recursiveUpdate(dstVal, srcVal); err != nil {
  174. return err
  175. }
  176. // Initialize the map if it's nil
  177. if dst.IsNil() {
  178. dst.Set(reflect.MakeMap(dst.Type()))
  179. }
  180. dst.SetMapIndex(key, dstVal)
  181. }
  182. return nil
  183. }
  184. // For non-map or non-struct fields, or for direct updates
  185. if dst.Type() != src.Type() {
  186. return fmt.Errorf("type mismatch: expected %s, got %s", dst.Type(), src.Type())
  187. }
  188. dst.Set(src)
  189. return nil
  190. }
  191. // return broadcast state
  192. func GetState() structs.AuthBroadcast {
  193. mu.Lock()
  194. defer mu.Unlock()
  195. return broadcastState
  196. }
  197. // return json string of current broadcast state
  198. func GetStateJson() ([]byte, error) {
  199. mu.Lock()
  200. defer mu.Unlock()
  201. broadcastJson, err := json.Marshal(broadcastState)
  202. if err != nil {
  203. errmsg := fmt.Sprintf("Error marshalling response: %v", err)
  204. logger.Error(errmsg)
  205. return nil, err
  206. }
  207. return broadcastJson, nil
  208. }
  209. // broadcast the global state to all clients
  210. func BroadcastToClients() error {
  211. broadcastJson, err := json.Marshal(broadcastState)
  212. if err != nil {
  213. logger.Error("Error marshalling response:", err)
  214. return err
  215. }
  216. for client := range clients {
  217. if err := client.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  218. logger.Error("Error writing response:", err)
  219. return err
  220. }
  221. }
  222. return nil
  223. }