backend.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/go-autorest/autorest/to"
  22. "github.com/docker/api/context/cloud"
  23. "github.com/docker/api/errdefs"
  24. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  25. "github.com/compose-spec/compose-go/types"
  26. "github.com/pkg/errors"
  27. "github.com/sirupsen/logrus"
  28. "github.com/docker/api/azure/convert"
  29. "github.com/docker/api/azure/login"
  30. "github.com/docker/api/backend"
  31. "github.com/docker/api/compose"
  32. "github.com/docker/api/containers"
  33. apicontext "github.com/docker/api/context"
  34. "github.com/docker/api/context/store"
  35. )
  36. const singleContainerName = "single--container--aci"
  37. // ErrNoSuchContainer is returned when the mentioned container does not exist
  38. var ErrNoSuchContainer = errors.New("no such container")
  39. func init() {
  40. backend.Register("aci", "aci", service, getCloudService)
  41. }
  42. func service(ctx context.Context) (backend.Service, error) {
  43. contextStore := store.ContextStore(ctx)
  44. currentContext := apicontext.CurrentContext(ctx)
  45. var aciContext store.AciContext
  46. if err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {
  47. return nil, err
  48. }
  49. return getAciAPIService(aciContext), nil
  50. }
  51. func getCloudService() (cloud.Service, error) {
  52. service, err := login.NewAzureLoginService()
  53. if err != nil {
  54. return nil, err
  55. }
  56. return &aciCloudService{
  57. loginService: service,
  58. }, nil
  59. }
  60. func getAciAPIService(aciCtx store.AciContext) *aciAPIService {
  61. return &aciAPIService{
  62. aciContainerService: &aciContainerService{
  63. ctx: aciCtx,
  64. },
  65. aciComposeService: &aciComposeService{
  66. ctx: aciCtx,
  67. },
  68. }
  69. }
  70. type aciAPIService struct {
  71. *aciContainerService
  72. *aciComposeService
  73. }
  74. func (a *aciAPIService) ContainerService() containers.Service {
  75. return a.aciContainerService
  76. }
  77. func (a *aciAPIService) ComposeService() compose.Service {
  78. return a.aciComposeService
  79. }
  80. type aciContainerService struct {
  81. ctx store.AciContext
  82. }
  83. func (cs *aciContainerService) List(ctx context.Context, _ bool) ([]containers.Container, error) {
  84. groupsClient, err := getContainerGroupsClient(cs.ctx.SubscriptionID)
  85. if err != nil {
  86. return nil, err
  87. }
  88. var containerGroups []containerinstance.ContainerGroup
  89. result, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  90. if err != nil {
  91. return []containers.Container{}, err
  92. }
  93. for result.NotDone() {
  94. containerGroups = append(containerGroups, result.Values()...)
  95. if err := result.NextWithContext(ctx); err != nil {
  96. return []containers.Container{}, err
  97. }
  98. }
  99. var res []containers.Container
  100. for _, containerGroup := range containerGroups {
  101. group, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  102. if err != nil {
  103. return []containers.Container{}, err
  104. }
  105. for _, container := range *group.Containers {
  106. var containerID string
  107. // don't list sidecar container
  108. if *container.Name == convert.ComposeDNSSidecarName {
  109. continue
  110. }
  111. if *container.Name == singleContainerName {
  112. containerID = *containerGroup.Name
  113. } else {
  114. containerID = *containerGroup.Name + "_" + *container.Name
  115. }
  116. status := "Unknown"
  117. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  118. status = *container.InstanceView.CurrentState.State
  119. }
  120. res = append(res, containers.Container{
  121. ID: containerID,
  122. Image: *container.Image,
  123. Status: status,
  124. Ports: convert.ToPorts(group.IPAddress, *container.Ports),
  125. })
  126. }
  127. }
  128. return res, nil
  129. }
  130. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  131. var ports []types.ServicePortConfig
  132. for _, p := range r.Ports {
  133. ports = append(ports, types.ServicePortConfig{
  134. Target: p.ContainerPort,
  135. Published: p.HostPort,
  136. })
  137. }
  138. projectVolumes, serviceConfigVolumes, err := convert.GetRunVolumes(r.Volumes)
  139. if err != nil {
  140. return err
  141. }
  142. project := compose.Project{
  143. Name: r.ID,
  144. Config: types.Config{
  145. Services: []types.ServiceConfig{
  146. {
  147. Name: singleContainerName,
  148. Image: r.Image,
  149. Ports: ports,
  150. Labels: r.Labels,
  151. Volumes: serviceConfigVolumes,
  152. },
  153. },
  154. Volumes: projectVolumes,
  155. },
  156. }
  157. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  158. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  159. if err != nil {
  160. return err
  161. }
  162. return createACIContainers(ctx, cs.ctx, groupDefinition)
  163. }
  164. func (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {
  165. return errdefs.ErrNotImplemented
  166. }
  167. func getGroupAndContainerName(containerID string) (groupName string, containerName string) {
  168. tokens := strings.Split(containerID, "_")
  169. groupName = tokens[0]
  170. if len(tokens) > 1 {
  171. containerName = tokens[len(tokens)-1]
  172. groupName = containerID[:len(containerID)-(len(containerName)+1)]
  173. } else {
  174. containerName = singleContainerName
  175. }
  176. return groupName, containerName
  177. }
  178. func (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {
  179. groupName, containerAciName := getGroupAndContainerName(name)
  180. containerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)
  181. if err != nil {
  182. return err
  183. }
  184. return exec(
  185. context.Background(),
  186. *containerExecResponse.WebSocketURI,
  187. *containerExecResponse.Password,
  188. reader,
  189. writer,
  190. )
  191. }
  192. func (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {
  193. groupName, containerAciName := getGroupAndContainerName(containerName)
  194. logs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName)
  195. if err != nil {
  196. return err
  197. }
  198. if req.Tail != "all" {
  199. tail, err := strconv.Atoi(req.Tail)
  200. if err != nil {
  201. return err
  202. }
  203. lines := strings.Split(logs, "\n")
  204. // If asked for less lines than exist, take only those lines
  205. if tail <= len(lines) {
  206. logs = strings.Join(lines[len(lines)-tail:], "\n")
  207. }
  208. }
  209. _, err = fmt.Fprint(req.Writer, logs)
  210. return err
  211. }
  212. func (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {
  213. cg, err := deleteACIContainerGroup(ctx, cs.ctx, containerID)
  214. if err != nil {
  215. return err
  216. }
  217. if cg.StatusCode == http.StatusNoContent {
  218. return ErrNoSuchContainer
  219. }
  220. return err
  221. }
  222. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  223. groupName, containerName := getGroupAndContainerName(containerID)
  224. cg, err := getACIContainerGroup(ctx, cs.ctx, groupName)
  225. if err != nil {
  226. return containers.Container{}, err
  227. }
  228. if cg.StatusCode == http.StatusNoContent {
  229. return containers.Container{}, ErrNoSuchContainer
  230. }
  231. var cc containerinstance.Container
  232. var found = false
  233. for _, c := range *cg.Containers {
  234. if to.String(c.Name) == containerName {
  235. cc = c
  236. found = true
  237. break
  238. }
  239. }
  240. if !found {
  241. return containers.Container{}, ErrNoSuchContainer
  242. }
  243. return convert.ContainerGroupToContainer(containerID, cg, cc)
  244. }
  245. type aciComposeService struct {
  246. ctx store.AciContext
  247. }
  248. func (cs *aciComposeService) Up(ctx context.Context, opts compose.ProjectOptions) error {
  249. project, err := compose.ProjectFromOptions(&opts)
  250. if err != nil {
  251. return err
  252. }
  253. logrus.Debugf("Up on project with name %q\n", project.Name)
  254. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  255. if err != nil {
  256. return err
  257. }
  258. return createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)
  259. }
  260. func (cs *aciComposeService) Down(ctx context.Context, opts compose.ProjectOptions) error {
  261. project, err := compose.ProjectFromOptions(&opts)
  262. if err != nil {
  263. return err
  264. }
  265. logrus.Debugf("Down on project with name %q\n", project.Name)
  266. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  267. if err != nil {
  268. return err
  269. }
  270. if cg.StatusCode == http.StatusNoContent {
  271. return ErrNoSuchContainer
  272. }
  273. return err
  274. }
  275. type aciCloudService struct {
  276. loginService login.AzureLoginService
  277. }
  278. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  279. return cs.loginService.Login(ctx)
  280. }
  281. func (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {
  282. contextHelper := newContextCreateHelper()
  283. return contextHelper.createContextData(ctx, params)
  284. }