agent.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. package docker
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "os"
  9. "strings"
  10. "time"
  11. "github.com/docker/distribution/reference"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/api/types/container"
  14. "github.com/docker/docker/api/types/filters"
  15. "github.com/docker/docker/api/types/network"
  16. "github.com/docker/docker/api/types/volume"
  17. "github.com/docker/docker/client"
  18. "github.com/moby/moby/pkg/jsonmessage"
  19. "github.com/moby/term"
  20. )
  21. // Agent is a Docker client for performing operations that interact
  22. // with the Docker engine over REST
  23. type Agent struct {
  24. authGetter *AuthGetter
  25. client *client.Client
  26. ctx context.Context
  27. label string
  28. }
  29. // CreateLocalVolumeIfNotExist creates a volume using driver type "local" with the
  30. // given name if it does not exist. If the volume does exist but does not contain
  31. // the required label (a.label), an error is thrown.
  32. func (a *Agent) CreateLocalVolumeIfNotExist(name string) (*types.Volume, error) {
  33. volListBody, err := a.client.VolumeList(a.ctx, filters.Args{})
  34. if err != nil {
  35. return nil, a.handleDockerClientErr(err, "Could not list volumes")
  36. }
  37. for _, _vol := range volListBody.Volumes {
  38. if contains, ok := _vol.Labels[a.label]; ok && contains == "true" && _vol.Name == name {
  39. return _vol, nil
  40. } else if !ok && _vol.Name == name {
  41. return nil, fmt.Errorf("volume conflict for %s: please remove existing volume and try again", name)
  42. }
  43. }
  44. return a.CreateLocalVolume(name)
  45. }
  46. // CreateLocalVolume creates a volume using driver type "local" with no
  47. // configured options. The equivalent of:
  48. //
  49. // docker volume create --driver local [name]
  50. func (a *Agent) CreateLocalVolume(name string) (*types.Volume, error) {
  51. labels := make(map[string]string)
  52. labels[a.label] = "true"
  53. opts := volume.VolumeCreateBody{
  54. Name: name,
  55. Driver: "local",
  56. Labels: labels,
  57. }
  58. vol, err := a.client.VolumeCreate(a.ctx, opts)
  59. if err != nil {
  60. return nil, a.handleDockerClientErr(err, "Could not create volume "+name)
  61. }
  62. return &vol, nil
  63. }
  64. // RemoveLocalVolume removes a volume by name
  65. func (a *Agent) RemoveLocalVolume(name string) error {
  66. return a.client.VolumeRemove(a.ctx, name, true)
  67. }
  68. // CreateBridgeNetworkIfNotExist creates a volume using driver type "local" with the
  69. // given name if it does not exist. If the volume does exist but does not contain
  70. // the required label (a.label), an error is thrown.
  71. func (a *Agent) CreateBridgeNetworkIfNotExist(name string) (id string, err error) {
  72. networks, err := a.client.NetworkList(a.ctx, types.NetworkListOptions{})
  73. if err != nil {
  74. return "", a.handleDockerClientErr(err, "Could not list volumes")
  75. }
  76. for _, net := range networks {
  77. if contains, ok := net.Labels[a.label]; ok && contains == "true" && net.Name == name {
  78. return net.ID, nil
  79. } else if !ok && net.Name == name {
  80. return "", fmt.Errorf("network conflict for %s: please remove existing network and try again", name)
  81. }
  82. }
  83. return a.CreateBridgeNetwork(name)
  84. }
  85. // CreateBridgeNetwork creates a volume using the default driver type (bridge)
  86. // with the CLI label attached
  87. func (a *Agent) CreateBridgeNetwork(name string) (id string, err error) {
  88. labels := make(map[string]string)
  89. labels[a.label] = "true"
  90. opts := types.NetworkCreate{
  91. Labels: labels,
  92. Attachable: true,
  93. }
  94. net, err := a.client.NetworkCreate(a.ctx, name, opts)
  95. if err != nil {
  96. return "", a.handleDockerClientErr(err, "Could not create network "+name)
  97. }
  98. return net.ID, nil
  99. }
  100. // ConnectContainerToNetwork attaches a container to a specified network
  101. func (a *Agent) ConnectContainerToNetwork(networkID, containerID, containerName string) error {
  102. // check if the container is connected already
  103. net, err := a.client.NetworkInspect(a.ctx, networkID, types.NetworkInspectOptions{})
  104. if err != nil {
  105. return a.handleDockerClientErr(err, "Could not inspect network"+networkID)
  106. }
  107. for _, cont := range net.Containers {
  108. // if container is connected, just return
  109. if cont.Name == containerName {
  110. return nil
  111. }
  112. }
  113. return a.client.NetworkConnect(a.ctx, networkID, containerID, &network.EndpointSettings{})
  114. }
  115. // PullImageEvent represents a response from the Docker API with an image pull event
  116. type PullImageEvent struct {
  117. Status string `json:"status"`
  118. Error string `json:"error"`
  119. Progress string `json:"progress"`
  120. ProgressDetail struct {
  121. Current int `json:"current"`
  122. Total int `json:"total"`
  123. } `json:"progressDetail"`
  124. }
  125. var PullImageErrNotFound = fmt.Errorf("Requested image not found")
  126. // PullImage pulls an image specified by the image string
  127. func (a *Agent) PullImage(image string) error {
  128. opts, err := a.getPullOptions(image)
  129. if err != nil {
  130. return err
  131. }
  132. // pull the specified image
  133. out, err := a.client.ImagePull(a.ctx, image, opts)
  134. if err != nil && strings.Contains(err.Error(), "Requested image not found") {
  135. return PullImageErrNotFound
  136. } else if err != nil {
  137. return a.handleDockerClientErr(err, "Could not pull image "+image)
  138. }
  139. defer out.Close()
  140. termFd, isTerm := term.GetFdInfo(os.Stderr)
  141. return jsonmessage.DisplayJSONMessagesStream(out, os.Stderr, termFd, isTerm, nil)
  142. // decoder := json.NewDecoder(out)
  143. // var event *PullImageEvent
  144. // for {
  145. // if err := decoder.Decode(&event); err != nil {
  146. // if err == io.EOF {
  147. // break
  148. // }
  149. // return err
  150. // }
  151. // fmt.Println(event.Status)
  152. // }
  153. return nil
  154. }
  155. // PushImage pushes an image specified by the image string
  156. func (a *Agent) PushImage(image string) error {
  157. opts, err := a.getPushOptions(image)
  158. if err != nil {
  159. return err
  160. }
  161. out, err := a.client.ImagePush(
  162. context.Background(),
  163. image,
  164. opts,
  165. )
  166. if err != nil {
  167. return err
  168. }
  169. defer out.Close()
  170. termFd, isTerm := term.GetFdInfo(os.Stderr)
  171. return jsonmessage.DisplayJSONMessagesStream(out, os.Stderr, termFd, isTerm, nil)
  172. }
  173. func (a *Agent) getPullOptions(image string) (types.ImagePullOptions, error) {
  174. // check if agent has an auth getter; otherwise, assume public usage
  175. if a.authGetter == nil {
  176. return types.ImagePullOptions{}, nil
  177. }
  178. // get using server url
  179. serverURL, err := GetServerURLFromTag(image)
  180. if err != nil {
  181. return types.ImagePullOptions{}, err
  182. }
  183. user, secret, err := a.authGetter.GetCredentials(serverURL)
  184. if err != nil {
  185. return types.ImagePullOptions{}, err
  186. }
  187. var authConfig = types.AuthConfig{
  188. Username: user,
  189. Password: secret,
  190. ServerAddress: "https://" + serverURL,
  191. }
  192. authConfigBytes, _ := json.Marshal(authConfig)
  193. authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
  194. return types.ImagePullOptions{
  195. RegistryAuth: authConfigEncoded,
  196. }, nil
  197. }
  198. func (a *Agent) getPushOptions(image string) (types.ImagePushOptions, error) {
  199. pullOpts, err := a.getPullOptions(image)
  200. return types.ImagePushOptions(pullOpts), err
  201. }
  202. func GetServerURLFromTag(image string) (string, error) {
  203. named, err := reference.ParseNamed(image)
  204. if err != nil {
  205. return "", err
  206. }
  207. domain := reference.Domain(named)
  208. // if domain name is empty, use index.docker.io/v1
  209. if domain == "" {
  210. return "index.docker.io/v1", nil
  211. }
  212. return domain, nil
  213. // else if matches := ecrPattern.FindStringSubmatch(image); matches >= 3 {
  214. // // if this matches ECR, just use the domain name
  215. // return domain, nil
  216. // } else if strings.Contains(image, "gcr.io") || strings.Contains(image, "registry.digitalocean.com") {
  217. // // if this matches GCR or DOCR, use the first path component
  218. // return fmt.Sprintf("%s/%s", domain, strings.Split(path, "/")[0]), nil
  219. // }
  220. // // otherwise, best-guess is to get components of path that aren't the image name
  221. // pathParts := strings.Split(path, "/")
  222. // nonImagePath := ""
  223. // if len(pathParts) > 1 {
  224. // nonImagePath = strings.Join(pathParts[0:len(pathParts)-1], "/")
  225. // }
  226. // if err != nil {
  227. // return "", err
  228. // }
  229. // return fmt.Sprintf("%s/%s", domain, nonImagePath), nil
  230. }
  231. // func imagePush(dockerClient *client.Client) error {
  232. // ctx, cancel := context.WithTimeout(context.Background(), time.Second*120)
  233. // defer cancel()
  234. // authConfigBytes, _ := json.Marshal(authConfig)
  235. // authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
  236. // tag := dockerRegistryUserID + "/node-hello"
  237. // opts := types.ImagePushOptions{RegistryAuth: authConfigEncoded}
  238. // rd, err := dockerClient.ImagePush(ctx, tag, opts)
  239. // if err != nil {
  240. // return err
  241. // }
  242. // defer rd.Close()
  243. // err = print(rd)
  244. // if err != nil {
  245. // return err
  246. // }
  247. // return nil
  248. // }
  249. // WaitForContainerStop waits until a container has stopped to exit
  250. func (a *Agent) WaitForContainerStop(id string) error {
  251. // wait for container to stop before exit
  252. statusCh, errCh := a.client.ContainerWait(a.ctx, id, container.WaitConditionNotRunning)
  253. select {
  254. case err := <-errCh:
  255. if err != nil {
  256. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  257. }
  258. case <-statusCh:
  259. }
  260. return nil
  261. }
  262. // WaitForContainerHealthy waits until a container is returning a healthy status. Streak
  263. // is the maximum number of failures in a row, while timeout is the length of time between
  264. // checks.
  265. func (a *Agent) WaitForContainerHealthy(id string, streak int) error {
  266. for {
  267. cont, err := a.client.ContainerInspect(a.ctx, id)
  268. if err != nil {
  269. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  270. }
  271. health := cont.State.Health
  272. if health == nil || health.Status == "healthy" {
  273. return nil
  274. } else if health.FailingStreak >= streak {
  275. break
  276. }
  277. time.Sleep(time.Second)
  278. }
  279. return errors.New("container not healthy")
  280. }
  281. // ------------------------- AGENT HELPER FUNCTIONS ------------------------- //
  282. func (a *Agent) handleDockerClientErr(err error, errPrefix string) error {
  283. if strings.Contains(err.Error(), "Cannot connect to the Docker daemon") {
  284. return fmt.Errorf("The Docker daemon must be running in order to start Porter: connection to %s failed", a.client.DaemonHost())
  285. }
  286. return fmt.Errorf("%s:%s", errPrefix, err.Error())
  287. }