docker.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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/api/types/container"
  14. "github.com/docker/docker/client"
  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) (structs.ContainerState, error) {
  107. var containerState ContainerState
  108. ctx := context.Background()
  109. cli, err := client.NewClientWithOpts(client.FromEnv)
  110. if err != nil {
  111. return containerState, err
  112. }
  113. // get the desired tag and hash from config
  114. containerInfo, err := GetLatestContainerInfo(containerType)
  115. if err != nil {
  116. return containerState, err
  117. }
  118. // check if container exists
  119. containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
  120. if err != nil {
  121. return containerState, err
  122. }
  123. var existingContainer *types.Container = nil
  124. for _, container := range containers {
  125. for _, name := range container.Names {
  126. if name == "/"+containerName {
  127. existingContainer = &container
  128. break
  129. }
  130. }
  131. if existingContainer != nil {
  132. break
  133. }
  134. }
  135. desiredTag := containerInfo["tag"]
  136. desiredHash := containerInfo["hash"]
  137. desiredRepo := containerInfo["repo"]
  138. if desiredTag == "" || desiredHash == "" {
  139. err = fmt.Errorf("Version info has not been retrieved!")
  140. return containerState, err
  141. }
  142. // check if the desired image is available locally
  143. images, err := cli.ImageList(ctx, types.ImageListOptions{})
  144. if err != nil {
  145. return containerState, err
  146. }
  147. imageExistsLocally := false
  148. for _, img := range images {
  149. for _, tag := range img.RepoTags {
  150. if tag == containerType+":"+desiredTag && img.ID == desiredHash {
  151. imageExistsLocally = true
  152. break
  153. }
  154. }
  155. if imageExistsLocally {
  156. break
  157. }
  158. }
  159. if !imageExistsLocally {
  160. // pull the image if it doesn't exist locally
  161. _, err = cli.ImagePull(ctx, desiredRepo+":"+desiredTag, types.ImagePullOptions{})
  162. if err != nil {
  163. return containerState, err
  164. }
  165. }
  166. switch {
  167. case existingContainer == nil:
  168. // if the container does not exist, create and start it
  169. _, err := cli.ContainerCreate(ctx, &container.Config{
  170. Image: containerType + ":" + desiredTag,
  171. }, nil, nil, nil, containerName)
  172. if err != nil {
  173. return containerState, err
  174. }
  175. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  176. if err != nil {
  177. return containerState, err
  178. }
  179. msg := fmt.Sprintf("%s started with image %s:%s", containerName, containerType, desiredTag)
  180. logger.Info(msg)
  181. case existingContainer.State == "exited":
  182. // if the container exists but is stopped, start it
  183. err := cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  184. if err != nil {
  185. return containerState, err
  186. }
  187. msg := fmt.Sprintf("Started stopped container %s", containerName)
  188. logger.Info(msg)
  189. default:
  190. // if container is running, check the image tag
  191. currentImage := existingContainer.Image
  192. currentTag := strings.Split(currentImage, ":")[1]
  193. if currentTag != desiredTag {
  194. // if the tags don't match, recreate the container with the new tag
  195. err := cli.ContainerRemove(ctx, containerName, types.ContainerRemoveOptions{Force: true})
  196. if err != nil {
  197. return containerState, err
  198. }
  199. _, err = cli.ContainerCreate(ctx, &container.Config{
  200. Image: containerType + ":" + desiredTag,
  201. }, nil, nil, nil, containerName)
  202. if err != nil {
  203. return containerState, err
  204. }
  205. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  206. if err != nil {
  207. return containerState, err
  208. }
  209. msg := fmt.Sprintf("Restarted %s with image %s:%s", containerName, containerType, desiredTag)
  210. logger.Info(msg)
  211. } else {
  212. msg := fmt.Sprintf("%s is already running with the correct tag: %s", containerName, desiredTag)
  213. logger.Info(msg)
  214. }
  215. }
  216. containerDetails, err := cli.ContainerInspect(ctx, containerName)
  217. if err != nil {
  218. return containerState, fmt.Errorf("failed to inspect container %s: %v", containerName, err)
  219. }
  220. containerState = ContainerState{
  221. ID: containerDetails.ID,
  222. Name: containerName,
  223. Image: fmt.Sprintf("%s:%s@sha256:%s", containerDetails.Config.Image, desiredTag, desiredHash),
  224. Status: containerDetails.State.Status,
  225. CreatedAt: containerDetails.Created,
  226. }
  227. return containerState, err
  228. }
  229. // convert the version info back into json then a map lol
  230. // so we can easily get the correct repo/release channel/tag/hash
  231. func GetLatestContainerInfo(containerType string) (map[string]string, error) {
  232. var res map[string]string
  233. conf := config.Conf()
  234. releaseChannel := conf.UpdateBranch
  235. arch := config.Architecture
  236. hashLabel := arch + "_sha256"
  237. versionInfo := config.VersionInfo
  238. jsonData, err := json.Marshal(versionInfo)
  239. if err != nil {
  240. return res, err
  241. }
  242. // Convert JSON to map
  243. var m map[string]interface{}
  244. err = json.Unmarshal(jsonData, &m)
  245. if err != nil {
  246. return res, err
  247. }
  248. groundseg, ok := m["groundseg"].(map[string]interface{})
  249. if !ok {
  250. return nil, fmt.Errorf("groundseg is not a map")
  251. }
  252. channel, ok := groundseg[releaseChannel].(map[string]interface{})
  253. if !ok {
  254. return nil, fmt.Errorf("%s is not a map", releaseChannel)
  255. }
  256. containerData, ok := channel[containerType].(map[string]interface{})
  257. if !ok {
  258. return nil, fmt.Errorf("%s data is not a map", containerType)
  259. }
  260. tag, ok := containerData["tag"].(string)
  261. if !ok {
  262. return nil, fmt.Errorf("'tag' is not a string")
  263. }
  264. hashValue, ok := containerData[hashLabel].(string)
  265. if !ok {
  266. return nil, fmt.Errorf("'%s' is not a string", hashLabel)
  267. }
  268. repo, ok := containerData["repo"].(string)
  269. if !ok {
  270. return nil, fmt.Errorf("'repo' is not a string")
  271. }
  272. res = make(map[string]string)
  273. res["tag"] = tag
  274. res["hash"] = hashValue
  275. res["repo"] = repo
  276. return res, nil
  277. }
  278. // stop a container with the name
  279. func StopContainerByName(containerName string) error {
  280. ctx := context.Background()
  281. cli, err := client.NewClientWithOpts(client.FromEnv)
  282. if err != nil {
  283. return err
  284. }
  285. // fetch all containers incl stopped
  286. containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
  287. if err != nil {
  288. return err
  289. }
  290. for _, cont := range containers {
  291. for _, name := range cont.Names {
  292. if name == "/"+containerName {
  293. // Stop the container
  294. options := container.StopOptions{}
  295. if err := cli.ContainerStop(ctx, cont.ID, options); err != nil {
  296. return fmt.Errorf("failed to stop container %s: %v", containerName, err)
  297. }
  298. logger.Info(fmt.Sprintf("Successfully stopped container %s\n", containerName))
  299. return nil
  300. }
  301. }
  302. }
  303. return fmt.Errorf("container with name %s not found", containerName)
  304. }
  305. func DockerListener() {
  306. ctx := context.Background()
  307. cli, err := client.NewClientWithOpts(client.FromEnv)
  308. if err != nil {
  309. logger.Error(fmt.Sprintf("Error initializing Docker client: %v", err))
  310. return
  311. }
  312. messages, errs := cli.Events(ctx, types.EventsOptions{})
  313. for {
  314. select {
  315. case event := <-messages:
  316. // Convert the Docker event to our custom event and send it to the EventBus
  317. EventBus <- structs.Event{Type: event.Action, Data: event}
  318. case err := <-errs:
  319. logger.Error(fmt.Sprintf("Docker event error: %v", err))
  320. }
  321. }
  322. }
  323. func DockerPoller() {
  324. ticker := time.NewTicker(10 * time.Second)
  325. for {
  326. select {
  327. case <-ticker.C:
  328. logger.Info("polling docker")
  329. // fetch the status of all containers and compare with app's state
  330. // if there's a change, send an event to the EventBus
  331. return
  332. }
  333. }
  334. }