agent.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package docker
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "strings"
  9. "time"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/filters"
  13. "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/api/types/volume"
  15. "github.com/docker/docker/client"
  16. )
  17. // Agent is a Docker client for performing operations that interact
  18. // with the Docker engine over REST
  19. type Agent struct {
  20. client *client.Client
  21. ctx context.Context
  22. label string
  23. }
  24. // CreateLocalVolumeIfNotExist creates a volume using driver type "local" with the
  25. // given name if it does not exist. If the volume does exist but does not contain
  26. // the required label (a.label), an error is thrown.
  27. func (a *Agent) CreateLocalVolumeIfNotExist(name string) (*types.Volume, error) {
  28. volListBody, err := a.client.VolumeList(a.ctx, filters.Args{})
  29. if err != nil {
  30. return nil, a.handleDockerClientErr(err, "Could not list volumes")
  31. }
  32. for _, _vol := range volListBody.Volumes {
  33. if contains, ok := _vol.Labels[a.label]; ok && contains == "true" && _vol.Name == name {
  34. return _vol, nil
  35. } else if !ok && _vol.Name == name {
  36. return nil, fmt.Errorf("volume conflict for %s: please remove existing volume and try again", name)
  37. }
  38. }
  39. return a.CreateLocalVolume(name)
  40. }
  41. // CreateLocalVolume creates a volume using driver type "local" with no
  42. // configured options. The equivalent of:
  43. //
  44. // docker volume create --driver local [name]
  45. func (a *Agent) CreateLocalVolume(name string) (*types.Volume, error) {
  46. labels := make(map[string]string)
  47. labels[a.label] = "true"
  48. opts := volume.VolumeCreateBody{
  49. Name: name,
  50. Driver: "local",
  51. Labels: labels,
  52. }
  53. vol, err := a.client.VolumeCreate(a.ctx, opts)
  54. if err != nil {
  55. return nil, a.handleDockerClientErr(err, "Could not create volume "+name)
  56. }
  57. return &vol, nil
  58. }
  59. // RemoveLocalVolume removes a volume by name
  60. func (a *Agent) RemoveLocalVolume(name string) error {
  61. return a.client.VolumeRemove(a.ctx, name, true)
  62. }
  63. // CreateBridgeNetworkIfNotExist creates a volume using driver type "local" with the
  64. // given name if it does not exist. If the volume does exist but does not contain
  65. // the required label (a.label), an error is thrown.
  66. func (a *Agent) CreateBridgeNetworkIfNotExist(name string) (id string, err error) {
  67. networks, err := a.client.NetworkList(a.ctx, types.NetworkListOptions{})
  68. if err != nil {
  69. return "", a.handleDockerClientErr(err, "Could not list volumes")
  70. }
  71. for _, net := range networks {
  72. if contains, ok := net.Labels[a.label]; ok && contains == "true" && net.Name == name {
  73. return net.ID, nil
  74. } else if !ok && net.Name == name {
  75. return "", fmt.Errorf("network conflict for %s: please remove existing network and try again", name)
  76. }
  77. }
  78. return a.CreateBridgeNetwork(name)
  79. }
  80. // CreateBridgeNetwork creates a volume using the default driver type (bridge)
  81. // with the CLI label attached
  82. func (a *Agent) CreateBridgeNetwork(name string) (id string, err error) {
  83. labels := make(map[string]string)
  84. labels[a.label] = "true"
  85. opts := types.NetworkCreate{
  86. Labels: labels,
  87. Attachable: true,
  88. }
  89. net, err := a.client.NetworkCreate(a.ctx, name, opts)
  90. if err != nil {
  91. return "", a.handleDockerClientErr(err, "Could not create network "+name)
  92. }
  93. return net.ID, nil
  94. }
  95. // ConnectContainerToNetwork attaches a container to a specified network
  96. func (a *Agent) ConnectContainerToNetwork(networkID, containerID, containerName string) error {
  97. // check if the container is connected already
  98. net, err := a.client.NetworkInspect(a.ctx, networkID, types.NetworkInspectOptions{})
  99. if err != nil {
  100. return a.handleDockerClientErr(err, "Could not inspect network"+networkID)
  101. }
  102. for _, cont := range net.Containers {
  103. // if container is connected, just return
  104. if cont.Name == containerName {
  105. return nil
  106. }
  107. }
  108. return a.client.NetworkConnect(a.ctx, networkID, containerID, &network.EndpointSettings{})
  109. }
  110. // PullImageEvent represents a response from the Docker API with an image pull event
  111. type PullImageEvent struct {
  112. Status string `json:"status"`
  113. Error string `json:"error"`
  114. Progress string `json:"progress"`
  115. ProgressDetail struct {
  116. Current int `json:"current"`
  117. Total int `json:"total"`
  118. } `json:"progressDetail"`
  119. }
  120. // PullImage pulls an image specified by the image string
  121. func (a *Agent) PullImage(image string) error {
  122. // pull the specified image
  123. out, err := a.client.ImagePull(a.ctx, image, types.ImagePullOptions{})
  124. if err != nil {
  125. return a.handleDockerClientErr(err, "Could not pull image"+image)
  126. }
  127. decoder := json.NewDecoder(out)
  128. var event *PullImageEvent
  129. for {
  130. if err := decoder.Decode(&event); err != nil {
  131. if err == io.EOF {
  132. break
  133. }
  134. return err
  135. }
  136. }
  137. return nil
  138. }
  139. // WaitForContainerStop waits until a container has stopped to exit
  140. func (a *Agent) WaitForContainerStop(id string) error {
  141. // wait for container to stop before exit
  142. statusCh, errCh := a.client.ContainerWait(a.ctx, id, container.WaitConditionNotRunning)
  143. select {
  144. case err := <-errCh:
  145. if err != nil {
  146. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  147. }
  148. case <-statusCh:
  149. }
  150. return nil
  151. }
  152. // WaitForContainerHealthy waits until a container is returning a healthy status. Streak
  153. // is the maximum number of failures in a row, while timeout is the length of time between
  154. // checks.
  155. func (a *Agent) WaitForContainerHealthy(id string, streak int) error {
  156. for {
  157. cont, err := a.client.ContainerInspect(a.ctx, id)
  158. if err != nil {
  159. return a.handleDockerClientErr(err, "Error waiting for stopped container")
  160. }
  161. health := cont.State.Health
  162. if health == nil || health.Status == "healthy" {
  163. return nil
  164. } else if health.FailingStreak >= streak {
  165. break
  166. }
  167. time.Sleep(time.Second)
  168. }
  169. return errors.New("container not healthy")
  170. }
  171. // ------------------------- AGENT HELPER FUNCTIONS ------------------------- //
  172. func (a *Agent) handleDockerClientErr(err error, errPrefix string) error {
  173. if strings.Contains(err.Error(), "Cannot connect to the Docker daemon") {
  174. return fmt.Errorf("The Docker daemon must be running in order to start Porter: connection to %s failed", a.client.DaemonHost())
  175. }
  176. return fmt.Errorf("%s:%s", errPrefix, err.Error())
  177. }