broadcast.go 10 KB

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