2
0

agent.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. // an error in this case is fatal, since it likely means the docker daemon is
  167. // not running
  168. if err != nil {
  169. return err
  170. }
  171. defer out.Close()
  172. termFd, isTerm := term.GetFdInfo(os.Stderr)
  173. err = jsonmessage.DisplayJSONMessagesStream(out, os.Stderr, termFd, isTerm, nil)
  174. if err != nil {
  175. time.Sleep(1 * time.Second)
  176. continue
  177. } else {
  178. break
  179. }
  180. }
  181. return err
  182. }
  183. func (a *Agent) getPullOptions(image string) (types.ImagePullOptions, error) {
  184. // check if agent has an auth getter; otherwise, assume public usage
  185. if a.authGetter == nil {
  186. return types.ImagePullOptions{}, nil
  187. }
  188. // get using server url
  189. serverURL, err := GetServerURLFromTag(image)
  190. if err != nil {
  191. return types.ImagePullOptions{}, err
  192. }
  193. user, secret, err := a.authGetter.GetCredentials(serverURL)
  194. if err != nil {
  195. return types.ImagePullOptions{}, err
  196. }
  197. var authConfig = types.AuthConfig{
  198. Username: user,
  199. Password: secret,
  200. ServerAddress: "https://" + serverURL,
  201. }
  202. authConfigBytes, _ := json.Marshal(authConfig)
  203. authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
  204. return types.ImagePullOptions{
  205. RegistryAuth: authConfigEncoded,
  206. }, nil
  207. }
  208. func (a *Agent) getPushOptions(image string) (types.ImagePushOptions, error) {
  209. pullOpts, err := a.getPullOptions(image)
  210. return types.ImagePushOptions(pullOpts), err
  211. }
  212. func GetServerURLFromTag(image string) (string, error) {
  213. named, err := reference.ParseNamed(image)
  214. if err != nil {
  215. return "", err
  216. }
  217. domain := reference.Domain(named)
  218. // if domain name is empty, use index.docker.io/v1
  219. if domain == "" {
  220. return "index.docker.io/v1", nil
  221. }
  222. return domain, nil
  223. // else if matches := ecrPattern.FindStringSubmatch(image); matches >= 3 {
  224. // // if this matches ECR, just use the domain name
  225. // return domain, nil
  226. // } else if strings.Contains(image, "gcr.io") || strings.Contains(image, "registry.digitalocean.com") {
  227. // // if this matches GCR or DOCR, use the first path component
  228. // return fmt.Sprintf("%s/%s", domain, strings.Split(path, "/")[0]), nil
  229. // }
  230. // // otherwise, best-guess is to get components of path that aren't the image name
  231. // pathParts := strings.Split(path, "/")
  232. // nonImagePath := ""
  233. // if len(pathParts) > 1 {
  234. // nonImagePath = strings.Join(pathParts[0:len(pathParts)-1], "/")
  235. // }
  236. // if err != nil {
  237. // return "", err
  238. // }
  239. // return fmt.Sprintf("%s/%s", domain, nonImagePath), nil
  240. }
  241. // func imagePush(dockerClient *client.Client) error {
  242. // ctx, cancel := context.WithTimeout(context.Background(), time.Second*120)
  243. // defer cancel()
  244. // authConfigBytes, _ := json.Marshal(authConfig)
  245. // authConfigEncoded := base64.URLEncoding.EncodeToString(authConfigBytes)
  246. // tag := dockerRegistryUserID + "/node-hello"
  247. // opts := types.ImagePushOptions{RegistryAuth: authConfigEncoded}
  248. // rd, err := dockerClient.ImagePush(ctx, tag, opts)
  249. // if err != nil {
  250. // return err
  251. // }
  252. // defer rd.Close()
  253. // err = print(rd)
  254. // if err != nil {
  255. // return err
  256. // }
  257. // return nil
  258. // }
  259. // WaitForContainerStop waits until a container has stopped to exit
  260. func (a *Agent) WaitForContainerStop(id string) error {
  261. // wait for container to stop before exit
  262. statusCh, errCh := a.client.ContainerWait(a.ctx, id, container.WaitConditionNotRunning)
  263. select {
  264. case err := <-errCh:
  265. if err != nil {
  266. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  267. }
  268. case <-statusCh:
  269. }
  270. return nil
  271. }
  272. // WaitForContainerHealthy waits until a container is returning a healthy status. Streak
  273. // is the maximum number of failures in a row, while timeout is the length of time between
  274. // checks.
  275. func (a *Agent) WaitForContainerHealthy(id string, streak int) error {
  276. for {
  277. cont, err := a.client.ContainerInspect(a.ctx, id)
  278. if err != nil {
  279. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  280. }
  281. health := cont.State.Health
  282. if health == nil || health.Status == "healthy" {
  283. return nil
  284. } else if health.FailingStreak >= streak {
  285. break
  286. }
  287. time.Sleep(time.Second)
  288. }
  289. return errors.New("container not healthy")
  290. }
  291. // ------------------------- AGENT HELPER FUNCTIONS ------------------------- //
  292. func (a *Agent) handleDockerClientErr(err error, errPrefix string) error {
  293. if strings.Contains(err.Error(), "Cannot connect to the Docker daemon") {
  294. return fmt.Errorf("The Docker daemon must be running in order to start Porter: connection to %s failed", a.client.DaemonHost())
  295. }
  296. return fmt.Errorf("%s:%s", errPrefix, err.Error())
  297. }