agent.go 9.9 KB

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