docker.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. // return the container status of a slice of ships
  21. func GetShipStatus(patps []string) (map[string]string, error) {
  22. statuses := make(map[string]string)
  23. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  24. if err != nil {
  25. errmsg := fmt.Sprintf("Error getting Docker info: %v", err)
  26. logger.Error(errmsg)
  27. return statuses, err
  28. } else {
  29. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
  30. if err != nil {
  31. errmsg := fmt.Sprintf("Error getting containers: %v", err)
  32. logger.Error(errmsg)
  33. return statuses, err
  34. } else {
  35. for _, pier := range patps {
  36. found := false
  37. for _, container := range containers {
  38. for _, name := range container.Names {
  39. fasPier := "/" + pier
  40. if name == fasPier {
  41. statuses[pier] = container.Status
  42. found = true
  43. break
  44. }
  45. }
  46. if found {
  47. break
  48. }
  49. }
  50. if !found {
  51. statuses[pier] = "not found"
  52. }
  53. }
  54. }
  55. return statuses, nil
  56. }
  57. }
  58. // return the name of a container's network
  59. func GetContainerNetwork(name string) (string, error) {
  60. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  61. if err != nil {
  62. return "", err
  63. }
  64. defer cli.Close()
  65. containerJSON, err := cli.ContainerInspect(context.Background(), name)
  66. if err != nil {
  67. return "", err
  68. }
  69. for networkName := range containerJSON.NetworkSettings.Networks {
  70. return networkName, nil
  71. }
  72. return "", fmt.Errorf("container is not attached to any network")
  73. }
  74. // return the disk and memory usage for a container
  75. func GetContainerStats(containerName string) (structs.ContainerStats, error) {
  76. var res structs.ContainerStats
  77. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
  78. if err != nil {
  79. return res, err
  80. }
  81. defer cli.Close()
  82. statsResp, err := cli.ContainerStats(context.Background(), containerName, false)
  83. if err != nil {
  84. return res, err
  85. }
  86. defer statsResp.Body.Close()
  87. var stat types.StatsJSON
  88. if err := json.NewDecoder(statsResp.Body).Decode(&stat); err != nil {
  89. return res, err
  90. }
  91. memUsage := stat.MemoryStats.Usage
  92. inspectResp, err := cli.ContainerInspect(context.Background(), containerName)
  93. if err != nil {
  94. return res, err
  95. }
  96. diskUsage := int64(0)
  97. if inspectResp.SizeRw != nil {
  98. diskUsage = *inspectResp.SizeRw
  99. }
  100. return structs.ContainerStats{
  101. MemoryUsage: memUsage,
  102. DiskUsage: diskUsage,
  103. }, nil
  104. }
  105. // start a container by name + type
  106. // contructs a container.Config, then runs through whether to boot/restart/etc
  107. // saves the current container state in memory after completion
  108. func StartContainer(containerName string, containerType string) (structs.ContainerState, error) {
  109. // bundle of info about container
  110. var containerState structs.ContainerState
  111. // config params for container
  112. var containerConfig container.Config
  113. // host config for container
  114. var hostConfig container.HostConfig
  115. // switch on containerType to process containerConfig
  116. switch containerType {
  117. case "vere":
  118. // containerConfig, HostConfig, err := urbitContainerConf(containerName)
  119. _, err := urbitContainerConf(containerName)
  120. if err != nil {
  121. return containerState, err
  122. }
  123. case "netdata":
  124. _, _, err := netdataContainerConf()
  125. if err != nil {
  126. return containerState, err
  127. }
  128. case "minio":
  129. _, _, err := minioContainerConf(containerName)
  130. if err != nil {
  131. return containerState, err
  132. }
  133. case "miniomc":
  134. _, _, err := mcContainerConf()
  135. if err != nil {
  136. return containerState, err
  137. }
  138. case "wireguard":
  139. _, _, err := wgContainerConf()
  140. if err != nil {
  141. return containerState, err
  142. }
  143. default:
  144. errmsg := fmt.Errorf("Unrecognized container type %s", containerType)
  145. return containerState, errmsg
  146. }
  147. ctx := context.Background()
  148. cli, err := client.NewClientWithOpts(client.FromEnv)
  149. if err != nil {
  150. return containerState, err
  151. }
  152. // get the desired tag and hash from config
  153. containerInfo, err := GetLatestContainerInfo(containerType)
  154. if err != nil {
  155. return containerState, err
  156. }
  157. // check if container exists
  158. containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
  159. if err != nil {
  160. return containerState, err
  161. }
  162. var existingContainer *types.Container = nil
  163. for _, container := range containers {
  164. for _, name := range container.Names {
  165. if name == "/"+containerName {
  166. existingContainer = &container
  167. break
  168. }
  169. }
  170. if existingContainer != nil {
  171. break
  172. }
  173. }
  174. desiredTag := containerInfo["tag"]
  175. desiredHash := containerInfo["hash"]
  176. desiredRepo := containerInfo["repo"]
  177. desiredImage := fmt.Sprintf("%s:%s@sha256:%s", desiredRepo, desiredTag, desiredHash)
  178. desiredStatus := "running"
  179. // check if the desired image is available locally
  180. images, err := cli.ImageList(ctx, types.ImageListOptions{})
  181. if err != nil {
  182. return containerState, err
  183. }
  184. imageExistsLocally := false
  185. for _, img := range images {
  186. if img.ID == desiredHash {
  187. imageExistsLocally = true
  188. break
  189. }
  190. if imageExistsLocally {
  191. break
  192. }
  193. }
  194. if !imageExistsLocally {
  195. // pull the image if it doesn't exist locally
  196. _, err = cli.ImagePull(ctx, desiredImage, types.ImagePullOptions{})
  197. if err != nil {
  198. return containerState, err
  199. }
  200. }
  201. switch {
  202. case existingContainer == nil:
  203. // if the container does not exist, create and start it
  204. _, err := cli.ContainerCreate(ctx, &containerConfig, nil, nil, nil, containerName)
  205. if err != nil {
  206. return containerState, err
  207. }
  208. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  209. if err != nil {
  210. return containerState, err
  211. }
  212. msg := fmt.Sprintf("%s started with image %s", containerName, desiredImage)
  213. logger.Info(msg)
  214. case existingContainer.State == "exited":
  215. // if the container exists but is stopped, start it
  216. err := cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  217. if err != nil {
  218. return containerState, err
  219. }
  220. msg := fmt.Sprintf("Started stopped container %s", containerName)
  221. logger.Info(msg)
  222. default:
  223. // if container is running, check the image digest
  224. currentImage := existingContainer.Image
  225. digestParts := strings.Split(currentImage, "@sha256:")
  226. currentDigest := ""
  227. if len(digestParts) > 1 {
  228. currentDigest = digestParts[1]
  229. }
  230. if currentDigest != desiredHash {
  231. // if the hashes don't match, recreate the container with the new one
  232. err := cli.ContainerRemove(ctx, containerName, types.ContainerRemoveOptions{Force: true})
  233. if err != nil {
  234. return containerState, err
  235. }
  236. _, err = cli.ContainerCreate(ctx, &container.Config{
  237. Image: desiredImage,
  238. }, nil, nil, nil, containerName)
  239. if err != nil {
  240. return containerState, err
  241. }
  242. err = cli.ContainerStart(ctx, containerName, types.ContainerStartOptions{})
  243. if err != nil {
  244. return containerState, err
  245. }
  246. msg := fmt.Sprintf("Restarted %s with image %s", containerName, desiredImage)
  247. logger.Info(msg)
  248. }
  249. }
  250. containerDetails, err := cli.ContainerInspect(ctx, containerName)
  251. if err != nil {
  252. return containerState, fmt.Errorf("failed to inspect container %s: %v", containerName, err)
  253. }
  254. // save the current state of the container in memory for reference
  255. containerState = structs.ContainerState{
  256. ID: containerDetails.ID, // container id hash
  257. Name: containerName, // name (eg @p)
  258. Image: desiredImage, // full repo:tag@hash string
  259. Type: containerType, // eg `vere` (corresponds with version server label)
  260. DesiredStatus: desiredStatus, // what the user sets
  261. ActualStatus: containerDetails.State.Status, // what the daemon reports
  262. CreatedAt: containerDetails.Created, // this is a string
  263. Config: containerConfig, // container.Config struct constructed above
  264. Host: hostConfig, // host.Config struct constructed above
  265. }
  266. return containerState, err
  267. }
  268. // convert the version info back into json then a map lol
  269. // so we can easily get the correct repo/release channel/tag/hash
  270. func GetLatestContainerInfo(containerType string) (map[string]string, error) {
  271. var res map[string]string
  272. arch := config.Architecture
  273. hashLabel := arch + "_sha256"
  274. versionInfo := config.VersionInfo
  275. jsonData, err := json.Marshal(versionInfo)
  276. if err != nil {
  277. return res, err
  278. }
  279. // Convert JSON to map
  280. var m map[string]interface{}
  281. err = json.Unmarshal(jsonData, &m)
  282. if err != nil {
  283. return res, err
  284. }
  285. containerData, ok := m[containerType].(map[string]interface{})
  286. if !ok {
  287. return nil, fmt.Errorf("%s data is not a map", containerType)
  288. }
  289. tag, ok := containerData["tag"].(string)
  290. if !ok {
  291. return nil, fmt.Errorf("'tag' is not a string")
  292. }
  293. hashValue, ok := containerData[hashLabel].(string)
  294. if !ok {
  295. return nil, fmt.Errorf("'%s' is not a string", hashLabel)
  296. }
  297. repo, ok := containerData["repo"].(string)
  298. if !ok {
  299. return nil, fmt.Errorf("'repo' is not a string")
  300. }
  301. res = make(map[string]string)
  302. res["tag"] = tag
  303. res["hash"] = hashValue
  304. res["repo"] = repo
  305. return res, nil
  306. }
  307. // stop a container with the name
  308. func StopContainerByName(containerName string) error {
  309. ctx := context.Background()
  310. cli, err := client.NewClientWithOpts(client.FromEnv)
  311. if err != nil {
  312. return err
  313. }
  314. // fetch all containers incl stopped
  315. containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
  316. if err != nil {
  317. return err
  318. }
  319. for _, cont := range containers {
  320. for _, name := range cont.Names {
  321. if name == "/"+containerName {
  322. // Stop the container
  323. options := container.StopOptions{}
  324. if err := cli.ContainerStop(ctx, cont.ID, options); err != nil {
  325. return fmt.Errorf("failed to stop container %s: %v", containerName, err)
  326. }
  327. logger.Info(fmt.Sprintf("Successfully stopped container %s\n", containerName))
  328. return nil
  329. }
  330. }
  331. }
  332. return fmt.Errorf("container with name %s not found", containerName)
  333. }
  334. // subscribe to docker events and feed them into eventbus
  335. func DockerListener() {
  336. ctx := context.Background()
  337. cli, err := client.NewClientWithOpts(client.FromEnv)
  338. if err != nil {
  339. logger.Error(fmt.Sprintf("Error initializing Docker client: %v", err))
  340. return
  341. }
  342. messages, errs := cli.Events(ctx, types.EventsOptions{})
  343. for {
  344. select {
  345. case event := <-messages:
  346. // Convert the Docker event to our custom event and send it to the EventBus
  347. EventBus <- structs.Event{Type: event.Action, Data: event}
  348. case err := <-errs:
  349. logger.Error(fmt.Sprintf("Docker event error: %v", err))
  350. }
  351. }
  352. }
  353. // periodically poll docker in case we miss something
  354. func DockerPoller() {
  355. ticker := time.NewTicker(10 * time.Second)
  356. for {
  357. select {
  358. case <-ticker.C:
  359. logger.Info("polling docker")
  360. // todo (maybe not necessary?)
  361. // fetch the status of all containers and compare with app's state
  362. // if there's a change, send an event to the EventBus
  363. return
  364. }
  365. }
  366. }