docker.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package docker
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "goseg/config"
  7. "goseg/structs"
  8. "log/slog"
  9. "os"
  10. "strings"
  11. "time"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/client"
  14. "github.com/docker/docker/api/types/container"
  15. )
  16. var (
  17. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  18. EventBus = make(chan structs.Event, 100)
  19. )
  20. func GetShipStatus(patps []string) (map[string]string, error) {
  21. statuses := make(map[string]string)
  22. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  23. if err != nil {
  24. errmsg := fmt.Sprintf("Error getting Docker info: %v", err)
  25. logger.Error(errmsg)
  26. return statuses, err
  27. } else {
  28. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
  29. if err != nil {
  30. errmsg := fmt.Sprintf("Error getting containers: %v", err)
  31. logger.Error(errmsg)
  32. return statuses, err
  33. } else {
  34. for _, pier := range patps {
  35. found := false
  36. for _, container := range containers {
  37. for _, name := range container.Names {
  38. fasPier := "/" + pier
  39. if name == fasPier {
  40. statuses[pier] = container.Status
  41. found = true
  42. break
  43. }
  44. }
  45. if found {
  46. break
  47. }
  48. }
  49. if !found {
  50. statuses[pier] = "not found"
  51. }
  52. }
  53. }
  54. return statuses, nil
  55. }
  56. }
  57. // return the name of a container's network
  58. func GetContainerNetwork(name string) (string, error) {
  59. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  60. if err != nil {
  61. return "", err
  62. }
  63. defer cli.Close()
  64. containerJSON, err := cli.ContainerInspect(context.Background(), name)
  65. if err != nil {
  66. return "", err
  67. }
  68. for networkName := range containerJSON.NetworkSettings.Networks {
  69. return networkName, nil
  70. }
  71. return "", fmt.Errorf("container is not attached to any network")
  72. }
  73. // return the disk and memory usage for a container
  74. func GetContainerStats(containerName string) (structs.ContainerStats, error) {
  75. var res structs.ContainerStats
  76. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  77. if err != nil {
  78. return res, err
  79. }
  80. defer cli.Close()
  81. statsResp, err := cli.ContainerStats(context.Background(), containerName, false)
  82. if err != nil {
  83. return res, err
  84. }
  85. defer statsResp.Body.Close()
  86. var stat types.StatsJSON
  87. if err := json.NewDecoder(statsResp.Body).Decode(&stat); err != nil {
  88. return res, err
  89. }
  90. memUsage := stat.MemoryStats.Usage
  91. inspectResp, err := cli.ContainerInspect(context.Background(), containerName)
  92. if err != nil {
  93. return res, err
  94. }
  95. diskUsage := int64(0)
  96. if inspectResp.SizeRw != nil {
  97. diskUsage = *inspectResp.SizeRw
  98. }
  99. return structs.ContainerStats{
  100. MemoryUsage: memUsage,
  101. DiskUsage: diskUsage,
  102. }, nil
  103. }
  104. // start a container by name + tag
  105. // not for booting new ships
  106. func StartContainer(containerName string, containerType string) error {
  107. ctx := context.Background()
  108. cli, err := client.NewClientWithOpts(client.FromEnv)
  109. if err != nil {
  110. return err
  111. }
  112. // get the desired tag and hash from config
  113. containerInfo, err := getLatestContainerInfo(containerType)
  114. if err != nil {
  115. return err
  116. }
  117. // check if container exists
  118. containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
  119. if err != nil {
  120. return err
  121. }
  122. var existingContainer *types.Container = nil
  123. for _, container := range containers {
  124. for _, name := range container.Names {
  125. if name == "/"+containerName {
  126. existingContainer = &container
  127. break
  128. }
  129. }
  130. if existingContainer != nil {
  131. break
  132. }
  133. }
  134. desiredTag := containerInfo["tag"]
  135. desiredHash := containerInfo["hash"]
  136. desiredRepo := containerInfo["repo"]
  137. if desiredTag == "" || desiredHash == "" {
  138. err = fmt.Errorf("Version info has not been retrieved!")
  139. return err
  140. }
  141. // check if the desired image is available locally
  142. images, err := cli.ImageList(ctx, types.ImageListOptions{})
  143. if err != nil {
  144. return err
  145. }
  146. imageExistsLocally := false
  147. for _, img := range images {
  148. for _, tag := range img.RepoTags {
  149. if tag == containerType+":"+desiredTag && img.ID == desiredHash {
  150. imageExistsLocally = true
  151. break
  152. }
  153. }
  154. if imageExistsLocally {
  155. break
  156. }
  157. }
  158. if !imageExistsLocally {
  159. // pull the image if it doesn't exist locally
  160. _, err = cli.ImagePull(ctx, desiredRepo+":"+desiredTag, types.ImagePullOptions{})
  161. if err != nil {
  162. return err
  163. }
  164. }
  165. switch {
  166. case existingContainer == nil:
  167. // if the container does not exist, create and start it
  168. _, err := cli.ContainerCreate(ctx, &container.Config{
  169. Image: containerType + ":" + desiredTag,
  170. }, nil, nil, nil, containerName)
  171. if err != nil {
  172. return err
  173. }
  174. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  175. if err != nil {
  176. return err
  177. }
  178. msg := fmt.Sprintf("%s started with image %s:%s", containerName, containerType, desiredTag)
  179. logger.Info(msg)
  180. case existingContainer.State == "exited":
  181. // if the container exists but is stopped, start it
  182. err := cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  183. if err != nil {
  184. return err
  185. }
  186. msg := fmt.Sprintf("Started stopped container %s", containerName)
  187. logger.Info(msg)
  188. default:
  189. // if container is running, check the image tag
  190. currentImage := existingContainer.Image
  191. currentTag := strings.Split(currentImage, ":")[1]
  192. if currentTag != desiredTag {
  193. // if the tags don't match, recreate the container with the new tag
  194. err := cli.ContainerRemove(ctx, containerName, types.ContainerRemoveOptions{Force: true})
  195. if err != nil {
  196. return err
  197. }
  198. _, err = cli.ContainerCreate(ctx, &container.Config{
  199. Image: containerType + ":" + desiredTag,
  200. }, nil, nil, nil, containerName)
  201. if err != nil {
  202. return err
  203. }
  204. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  205. if err != nil {
  206. return err
  207. }
  208. msg := fmt.Sprintf("Restarted %s with image %s:%s", containerName, containerType, desiredTag)
  209. logger.Info(msg)
  210. } else {
  211. msg := fmt.Sprintf("%s is already running with the correct tag: %s", containerName, desiredTag)
  212. logger.Info(msg)
  213. }
  214. }
  215. return nil
  216. }
  217. // convert the version info back into json then a map lol
  218. // so we can easily get the correct repo/release channel/tag/hash
  219. func getLatestContainerInfo(containerType string) (map[string]string, error) {
  220. var res map[string]string
  221. conf := config.Conf()
  222. releaseChannel := conf.UpdateBranch
  223. arch := config.Architecture
  224. hashLabel := arch + "_sha256"
  225. versionInfo := config.VersionInfo
  226. jsonData, err := json.Marshal(versionInfo)
  227. if err != nil {
  228. return res, err
  229. }
  230. // Convert JSON to map
  231. var m map[string]interface{}
  232. err = json.Unmarshal(jsonData, &m)
  233. if err != nil {
  234. return res, err
  235. }
  236. groundseg, ok := m["groundseg"].(map[string]interface{})
  237. if !ok {
  238. return nil, fmt.Errorf("groundseg is not a map")
  239. }
  240. channel, ok := groundseg[releaseChannel].(map[string]interface{})
  241. if !ok {
  242. return nil, fmt.Errorf("%s is not a map", releaseChannel)
  243. }
  244. containerData, ok := channel[containerType].(map[string]interface{})
  245. if !ok {
  246. return nil, fmt.Errorf("%s data is not a map", containerType)
  247. }
  248. tag, ok := containerData["tag"].(string)
  249. if !ok {
  250. return nil, fmt.Errorf("'tag' is not a string")
  251. }
  252. hashValue, ok := containerData[hashLabel].(string)
  253. if !ok {
  254. return nil, fmt.Errorf("'%s' is not a string", hashLabel)
  255. }
  256. repo, ok := containerData["repo"].(string)
  257. if !ok {
  258. return nil, fmt.Errorf("'repo' is not a string")
  259. }
  260. res = make(map[string]string)
  261. res["tag"] = tag
  262. res["hash"] = hashValue
  263. res["repo"] = repo
  264. return res, nil
  265. }
  266. // stop a container with the name
  267. func StopContainerByName(containerName string) error {
  268. ctx := context.Background()
  269. cli, err := client.NewClientWithOpts(client.FromEnv)
  270. if err != nil {
  271. return err
  272. }
  273. // fetch all containers incl stopped
  274. containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
  275. if err != nil {
  276. return err
  277. }
  278. for _, cont := range containers {
  279. for _, name := range cont.Names {
  280. if name == "/"+containerName {
  281. // Stop the container
  282. options := container.StopOptions{}
  283. if err := cli.ContainerStop(ctx, cont.ID, options); err != nil {
  284. return fmt.Errorf("failed to stop container %s: %v", containerName, err)
  285. }
  286. logger.Info(fmt.Sprintf("Successfully stopped container %s\n", containerName))
  287. return nil
  288. }
  289. }
  290. }
  291. return fmt.Errorf("container with name %s not found", containerName)
  292. }
  293. func DockerListener() {
  294. ctx := context.Background()
  295. cli, err := client.NewClientWithOpts(client.FromEnv)
  296. if err != nil {
  297. logger.Error(fmt.Sprintf("Error initializing Docker client: %v", err))
  298. return
  299. }
  300. messages, errs := cli.Events(ctx, types.EventsOptions{})
  301. for {
  302. select {
  303. case event := <-messages:
  304. // Convert the Docker event to our custom event and send it to the EventBus
  305. EventBus <- structs.Event{Type: event.Action, Data: event}
  306. case err := <-errs:
  307. logger.Error(fmt.Sprintf("Docker event error: %v", err))
  308. }
  309. }
  310. }
  311. func DockerPoller() {
  312. ticker := time.NewTicker(10 * time.Second)
  313. for {
  314. select {
  315. case <-ticker.C:
  316. logger.Info("polling docker")
  317. // fetch the status of all containers and compare with app's state
  318. // if there's a change, send an event to the EventBus
  319. return
  320. }
  321. }
  322. }