backend.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/docker/api/context/cloud"
  10. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  11. "github.com/compose-spec/compose-go/types"
  12. "github.com/pkg/errors"
  13. "github.com/sirupsen/logrus"
  14. "github.com/docker/api/azure/convert"
  15. "github.com/docker/api/azure/login"
  16. "github.com/docker/api/backend"
  17. "github.com/docker/api/compose"
  18. "github.com/docker/api/containers"
  19. apicontext "github.com/docker/api/context"
  20. "github.com/docker/api/context/store"
  21. )
  22. const singleContainerName = "single--container--aci"
  23. // ErrNoSuchContainer is returned when the mentioned container does not exist
  24. var ErrNoSuchContainer = errors.New("no such container")
  25. func init() {
  26. backend.Register("aci", "aci", func(ctx context.Context) (backend.Service, error) {
  27. return New(ctx)
  28. })
  29. }
  30. func getter() interface{} {
  31. return &store.AciContext{}
  32. }
  33. // New creates a backend that can manage containers
  34. func New(ctx context.Context) (backend.Service, error) {
  35. currentContext := apicontext.CurrentContext(ctx)
  36. contextStore, err := store.New()
  37. if err != nil {
  38. return nil, err
  39. }
  40. metadata, err := contextStore.Get(currentContext, getter)
  41. if err != nil {
  42. return nil, errors.Wrap(err, "wrong context type")
  43. }
  44. aciContext, _ := metadata.Metadata.Data.(store.AciContext)
  45. auth, _ := login.NewAuthorizerFromLogin()
  46. containerGroupsClient := containerinstance.NewContainerGroupsClient(aciContext.SubscriptionID)
  47. containerGroupsClient.Authorizer = auth
  48. return getAciAPIService(containerGroupsClient, aciContext)
  49. }
  50. func getAciAPIService(cgc containerinstance.ContainerGroupsClient, aciCtx store.AciContext) (*aciAPIService, error) {
  51. service, err := login.NewAzureLoginService()
  52. if err != nil {
  53. return nil, err
  54. }
  55. return &aciAPIService{
  56. aciContainerService: aciContainerService{
  57. containerGroupsClient: cgc,
  58. ctx: aciCtx,
  59. },
  60. aciComposeService: aciComposeService{
  61. ctx: aciCtx,
  62. },
  63. aciCloudService: aciCloudService{
  64. loginService: service,
  65. },
  66. }, nil
  67. }
  68. type aciAPIService struct {
  69. aciContainerService
  70. aciComposeService
  71. aciCloudService
  72. }
  73. func (a *aciAPIService) ContainerService() containers.Service {
  74. return &a.aciContainerService
  75. }
  76. func (a *aciAPIService) ComposeService() compose.Service {
  77. return &a.aciComposeService
  78. }
  79. func (a *aciAPIService) CloudService() cloud.Service {
  80. return &a.aciCloudService
  81. }
  82. type aciContainerService struct {
  83. containerGroupsClient containerinstance.ContainerGroupsClient
  84. ctx store.AciContext
  85. }
  86. func (cs *aciContainerService) List(ctx context.Context) ([]containers.Container, error) {
  87. var containerGroups []containerinstance.ContainerGroup
  88. result, err := cs.containerGroupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  89. if err != nil {
  90. return []containers.Container{}, err
  91. }
  92. for result.NotDone() {
  93. containerGroups = append(containerGroups, result.Values()...)
  94. if err := result.NextWithContext(ctx); err != nil {
  95. return []containers.Container{}, err
  96. }
  97. }
  98. var res []containers.Container
  99. for _, containerGroup := range containerGroups {
  100. group, err := cs.containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  101. if err != nil {
  102. return []containers.Container{}, err
  103. }
  104. for _, container := range *group.Containers {
  105. var containerID string
  106. if *container.Name == singleContainerName {
  107. containerID = *containerGroup.Name
  108. } else {
  109. containerID = *containerGroup.Name + "_" + *container.Name
  110. }
  111. status := "Unknown"
  112. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  113. status = *container.InstanceView.CurrentState.State
  114. }
  115. res = append(res, containers.Container{
  116. ID: containerID,
  117. Image: *container.Image,
  118. Status: status,
  119. Ports: convert.ToPorts(group.IPAddress, *container.Ports),
  120. })
  121. }
  122. }
  123. return res, nil
  124. }
  125. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  126. var ports []types.ServicePortConfig
  127. for _, p := range r.Ports {
  128. ports = append(ports, types.ServicePortConfig{
  129. Target: p.ContainerPort,
  130. Published: p.HostPort,
  131. })
  132. }
  133. project := compose.Project{
  134. Name: r.ID,
  135. Config: types.Config{
  136. Services: []types.ServiceConfig{
  137. {
  138. Name: singleContainerName,
  139. Image: r.Image,
  140. Ports: ports,
  141. Labels: r.Labels,
  142. },
  143. },
  144. },
  145. }
  146. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  147. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  148. if err != nil {
  149. return err
  150. }
  151. return createACIContainers(ctx, cs.ctx, groupDefinition)
  152. }
  153. func getGroupAndContainerName(containerID string) (groupName string, containerName string) {
  154. tokens := strings.Split(containerID, "_")
  155. groupName = tokens[0]
  156. if len(tokens) > 1 {
  157. containerName = tokens[len(tokens)-1]
  158. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  159. } else {
  160. containerName = singleContainerName
  161. }
  162. return groupName, containerName
  163. }
  164. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  165. groupName, containerAciName := getGroupAndContainerName(name)
  166. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  167. if err != nil {
  168. return err
  169. }
  170. return exec(
  171. context.Background(),
  172. *containerExecResponse.WebSocketURI,
  173. *containerExecResponse.Password,
  174. reader,
  175. writer,
  176. )
  177. }
  178. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  179. groupName, containerAciName := getGroupAndContainerName(containerName)
  180. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName)
  181. if err != nil {
  182. return err
  183. }
  184. if req.Tail != "all" {
  185. tail, err := strconv.Atoi(req.Tail)
  186. if err != nil {
  187. return err
  188. }
  189. lines := strings.Split(logs, "\n")
  190. // If asked for less lines than exist, take only those lines
  191. if tail <= len(lines) {
  192. logs = strings.Join(lines[len(lines)-tail:], "\n")
  193. }
  194. }
  195. _, err = fmt.Fprint(req.Writer, logs)
  196. return err
  197. }
  198. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  199. cg, err := deleteACIContainerGroup(ctx, cs.ctx, containerID)
  200. if err != nil {
  201. return err
  202. }
  203. if cg.StatusCode == http.StatusNoContent {
  204. return ErrNoSuchContainer
  205. }
  206. return err
  207. }
  208. type aciComposeService struct {
  209. ctx store.AciContext
  210. }
  211. func (cs *aciComposeService) Up(ctx context.Context, opts compose.ProjectOptions) error {
  212. project, err := compose.ProjectFromOptions(&opts)
  213. if err != nil {
  214. return err
  215. }
  216. logrus.Debugf("Up on project with name %q\n", project.Name)
  217. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  218. if err != nil {
  219. return err
  220. }
  221. return createACIContainers(ctx, cs.ctx, groupDefinition)
  222. }
  223. func (cs *aciComposeService) Down(ctx context.Context, opts compose.ProjectOptions) error {
  224. project, err := compose.ProjectFromOptions(&opts)
  225. if err != nil {
  226. return err
  227. }
  228. logrus.Debugf("Down on project with name %q\n", project.Name)
  229. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  230. if err != nil {
  231. return err
  232. }
  233. if cg.StatusCode == http.StatusNoContent {
  234. return ErrNoSuchContainer
  235. }
  236. return err
  237. }
  238. type aciCloudService struct {
  239. loginService login.AzureLoginService
  240. }
  241. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  242. return cs.loginService.Login(ctx)
  243. }