backend.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/Azure/go-autorest/autorest/to"
  10. "github.com/docker/api/context/cloud"
  11. "github.com/docker/api/errdefs"
  12. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  13. "github.com/compose-spec/compose-go/types"
  14. "github.com/pkg/errors"
  15. "github.com/sirupsen/logrus"
  16. "github.com/docker/api/azure/convert"
  17. "github.com/docker/api/azure/login"
  18. "github.com/docker/api/backend"
  19. "github.com/docker/api/compose"
  20. "github.com/docker/api/containers"
  21. apicontext "github.com/docker/api/context"
  22. "github.com/docker/api/context/store"
  23. )
  24. const singleContainerName = "single--container--aci"
  25. // ErrNoSuchContainer is returned when the mentioned container does not exist
  26. var ErrNoSuchContainer = errors.New("no such container")
  27. // ErrTooManyContainers is returned when trying to inspect on multiple containers at once
  28. var ErrTooManyContainers = errors.New("more than one container in group ID")
  29. func init() {
  30. backend.Register("aci", "aci", service, getCloudService)
  31. }
  32. func service(ctx context.Context) (backend.Service, error) {
  33. contextStore := store.ContextStore(ctx)
  34. currentContext := apicontext.CurrentContext(ctx)
  35. var aciContext store.AciContext
  36. if err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {
  37. return nil, err
  38. }
  39. return getAciAPIService(aciContext), nil
  40. }
  41. func getCloudService() (cloud.Service, error) {
  42. service, err := login.NewAzureLoginService()
  43. if err != nil {
  44. return nil, err
  45. }
  46. return &aciCloudService{
  47. loginService: service,
  48. }, nil
  49. }
  50. func getAciAPIService(aciCtx store.AciContext) *aciAPIService {
  51. return &aciAPIService{
  52. aciContainerService: &aciContainerService{
  53. ctx: aciCtx,
  54. },
  55. aciComposeService: &aciComposeService{
  56. ctx: aciCtx,
  57. },
  58. }
  59. }
  60. type aciAPIService struct {
  61. *aciContainerService
  62. *aciComposeService
  63. }
  64. func (a *aciAPIService) ContainerService() containers.Service {
  65. return a.aciContainerService
  66. }
  67. func (a *aciAPIService) ComposeService() compose.Service {
  68. return a.aciComposeService
  69. }
  70. type aciContainerService struct {
  71. ctx store.AciContext
  72. }
  73. func (cs *aciContainerService) List(ctx context.Context, _ bool) ([]containers.Container, error) {
  74. groupsClient, err := getContainerGroupsClient(cs.ctx.SubscriptionID)
  75. if err != nil {
  76. return nil, err
  77. }
  78. var containerGroups []containerinstance.ContainerGroup
  79. result, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
  80. if err != nil {
  81. return []containers.Container{}, err
  82. }
  83. for result.NotDone() {
  84. containerGroups = append(containerGroups, result.Values()...)
  85. if err := result.NextWithContext(ctx); err != nil {
  86. return []containers.Container{}, err
  87. }
  88. }
  89. var res []containers.Container
  90. for _, containerGroup := range containerGroups {
  91. group, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
  92. if err != nil {
  93. return []containers.Container{}, err
  94. }
  95. for _, container := range *group.Containers {
  96. var containerID string
  97. if *container.Name == singleContainerName {
  98. containerID = *containerGroup.Name
  99. } else {
  100. containerID = *containerGroup.Name + "_" + *container.Name
  101. }
  102. status := "Unknown"
  103. if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
  104. status = *container.InstanceView.CurrentState.State
  105. }
  106. res = append(res, containers.Container{
  107. ID: containerID,
  108. Image: *container.Image,
  109. Status: status,
  110. Ports: convert.ToPorts(group.IPAddress, *container.Ports),
  111. })
  112. }
  113. }
  114. return res, nil
  115. }
  116. func (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {
  117. var ports []types.ServicePortConfig
  118. for _, p := range r.Ports {
  119. ports = append(ports, types.ServicePortConfig{
  120. Target: p.ContainerPort,
  121. Published: p.HostPort,
  122. })
  123. }
  124. projectVolumes, serviceConfigVolumes, err := convert.GetRunVolumes(r.Volumes)
  125. if err != nil {
  126. return err
  127. }
  128. project := compose.Project{
  129. Name: r.ID,
  130. Config: types.Config{
  131. Services: []types.ServiceConfig{
  132. {
  133. Name: singleContainerName,
  134. Image: r.Image,
  135. Ports: ports,
  136. Labels: r.Labels,
  137. Volumes: serviceConfigVolumes,
  138. },
  139. },
  140. Volumes: projectVolumes,
  141. },
  142. }
  143. logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
  144. groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
  145. if err != nil {
  146. return err
  147. }
  148. return createACIContainers(ctx, cs.ctx, groupDefinition)
  149. }
  150. func (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {
  151. return errdefs.ErrNotImplemented
  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. func (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {
  209. cg, err := getACIContainerGroup(ctx, cs.ctx, containerID)
  210. if err != nil {
  211. return containers.Container{}, err
  212. }
  213. if cg.StatusCode == http.StatusNoContent {
  214. return containers.Container{}, ErrNoSuchContainer
  215. }
  216. if cg.Containers != nil && len(*cg.Containers) > 1 {
  217. return containers.Container{}, ErrTooManyContainers
  218. }
  219. return containerGroupToContainer(cg)
  220. }
  221. func containerGroupToContainer(cg containerinstance.ContainerGroup) (containers.Container, error) {
  222. status := "unavailable"
  223. cc := (*cg.Containers)[0]
  224. if cc.InstanceView != nil &&
  225. cc.InstanceView.CurrentState != nil &&
  226. cc.InstanceView.CurrentState.State != nil {
  227. status = to.String(cc.InstanceView.CurrentState.State)
  228. }
  229. memLimits := -1.
  230. if cc.Resources != nil &&
  231. cc.Resources.Limits != nil &&
  232. cc.Resources.Limits.MemoryInGB != nil {
  233. memLimits = *cc.Resources.Limits.MemoryInGB
  234. }
  235. command := ""
  236. if cc.Command != nil {
  237. command = strings.Join(*cc.Command, "")
  238. }
  239. c := containers.Container{
  240. ID: to.String(cg.Name),
  241. Status: status,
  242. Image: to.String(cc.Image),
  243. Command: command,
  244. CPUTime: 0,
  245. MemoryUsage: 0,
  246. MemoryLimit: uint64(memLimits),
  247. PidsCurrent: 0,
  248. PidsLimit: 0,
  249. Labels: nil,
  250. Ports: convert.ToPorts(cg.IPAddress, *cc.Ports),
  251. }
  252. return c, nil
  253. }
  254. type aciComposeService struct {
  255. ctx store.AciContext
  256. }
  257. func (cs *aciComposeService) Up(ctx context.Context, opts compose.ProjectOptions) error {
  258. project, err := compose.ProjectFromOptions(&opts)
  259. if err != nil {
  260. return err
  261. }
  262. logrus.Debugf("Up on project with name %q\n", project.Name)
  263. groupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)
  264. if err != nil {
  265. return err
  266. }
  267. return createACIContainers(ctx, cs.ctx, groupDefinition)
  268. }
  269. func (cs *aciComposeService) Down(ctx context.Context, opts compose.ProjectOptions) error {
  270. project, err := compose.ProjectFromOptions(&opts)
  271. if err != nil {
  272. return err
  273. }
  274. logrus.Debugf("Down on project with name %q\n", project.Name)
  275. cg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)
  276. if err != nil {
  277. return err
  278. }
  279. if cg.StatusCode == http.StatusNoContent {
  280. return ErrNoSuchContainer
  281. }
  282. return err
  283. }
  284. type aciCloudService struct {
  285. loginService login.AzureLoginService
  286. }
  287. func (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {
  288. return cs.loginService.Login(ctx)
  289. }
  290. func (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {
  291. contextHelper := newContextCreateHelper()
  292. return contextHelper.createContextData(ctx, params)
  293. }