agent.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. func (a *Agent) TagImage(old, new string) error {
  116. return a.client.ImageTag(a.ctx, old, new)
  117. }
  118. // PullImageEvent represents a response from the Docker API with an image pull event
  119. type PullImageEvent struct {
  120. Status string `json:"status"`
  121. Error string `json:"error"`
  122. Progress string `json:"progress"`
  123. ProgressDetail struct {
  124. Current int `json:"current"`
  125. Total int `json:"total"`
  126. } `json:"progressDetail"`
  127. }
  128. var PullImageErrNotFound = fmt.Errorf("Requested image not found")
  129. var PullImageErrUnauthorized = fmt.Errorf("Could not pull image: unauthorized")
  130. // PullImage pulls an image specified by the image string
  131. func (a *Agent) PullImage(image string) error {
  132. opts, err := a.getPullOptions(image)
  133. if err != nil {
  134. return err
  135. }
  136. // pull the specified image
  137. out, err := a.client.ImagePull(a.ctx, image, opts)
  138. if err != nil {
  139. if client.IsErrNotFound(err) {
  140. return PullImageErrNotFound
  141. } else if client.IsErrUnauthorized(err) {
  142. return PullImageErrUnauthorized
  143. } else {
  144. return a.handleDockerClientErr(err, "Could not pull image "+image)
  145. }
  146. }
  147. defer out.Close()
  148. termFd, isTerm := term.GetFdInfo(os.Stderr)
  149. return jsonmessage.DisplayJSONMessagesStream(out, os.Stderr, termFd, isTerm, nil)
  150. }
  151. // PushImage pushes an image specified by the image string
  152. func (a *Agent) PushImage(image string) error {
  153. opts, err := a.getPushOptions(image)
  154. if err != nil {
  155. return err
  156. }
  157. out, err := a.client.ImagePush(
  158. context.Background(),
  159. image,
  160. opts,
  161. )
  162. if err != nil {
  163. return err
  164. }
  165. defer out.Close()
  166. termFd, isTerm := term.GetFdInfo(os.Stderr)
  167. return jsonmessage.DisplayJSONMessagesStream(out, os.Stderr, termFd, isTerm, nil)
  168. }
  169. func (a *Agent) getPullOptions(image string) (types.ImagePullOptions, error) {
  170. // check if agent has an auth getter; otherwise, assume public usage
  171. if a.authGetter == nil {
  172. return types.ImagePullOptions{}, nil
  173. }
  174. // get using server url
  175. serverURL, err := GetServerURLFromTag(image)
  176. if err != nil {
  177. return types.ImagePullOptions{}, err
  178. }
  179. user, secret, err := a.authGetter.GetCredentials(serverURL)
  180. if err != nil {
  181. return types.ImagePullOptions{}, err
  182. }
  183. var authConfig = types.AuthConfig{
  184. Username: user,
  185. Password: secret,
  186. ServerAddress: "https://" + serverURL,
  187. }
  188. authConfigBytes, _ := json.Marshal(authConfig)
  189. authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
  190. return types.ImagePullOptions{
  191. RegistryAuth: authConfigEncoded,
  192. }, nil
  193. }
  194. func (a *Agent) getPushOptions(image string) (types.ImagePushOptions, error) {
  195. pullOpts, err := a.getPullOptions(image)
  196. return types.ImagePushOptions(pullOpts), err
  197. }
  198. func GetServerURLFromTag(image string) (string, error) {
  199. named, err := reference.ParseNamed(image)
  200. if err != nil {
  201. return "", err
  202. }
  203. domain := reference.Domain(named)
  204. // if domain name is empty, use index.docker.io/v1
  205. if domain == "" {
  206. return "index.docker.io/v1", nil
  207. }
  208. return domain, nil
  209. // else if matches := ecrPattern.FindStringSubmatch(image); matches >= 3 {
  210. // // if this matches ECR, just use the domain name
  211. // return domain, nil
  212. // } else if strings.Contains(image, "gcr.io") || strings.Contains(image, "registry.digitalocean.com") {
  213. // // if this matches GCR or DOCR, use the first path component
  214. // return fmt.Sprintf("%s/%s", domain, strings.Split(path, "/")[0]), nil
  215. // }
  216. // // otherwise, best-guess is to get components of path that aren't the image name
  217. // pathParts := strings.Split(path, "/")
  218. // nonImagePath := ""
  219. // if len(pathParts) > 1 {
  220. // nonImagePath = strings.Join(pathParts[0:len(pathParts)-1], "/")
  221. // }
  222. // if err != nil {
  223. // return "", err
  224. // }
  225. // return fmt.Sprintf("%s/%s", domain, nonImagePath), nil
  226. }
  227. // func imagePush(dockerClient *client.Client) error {
  228. // ctx, cancel := context.WithTimeout(context.Background(), time.Second*120)
  229. // defer cancel()
  230. // authConfigBytes, _ := json.Marshal(authConfig)
  231. // authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
  232. // tag := dockerRegistryUserID + "/node-hello"
  233. // opts := types.ImagePushOptions{RegistryAuth: authConfigEncoded}
  234. // rd, err := dockerClient.ImagePush(ctx, tag, opts)
  235. // if err != nil {
  236. // return err
  237. // }
  238. // defer rd.Close()
  239. // err = print(rd)
  240. // if err != nil {
  241. // return err
  242. // }
  243. // return nil
  244. // }
  245. // WaitForContainerStop waits until a container has stopped to exit
  246. func (a *Agent) WaitForContainerStop(id string) error {
  247. // wait for container to stop before exit
  248. statusCh, errCh := a.client.ContainerWait(a.ctx, id, container.WaitConditionNotRunning)
  249. select {
  250. case err := <-errCh:
  251. if err != nil {
  252. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  253. }
  254. case <-statusCh:
  255. }
  256. return nil
  257. }
  258. // WaitForContainerHealthy waits until a container is returning a healthy status. Streak
  259. // is the maximum number of failures in a row, while timeout is the length of time between
  260. // checks.
  261. func (a *Agent) WaitForContainerHealthy(id string, streak int) error {
  262. for {
  263. cont, err := a.client.ContainerInspect(a.ctx, id)
  264. if err != nil {
  265. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  266. }
  267. health := cont.State.Health
  268. if health == nil || health.Status == "healthy" {
  269. return nil
  270. } else if health.FailingStreak >= streak {
  271. break
  272. }
  273. time.Sleep(time.Second)
  274. }
  275. return errors.New("container not healthy")
  276. }
  277. // ------------------------- AGENT HELPER FUNCTIONS ------------------------- //
  278. func (a *Agent) handleDockerClientErr(err error, errPrefix string) error {
  279. if strings.Contains(err.Error(), "Cannot connect to the Docker daemon") {
  280. return fmt.Errorf("The Docker daemon must be running in order to start Porter: connection to %s failed", a.client.DaemonHost())
  281. }
  282. return fmt.Errorf("%s:%s", errPrefix, err.Error())
  283. }