broadcast.go 9.7 KB

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