agent.go 5.5 KB

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