agent.go 6.0 KB

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