broadcast.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package broadcast
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "goseg/config"
  6. "goseg/docker"
  7. "goseg/startram"
  8. "goseg/structs"
  9. "goseg/system"
  10. "log/slog"
  11. "math"
  12. "os"
  13. "reflect"
  14. "strings"
  15. "sync"
  16. "github.com/gorilla/websocket"
  17. )
  18. var (
  19. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  20. clients = make(map[*websocket.Conn]bool)
  21. broadcastState structs.AuthBroadcast
  22. mu sync.RWMutex // synchronize access to broadcastState
  23. )
  24. func init() {
  25. // initialize broadcastState global var
  26. config := config.Conf()
  27. broadcast, err := bootstrapBroadcastState(config)
  28. if err != nil {
  29. errmsg := fmt.Sprintf("Unable to initialize broadcast: %v", err)
  30. panic(errmsg)
  31. }
  32. broadcastState = broadcast
  33. }
  34. // adds ws client
  35. func RegisterClient(conn *websocket.Conn) {
  36. clients[conn] = true
  37. broadcastJson, err := GetStateJson()
  38. if err != nil {
  39. return
  40. }
  41. // when a new ws client registers, send them the current broadcast
  42. if err := conn.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  43. fmt.Println("Error writing response:", err)
  44. return
  45. }
  46. }
  47. // remove ws client
  48. func UnregisterClient(conn *websocket.Conn) {
  49. delete(clients, conn)
  50. }
  51. // take in config file and addt'l info to initialize broadcast
  52. func bootstrapBroadcastState(config structs.SysConfig) (structs.AuthBroadcast, error) {
  53. logger.Info("Bootstrapping state")
  54. var res structs.AuthBroadcast
  55. // get a list of piers from config
  56. piers := config.Piers
  57. // this returns a map of ship:running status
  58. logger.Info("Resolving pier status")
  59. updates, err := constructPierInfo(piers)
  60. if err != nil {
  61. return res, err
  62. }
  63. // update broadcastState
  64. err = UpdateBroadcastState(map[string]interface{}{
  65. "Urbits": updates,
  66. })
  67. if err != nil {
  68. errmsg := fmt.Sprintf("Unable to update broadcast state: %v", err)
  69. logger.Error(errmsg)
  70. return res, err
  71. }
  72. // wgRegistered := config.WgRegistered
  73. // wgOn := config.WgOn
  74. // get startram regions
  75. logger.Info("Retrieving StarTram region info")
  76. regions, err := startram.GetRegions()
  77. if err != nil {
  78. logger.Warn("Couldn't get StarTram regions")
  79. } else {
  80. updates := map[string]interface{}{
  81. "Profile": map[string]interface{}{
  82. "Startram": map[string]interface{}{
  83. "Info": map[string]interface{}{
  84. "Regions": regions,
  85. },
  86. },
  87. },
  88. }
  89. err := UpdateBroadcastState(updates)
  90. if err != nil {
  91. errmsg := fmt.Sprintf("Error updating broadcast state:", err)
  92. logger.Error(errmsg)
  93. }
  94. }
  95. // update with system state
  96. sysInfo := constructSystemInfo()
  97. err = UpdateBroadcastState(sysInfo)
  98. if err != nil {
  99. errmsg := fmt.Sprintf("Error updating broadcast state:", err)
  100. logger.Error(errmsg)
  101. }
  102. // return the boostrapped result
  103. res = GetState()
  104. return res, nil
  105. }
  106. // this is for building the broadcast objects describing piers
  107. func constructPierInfo(piers []string) (map[string]structs.Urbit, error) {
  108. updates := make(map[string]structs.Urbit)
  109. // load fresh broadcast state
  110. currentState := GetState()
  111. // get the networks containers are attached to
  112. shipNetworks := GetContainerNetworks(piers)
  113. // find out whether they're running
  114. pierStatus, err := docker.GetShipStatus(piers)
  115. if err != nil {
  116. errmsg := fmt.Sprintf("Unable to bootstrap urbit states: %v", err)
  117. logger.Error(errmsg)
  118. return updates, err
  119. }
  120. hostName, err := os.Hostname()
  121. if err != nil {
  122. errmsg := fmt.Sprintf("Error getting hostname, defaulting to `nativeplanet`: %v", err)
  123. logger.Warn(errmsg)
  124. hostName = "nativeplanet"
  125. }
  126. // convert the running status into bools
  127. for pier, status := range pierStatus {
  128. // pull urbit info from json
  129. err := docker.LoadConfig(pier)
  130. if err != nil {
  131. errmsg := fmt.Sprintf("Unable to load %s config: %v", pier, err)
  132. logger.Error(errmsg)
  133. continue
  134. }
  135. dockerConfig := docker.Conf(pier)
  136. // get container stats from docker
  137. var dockerStats structs.ContainerStats
  138. dockerStats, err = docker.GetContainerStats(pier)
  139. if err != nil {
  140. errmsg := fmt.Sprintf("Unable to load %s stats: %v", pier, err)
  141. logger.Error(errmsg)
  142. continue
  143. }
  144. urbit := structs.Urbit{}
  145. if existingUrbit, exists := currentState.Urbits[pier]; exists {
  146. // If the ship already exists in broadcastState, use its current state
  147. urbit = existingUrbit
  148. }
  149. isRunning := (status == "Up" || strings.HasPrefix(status, "Up "))
  150. bootStatus := true
  151. if dockerConfig.BootStatus == "ignore" {
  152. bootStatus = false
  153. }
  154. setRemote := false
  155. if dockerConfig.Network == "wireguard" {
  156. setRemote = true
  157. }
  158. // collate all the info from our sources into the struct
  159. urbit.Info.Running = isRunning
  160. urbit.Info.Network = shipNetworks[pier]
  161. urbit.Info.URL = fmt.Sprintf("http://%s.local:%d", hostName, dockerConfig.HTTPPort)
  162. urbit.Info.LoomSize = int(math.Pow(2, float64(dockerConfig.LoomSize)) / math.Pow(1024, 2))
  163. urbit.Info.DiskUsage = dockerStats.DiskUsage
  164. urbit.Info.MemUsage = dockerStats.MemoryUsage
  165. urbit.Info.DevMode = dockerConfig.DevMode
  166. urbit.Info.Vere = dockerConfig.UrbitVersion
  167. urbit.Info.DetectBootStatus = bootStatus
  168. urbit.Info.Remote = setRemote
  169. urbit.Info.Vere = dockerConfig.UrbitVersion
  170. // and insert the struct into the map we will use as input for the broadcast struct
  171. updates[pier] = urbit
  172. }
  173. return updates, nil
  174. }
  175. // put together the system[usage] subobject
  176. func constructSystemInfo() map[string]interface{} {
  177. var res map[string]interface{}
  178. var ramObj []uint64
  179. var diskObj []uint64
  180. usedRam, totalRam := system.GetMemory()
  181. ramObj = append(ramObj,usedRam,totalRam)
  182. cpuUsage := system.GetCPU()
  183. usedDisk, freeDisk := system.GetDisk()
  184. diskObj = append(diskObj,usedDisk,freeDisk)
  185. res = map[string]interface{}{
  186. "system":map[string]interface{}{
  187. "usage":map[string]interface{}{
  188. "ram":ramObj,
  189. "cpu":cpuUsage,
  190. "disk":diskObj,
  191. },
  192. },
  193. }
  194. return res
  195. }
  196. // return a map of ships and their networks
  197. func GetContainerNetworks(containers []string) map[string]string {
  198. res := make(map[string]string)
  199. for _, container := range containers {
  200. network, err := docker.GetContainerNetwork(container)
  201. if err != nil {
  202. errmsg := fmt.Sprintf("Error getting container network: %v", err)
  203. logger.Error(errmsg)
  204. continue
  205. } else {
  206. res[container] = network
  207. }
  208. }
  209. return res
  210. }
  211. // update broadcastState with a map of items
  212. func UpdateBroadcastState(values map[string]interface{}) error {
  213. mu.Lock()
  214. defer mu.Unlock()
  215. v := reflect.ValueOf(&broadcastState).Elem()
  216. for key, value := range values {
  217. field := v.FieldByName(key)
  218. if !field.IsValid() || !field.CanSet() {
  219. return fmt.Errorf("field %s does not exist or is not settable", key)
  220. }
  221. val := reflect.ValueOf(value)
  222. if val.Kind() == reflect.Interface {
  223. val = val.Elem() // Extract the underlying value from the interface
  224. }
  225. if err := recursiveUpdate(field, val); err != nil {
  226. return err
  227. }
  228. }
  229. BroadcastToClients()
  230. return nil
  231. }
  232. // this allows us to insert stuff into nested structs/keys and not overwrite the existing contents
  233. func recursiveUpdate(dst, src reflect.Value) error {
  234. if !dst.CanSet() {
  235. return fmt.Errorf("field is not settable")
  236. }
  237. // If dst is a struct and src is a map, handle them field by field
  238. if dst.Kind() == reflect.Struct && src.Kind() == reflect.Map {
  239. for _, key := range src.MapKeys() {
  240. dstField := dst.FieldByName(key.String())
  241. if !dstField.IsValid() {
  242. return fmt.Errorf("field %s does not exist in the struct", key.String())
  243. }
  244. // Initialize the map if it's nil and we're trying to set a map
  245. if dstField.Kind() == reflect.Map && dstField.IsNil() && src.MapIndex(key).Kind() == reflect.Map {
  246. dstField.Set(reflect.MakeMap(dstField.Type()))
  247. }
  248. if !dstField.CanSet() {
  249. return fmt.Errorf("field %s is not settable in the struct", key.String())
  250. }
  251. srcVal := src.MapIndex(key)
  252. if srcVal.Kind() == reflect.Interface {
  253. srcVal = srcVal.Elem()
  254. }
  255. if err := recursiveUpdate(dstField, srcVal); err != nil {
  256. return err
  257. }
  258. }
  259. return nil
  260. }
  261. // If both dst and src are maps, handle them recursively
  262. if dst.Kind() == reflect.Map && src.Kind() == reflect.Map {
  263. for _, key := range src.MapKeys() {
  264. srcVal := src.MapIndex(key)
  265. // If the key doesn't exist in dst, initialize it
  266. dstVal := dst.MapIndex(key)
  267. if !dstVal.IsValid() {
  268. dstVal = reflect.New(dst.Type().Elem()).Elem()
  269. }
  270. // Recursive call to handle potential nested maps or structs
  271. if err := recursiveUpdate(dstVal, srcVal); err != nil {
  272. return err
  273. }
  274. // Initialize the map if it's nil
  275. if dst.IsNil() {
  276. dst.Set(reflect.MakeMap(dst.Type()))
  277. }
  278. dst.SetMapIndex(key, dstVal)
  279. }
  280. return nil
  281. }
  282. // For non-map or non-struct fields, or for direct updates
  283. if dst.Type() != src.Type() {
  284. return fmt.Errorf("type mismatch: expected %s, got %s", dst.Type(), src.Type())
  285. }
  286. dst.Set(src)
  287. return nil
  288. }
  289. // return broadcast state
  290. func GetState() structs.AuthBroadcast {
  291. mu.Lock()
  292. defer mu.Unlock()
  293. return broadcastState
  294. }
  295. // return json string of current broadcast state
  296. func GetStateJson() ([]byte, error) {
  297. mu.Lock()
  298. defer mu.Unlock()
  299. broadcastJson, err := json.Marshal(broadcastState)
  300. if err != nil {
  301. errmsg := fmt.Sprintf("Error marshalling response: %v", err)
  302. logger.Error(errmsg)
  303. return nil, err
  304. }
  305. return broadcastJson, nil
  306. }
  307. // broadcast the global state to all clients
  308. func BroadcastToClients() error {
  309. broadcastJson, err := json.Marshal(broadcastState)
  310. if err != nil {
  311. logger.Error("Error marshalling response:", err)
  312. return err
  313. }
  314. for client := range clients {
  315. if err := client.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  316. logger.Error("Error writing response:", err)
  317. return err
  318. }
  319. }
  320. return nil
  321. }