backend.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package azure
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "strconv"
  20. "strings"
  21. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  22. "github.com/Azure/go-autorest/autorest/to"
  23. "github.com/compose-spec/compose-go/cli"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/pkg/errors"
  26. "github.com/sirupsen/logrus"
  27. "github.com/docker/api/azure/convert"
  28. "github.com/docker/api/azure/login"
  29. "github.com/docker/api/backend"
  30. "github.com/docker/api/compose"
  31. "github.com/docker/api/containers"
  32. apicontext "github.com/docker/api/context"
  33. "github.com/docker/api/context/cloud"
  34. "github.com/docker/api/context/store"
  35. "github.com/docker/api/errdefs"
  36. )
  37. const (
  38. singleContainerName = "single--container--aci"
  39. composeContainerSeparator = "_"
  40. )
  41. // ErrNoSuchContainer is returned when the mentioned container does not exist
  42. var ErrNoSuchContainer = errors.New("no such container")
  43. func init() {
  44. backend.Register("aci", "aci", service, getCloudService)
  45. }
  46. func service(ctx context.Context) (backend.Service, error) {
  47. contextStore := store.ContextStore(ctx)
  48. currentContext := apicontext.CurrentContext(ctx)
  49. var aciContext store.AciContext
  50. if err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {
  51. return nil, err
  52. }
  53. return getAciAPIService(aciContext), nil
  54. }
  55. func getCloudService() (cloud.Service, error) {
  56. service, err := login.NewAzureLoginService()
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &aciCloudService{
  61. loginService: service,
  62. }, nil
  63. }
  64. func getAciAPIService(aciCtx store.AciContext) *aciAPIService {
  65. return &aciAPIService{
  66. aciContainerService: &aciContainerService{
  67. ctx: aciCtx,
  68. },
  69. aciComposeService: &aciComposeService{
  70. ctx: aciCtx,
  71. },
  72. }
  73. }
  74. type aciAPIService struct {
  75. *aciContainerService
  76. *aciComposeService
  77. }
  78. func (a *aciAPIService) ContainerService() containers.Service {
  79. return a.aciContainerService
  80. }
  81. func (a *aciAPIService) ComposeService() compose.Service {
  82. return a.aciComposeService
  83. }
  84. type aciContainerService struct {
  85. ctx store.AciContext
  86. }
  87. func (cs *aciContainerService) List(ctx context.Context, _ bool) ([]containers.Container, error) {
  88. groupsClient, err := getContainerGroupsClient(cs.ctx.SubscriptionID)
  89. if err != nil {
  90. return nil, err
  91. }
  92. var containerGroups []containerinstance.ContainerGroup
  93. result, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  94. if err != nil {
  95. return []containers.Container{}, err
  96. }
  97. for result.NotDone() {
  98. containerGroups = append(containerGroups, result.Values()...)
  99. if err := result.NextWithContext(ctx); err != nil {
  100. return []containers.Container{}, err
  101. }
  102. }
  103. var res []containers.Container
  104. for _, containerGroup := range containerGroups {
  105. group, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  106. if err != nil {
  107. return []containers.Container{}, err
  108. }
  109. for _, container := range *group.Containers {
  110. var containerID string
  111. // don't list sidecar container
  112. if *container.Name == convert.ComposeDNSSidecarName {
  113. continue
  114. }
  115. if *container.Name == singleContainerName {
  116. containerID = *containerGroup.Name
  117. } else {
  118. containerID = *containerGroup.Name + composeContainerSeparator + *container.Name
  119. }
  120. status := "Unknown"
  121. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  122. status = *container.InstanceView.CurrentState.State
  123. }
  124. res = append(res, containers.Container{
  125. ID: containerID,
  126. Image: *container.Image,
  127. Status: status,
  128. Ports: convert.ToPorts(group.IPAddress, *container.Ports),
  129. })
  130. }
  131. }
  132. return res, nil
  133. }
  134. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  135. if strings.Contains(r.ID, composeContainerSeparator) {
  136. return errors.New(fmt.Sprintf("invalid container name. ACI container name cannot include %q", composeContainerSeparator))
  137. }
  138. var ports []types.ServicePortConfig
  139. for _, p := range r.Ports {
  140. ports = append(ports, types.ServicePortConfig{
  141. Target: p.ContainerPort,
  142. Published: p.HostPort,
  143. })
  144. }
  145. projectVolumes, serviceConfigVolumes, err := convert.GetRunVolumes(r.Volumes)
  146. if err != nil {
  147. return err
  148. }
  149. project := types.Project{
  150. Name: r.ID,
  151. Services: []types.ServiceConfig{
  152. {
  153. Name: singleContainerName,
  154. Image: r.Image,
  155. Ports: ports,
  156. Labels: r.Labels,
  157. Volumes: serviceConfigVolumes,
  158. Deploy: &types.DeployConfig{
  159. Resources: types.Resources{
  160. Limits: &types.Resource{
  161. NanoCPUs: fmt.Sprintf("%f", r.CPULimit),
  162. MemoryBytes: types.UnitBytes(r.MemLimit.Value()),
  163. },
  164. },
  165. },
  166. },
  167. },
  168. Volumes: projectVolumes,
  169. }
  170. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  171. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  172. if err != nil {
  173. return err
  174. }
  175. return createACIContainers(ctx, cs.ctx, groupDefinition)
  176. }
  177. func (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {
  178. return errdefs.ErrNotImplemented
  179. }
  180. func getGroupAndContainerName(containerID string) (groupName string, containerName string) {
  181. tokens := strings.Split(containerID, composeContainerSeparator)
  182. groupName = tokens[0]
  183. if len(tokens) > 1 {
  184. containerName = tokens[len(tokens)-1]
  185. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  186. } else {
  187. containerName = singleContainerName
  188. }
  189. return groupName, containerName
  190. }
  191. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  192. groupName, containerAciName := getGroupAndContainerName(name)
  193. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  194. if err != nil {
  195. return err
  196. }
  197. return exec(
  198. context.Background(),
  199. *containerExecResponse.WebSocketURI,
  200. *containerExecResponse.Password,
  201. reader,
  202. writer,
  203. )
  204. }
  205. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  206. groupName, containerAciName := getGroupAndContainerName(containerName)
  207. var tail *int32
  208. if req.Follow {
  209. return streamLogs(ctx, cs.ctx, groupName, containerAciName, req.Writer)
  210. }
  211. if req.Tail != "all" {
  212. reqTail, err := strconv.Atoi(req.Tail)
  213. if err != nil {
  214. return err
  215. }
  216. i32 := int32(reqTail)
  217. tail = &i32
  218. }
  219. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)
  220. if err != nil {
  221. return err
  222. }
  223. _, err = fmt.Fprint(req.Writer, logs)
  224. return err
  225. }
  226. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  227. groupName, containerName := getGroupAndContainerName(containerID)
  228. if groupName != containerID {
  229. msg := "cannot delete service %q from compose application %q, you can delete the entire compose app with docker compose down --project-name %s"
  230. return errors.New(fmt.Sprintf(msg, containerName, groupName, groupName))
  231. }
  232. cg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)
  233. if err != nil {
  234. return err
  235. }
  236. if cg.StatusCode == http.StatusNoContent {
  237. return ErrNoSuchContainer
  238. }
  239. return err
  240. }
  241. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  242. groupName, containerName := getGroupAndContainerName(containerID)
  243. cg, err := getACIContainerGroup(ctx, cs.ctx, groupName)
  244. if err != nil {
  245. return containers.Container{}, err
  246. }
  247. if cg.StatusCode == http.StatusNoContent {
  248. return containers.Container{}, ErrNoSuchContainer
  249. }
  250. var cc containerinstance.Container
  251. var found = false
  252. for _, c := range *cg.Containers {
  253. if to.String(c.Name) == containerName {
  254. cc = c
  255. found = true
  256. break
  257. }
  258. }
  259. if !found {
  260. return containers.Container{}, ErrNoSuchContainer
  261. }
  262. return convert.ContainerGroupToContainer(containerID, cg, cc)
  263. }
  264. type aciComposeService struct {
  265. ctx store.AciContext
  266. }
  267. func (cs *aciComposeService) Up(ctx context.Context, opts cli.ProjectOptions) error {
  268. project, err := cli.ProjectFromOptions(&opts)
  269. if err != nil {
  270. return err
  271. }
  272. logrus.Debugf("Up on project with name %q\n", project.Name)
  273. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  274. if err != nil {
  275. return err
  276. }
  277. return createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)
  278. }
  279. func (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) error {
  280. var project types.Project
  281. if opts.Name != "" {
  282. project = types.Project{Name: opts.Name}
  283. } else {
  284. fullProject, err := cli.ProjectFromOptions(&opts)
  285. if err != nil {
  286. return err
  287. }
  288. project = *fullProject
  289. }
  290. logrus.Debugf("Down on project with name %q\n", project.Name)
  291. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  292. if err != nil {
  293. return err
  294. }
  295. if cg.StatusCode == http.StatusNoContent {
  296. return ErrNoSuchContainer
  297. }
  298. return err
  299. }
  300. type aciCloudService struct {
  301. loginService login.AzureLoginService
  302. }
  303. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  304. return cs.loginService.Login(ctx, params[login.TenantIDLoginParam])
  305. }
  306. func (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {
  307. contextHelper := newContextCreateHelper()
  308. return contextHelper.createContextData(ctx, params)
  309. }