broadcast.go 7.9 KB

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