docker.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package docker
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "goseg/config"
  7. "goseg/structs"
  8. "log/slog"
  9. "os"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/client"
  12. )
  13. var (
  14. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  15. )
  16. func GetShipStatus(patps []string) (map[string]string, error) {
  17. statuses := make(map[string]string)
  18. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  19. if err != nil {
  20. errmsg := fmt.Sprintf("Error getting Docker info: %v", err)
  21. logger.Error(errmsg)
  22. return statuses, err
  23. } else {
  24. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
  25. if err != nil {
  26. errmsg := fmt.Sprintf("Error getting containers: %v", err)
  27. logger.Error(errmsg)
  28. return statuses, err
  29. } else {
  30. for _, pier := range patps {
  31. found := false
  32. for _, container := range containers {
  33. for _, name := range container.Names {
  34. fasPier := "/" + pier
  35. if name == fasPier {
  36. statuses[pier] = container.Status
  37. found = true
  38. break
  39. }
  40. }
  41. if found {
  42. break
  43. }
  44. }
  45. if !found {
  46. statuses[pier] = "not found"
  47. }
  48. }
  49. }
  50. return statuses, nil
  51. }
  52. }
  53. // return the name of a container's network
  54. func GetContainerNetwork(name string) (string, error) {
  55. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  56. if err != nil {
  57. return "", err
  58. }
  59. defer cli.Close()
  60. containerJSON, err := cli.ContainerInspect(context.Background(), name)
  61. if err != nil {
  62. return "", err
  63. }
  64. for networkName := range containerJSON.NetworkSettings.Networks {
  65. return networkName, nil
  66. }
  67. return "", fmt.Errorf("container is not attached to any network")
  68. }
  69. // return the disk and memory usage for a container
  70. func GetContainerStats(containerName string) (structs.ContainerStats, error) {
  71. var res structs.ContainerStats
  72. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  73. if err != nil {
  74. return res, err
  75. }
  76. defer cli.Close()
  77. statsResp, err := cli.ContainerStats(context.Background(), containerName, false)
  78. if err != nil {
  79. return res, err
  80. }
  81. defer statsResp.Body.Close()
  82. var stat types.StatsJSON
  83. if err := json.NewDecoder(statsResp.Body).Decode(&stat); err != nil {
  84. return res, err
  85. }
  86. memUsage := stat.MemoryStats.Usage
  87. inspectResp, err := cli.ContainerInspect(context.Background(), containerName)
  88. if err != nil {
  89. return res, err
  90. }
  91. diskUsage := int64(0)
  92. if inspectResp.SizeRw != nil {
  93. diskUsage = *inspectResp.SizeRw
  94. }
  95. return structs.ContainerStats{
  96. MemoryUsage: memUsage,
  97. DiskUsage: diskUsage,
  98. }, nil
  99. }
  100. // start a container by name + tag
  101. // not for booting new ships
  102. func StartContainer(containerName, containerType string) error {
  103. ctx := context.Background()
  104. cli, err := client.NewClientWithOpts(client.FromEnv)
  105. if err != nil {
  106. return err
  107. }
  108. // Placeholder: Get the desired tag and hash from your config
  109. containerInfo, err := getCurrentContainerInfo()
  110. if err != nil {
  111. errMsg := fmt.Errorf("Couldn't get %s container info: %v", containerName, err)
  112. logger.Error(errMsg)
  113. return err
  114. }
  115. desiredTag := containerInfo["tag"]
  116. desiredHash := containerInfo["hash"]
  117. desiredRepo := containerInfo["repo"]
  118. if desiredTag == "" || desiredHash == "" {
  119. err = fmt.Errorf("Version info has not been retrieved!")
  120. logger.Error(err)
  121. return err
  122. }
  123. // Check if the desired image is available locally
  124. images, err := cli.ImageList(ctx, types.ImageListOptions{})
  125. if err != nil {
  126. return err
  127. }
  128. imageExistsLocally := false
  129. for _, img := range images {
  130. for _, tag := range img.RepoTags {
  131. if tag == containerType+":"+desiredTag && img.ID == desiredHash {
  132. imageExistsLocally = true
  133. break
  134. }
  135. }
  136. if imageExistsLocally {
  137. break
  138. }
  139. }
  140. if !imageExistsLocally {
  141. // pull the image if it doesn't exist locally
  142. _, err = cli.ImagePull(ctx, desiredRepo+":"+desiredTag, types.ImagePullOptions{})
  143. if err != nil {
  144. return err
  145. }
  146. }
  147. switch {
  148. case existingContainer == nil:
  149. // if the container does not exist, create and start it
  150. _, err := cli.ContainerCreate(ctx, &container.Config{
  151. Image: containerType + ":" + containerTag,
  152. }, nil, nil, nil, containerName)
  153. if err != nil {
  154. return err
  155. }
  156. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  157. if err != nil {
  158. return err
  159. }
  160. msg := fmt.Sprintf("%s started with image %s:%s", containerName, containerType, containerTag)
  161. logger.Info(msg)
  162. case existingContainer.State == "exited":
  163. // if the container exists but is stopped, start it
  164. err := cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  165. if err != nil {
  166. return err
  167. }
  168. msg := fmt.Sprintf("Started stopped container %s", containerName)
  169. logger.Info(msg)
  170. default:
  171. // if container is running, check the image tag
  172. currentImage := existingContainer.Image
  173. currentTag := strings.Split(currentImage, ":")[1]
  174. if currentTag != containerTag {
  175. // if the tags don't match, recreate the container with the new tag
  176. err := cli.ContainerRemove(ctx, containerName, types.ContainerRemoveOptions{Force: true})
  177. if err != nil {
  178. return err
  179. }
  180. _, err = cli.ContainerCreate(ctx, &container.Config{
  181. Image: containerType + ":" + containerTag,
  182. }, nil, nil, nil, containerName)
  183. if err != nil {
  184. return err
  185. }
  186. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  187. if err != nil {
  188. return err
  189. }
  190. msg := fmt.Sprintf("Restarted %s with image %s:%s", containerName, containerType, containerTag)
  191. logger.Info(msg)
  192. } else {
  193. msg := fmt.Sprintf("%s is already running with the correct tag: %s", containerName, containerTag)
  194. logger.Info(msg)
  195. }
  196. }
  197. return nil
  198. }
  199. // convert the version info back into json then a map lol
  200. // so we can easily get the correct repo/release channel/tag/hash
  201. func getCurrentContainerInfo(containerType string) (map[string]string, error) {
  202. var res map[string]string
  203. conf := config.Conf()
  204. releaseChannel := conf.UpdateBranch
  205. arch := config.Architecture
  206. hashLabel := arch + "_sha256"
  207. versionInfo := config.VersionInfo
  208. jsonData, err := json.Marshal(VersionInfo)
  209. if err != nil {
  210. return res, err
  211. }
  212. // Convert JSON to map
  213. var m map[string]interface{}
  214. err = json.Unmarshal(jsonData, &m)
  215. if err != nil {
  216. return res, err
  217. }
  218. res["tag"] = m["groundseg"][releaseChannel][containerType]["tag"]
  219. res["hash"] = m["groundseg"][releaseChannel][containerType][hashLabel]
  220. res["repo"] = m["groundseg"][releaseChannel][containerType]["repo"]
  221. return res, nil
  222. }