aci.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 aci
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "net/http"
  19. "strings"
  20. "time"
  21. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  22. "github.com/Azure/go-autorest/autorest"
  23. "github.com/Azure/go-autorest/autorest/to"
  24. tm "github.com/buger/goterm"
  25. "github.com/gobwas/ws"
  26. "github.com/gobwas/ws/wsutil"
  27. "github.com/morikuni/aec"
  28. "github.com/pkg/errors"
  29. "github.com/docker/compose-cli/aci/convert"
  30. "github.com/docker/compose-cli/aci/login"
  31. "github.com/docker/compose-cli/containers"
  32. "github.com/docker/compose-cli/context/store"
  33. "github.com/docker/compose-cli/errdefs"
  34. "github.com/docker/compose-cli/progress"
  35. )
  36. func createACIContainers(ctx context.Context, aciContext store.AciContext, groupDefinition containerinstance.ContainerGroup) error {
  37. containerGroupsClient, err := login.NewContainerGroupsClient(aciContext.SubscriptionID)
  38. if err != nil {
  39. return errors.Wrapf(err, "cannot get container group client")
  40. }
  41. // Check if the container group already exists
  42. _, err = containerGroupsClient.Get(ctx, aciContext.ResourceGroup, *groupDefinition.Name)
  43. if err != nil {
  44. if err, ok := err.(autorest.DetailedError); ok {
  45. if err.StatusCode != http.StatusNotFound {
  46. return err
  47. }
  48. } else {
  49. return err
  50. }
  51. } else {
  52. return fmt.Errorf("container group %q already exists", *groupDefinition.Name)
  53. }
  54. return createOrUpdateACIContainers(ctx, aciContext, groupDefinition)
  55. }
  56. func createOrUpdateACIContainers(ctx context.Context, aciContext store.AciContext, groupDefinition containerinstance.ContainerGroup) error {
  57. w := progress.ContextWriter(ctx)
  58. containerGroupsClient, err := login.NewContainerGroupsClient(aciContext.SubscriptionID)
  59. if err != nil {
  60. return errors.Wrapf(err, "cannot get container group client")
  61. }
  62. groupDisplay := "Group " + *groupDefinition.Name
  63. w.Event(progress.Event{
  64. ID: groupDisplay,
  65. Status: progress.Working,
  66. StatusText: "Waiting",
  67. })
  68. future, err := containerGroupsClient.CreateOrUpdate(
  69. ctx,
  70. aciContext.ResourceGroup,
  71. *groupDefinition.Name,
  72. groupDefinition,
  73. )
  74. if err != nil {
  75. return err
  76. }
  77. w.Event(progress.Event{
  78. ID: groupDisplay,
  79. Status: progress.Done,
  80. StatusText: "Created",
  81. })
  82. for _, c := range *groupDefinition.Containers {
  83. if c.Name != nil && *c.Name != convert.ComposeDNSSidecarName {
  84. w.Event(progress.Event{
  85. ID: *c.Name,
  86. Status: progress.Working,
  87. StatusText: "Waiting",
  88. })
  89. }
  90. }
  91. err = future.WaitForCompletionRef(ctx, containerGroupsClient.Client)
  92. if err != nil {
  93. return err
  94. }
  95. for _, c := range *groupDefinition.Containers {
  96. if c.Name != nil && *c.Name != convert.ComposeDNSSidecarName {
  97. w.Event(progress.Event{
  98. ID: *c.Name,
  99. Status: progress.Done,
  100. StatusText: "Done",
  101. })
  102. }
  103. }
  104. return err
  105. }
  106. func getACIContainerGroup(ctx context.Context, aciContext store.AciContext, containerGroupName string) (containerinstance.ContainerGroup, error) {
  107. containerGroupsClient, err := login.NewContainerGroupsClient(aciContext.SubscriptionID)
  108. if err != nil {
  109. return containerinstance.ContainerGroup{}, fmt.Errorf("cannot get container group client: %v", err)
  110. }
  111. return containerGroupsClient.Get(ctx, aciContext.ResourceGroup, containerGroupName)
  112. }
  113. func deleteACIContainerGroup(ctx context.Context, aciContext store.AciContext, containerGroupName string) (containerinstance.ContainerGroup, error) {
  114. containerGroupsClient, err := login.NewContainerGroupsClient(aciContext.SubscriptionID)
  115. if err != nil {
  116. return containerinstance.ContainerGroup{}, fmt.Errorf("cannot get container group client: %v", err)
  117. }
  118. return containerGroupsClient.Delete(ctx, aciContext.ResourceGroup, containerGroupName)
  119. }
  120. func stopACIContainerGroup(ctx context.Context, aciContext store.AciContext, containerGroupName string) error {
  121. containerGroupsClient, err := login.NewContainerGroupsClient(aciContext.SubscriptionID)
  122. if err != nil {
  123. return fmt.Errorf("cannot get container group client: %v", err)
  124. }
  125. result, err := containerGroupsClient.Stop(ctx, aciContext.ResourceGroup, containerGroupName)
  126. if result.StatusCode == http.StatusNotFound {
  127. return errdefs.ErrNotFound
  128. }
  129. return err
  130. }
  131. func execACIContainer(ctx context.Context, aciContext store.AciContext, command, containerGroup string, containerName string) (c containerinstance.ContainerExecResponse, err error) {
  132. containerClient, err := login.NewContainerClient(aciContext.SubscriptionID)
  133. if err != nil {
  134. return c, errors.Wrapf(err, "cannot get container client")
  135. }
  136. rows, cols := getTermSize()
  137. containerExecRequest := containerinstance.ContainerExecRequest{
  138. Command: to.StringPtr(command),
  139. TerminalSize: &containerinstance.ContainerExecRequestTerminalSize{
  140. Rows: rows,
  141. Cols: cols,
  142. },
  143. }
  144. return containerClient.ExecuteCommand(
  145. ctx,
  146. aciContext.ResourceGroup,
  147. containerGroup,
  148. containerName,
  149. containerExecRequest)
  150. }
  151. func getTermSize() (*int32, *int32) {
  152. rows := tm.Height()
  153. cols := tm.Width()
  154. return to.Int32Ptr(int32(rows)), to.Int32Ptr(int32(cols))
  155. }
  156. func exec(ctx context.Context, address string, password string, request containers.ExecRequest) error {
  157. conn, _, _, err := ws.DefaultDialer.Dial(ctx, address)
  158. if err != nil {
  159. return err
  160. }
  161. err = wsutil.WriteClientMessage(conn, ws.OpText, []byte(password))
  162. if err != nil {
  163. return err
  164. }
  165. downstreamChannel := make(chan error, 10)
  166. upstreamChannel := make(chan error, 10)
  167. go func() {
  168. for {
  169. msg, _, err := wsutil.ReadServerData(conn)
  170. if err != nil {
  171. if err == io.EOF {
  172. downstreamChannel <- nil
  173. return
  174. }
  175. downstreamChannel <- err
  176. return
  177. }
  178. fmt.Fprint(request.Stdout, string(msg))
  179. }
  180. }()
  181. if request.Interactive {
  182. go func() {
  183. for {
  184. // We send each byte, byte-per-byte over the
  185. // websocket because the console is in raw mode
  186. buffer := make([]byte, 1)
  187. n, err := request.Stdin.Read(buffer)
  188. if err != nil {
  189. if err == io.EOF {
  190. upstreamChannel <- nil
  191. return
  192. }
  193. upstreamChannel <- err
  194. return
  195. }
  196. if n > 0 {
  197. err := wsutil.WriteClientMessage(conn, ws.OpText, buffer)
  198. if err != nil {
  199. upstreamChannel <- err
  200. return
  201. }
  202. }
  203. }
  204. }()
  205. }
  206. for {
  207. select {
  208. case err := <-downstreamChannel:
  209. return errors.Wrap(err, "failed to read input from container")
  210. case err := <-upstreamChannel:
  211. return errors.Wrap(err, "failed to send input to container")
  212. }
  213. }
  214. }
  215. func getACIContainerLogs(ctx context.Context, aciContext store.AciContext, containerGroupName, containerName string, tail *int32) (string, error) {
  216. containerClient, err := login.NewContainerClient(aciContext.SubscriptionID)
  217. if err != nil {
  218. return "", errors.Wrapf(err, "cannot get container client")
  219. }
  220. logs, err := containerClient.ListLogs(ctx, aciContext.ResourceGroup, containerGroupName, containerName, tail)
  221. if err != nil {
  222. return "", fmt.Errorf("cannot get container logs: %v", err)
  223. }
  224. return *logs.Content, err
  225. }
  226. func streamLogs(ctx context.Context, aciContext store.AciContext, containerGroupName, containerName string, req containers.LogsRequest) error {
  227. numLines := 0
  228. for {
  229. select {
  230. case <-ctx.Done():
  231. return nil
  232. default:
  233. logs, err := getACIContainerLogs(ctx, aciContext, containerGroupName, containerName, nil)
  234. if err != nil {
  235. return err
  236. }
  237. logLines := strings.Split(logs, "\n")
  238. currentOutput := len(logLines)
  239. // Note: a backend should not do this normally, this breaks the log
  240. // streaming over gRPC but this is the only thing we can do with
  241. // the kind of logs ACI is giving us. Hopefully Azue will give us
  242. // a real logs streaming api soon.
  243. b := aec.EmptyBuilder
  244. b = b.Up(uint(numLines))
  245. fmt.Fprint(req.Writer, b.Column(0).ANSI)
  246. numLines = getBacktrackLines(logLines, req.Width)
  247. for i := 0; i < currentOutput-1; i++ {
  248. fmt.Fprintln(req.Writer, logLines[i])
  249. }
  250. select {
  251. case <-ctx.Done():
  252. return nil
  253. case <-time.After(2 * time.Second):
  254. }
  255. }
  256. }
  257. }
  258. func getBacktrackLines(lines []string, terminalWidth int) int {
  259. if terminalWidth == 0 { // no terminal width has been set, do not divide by zero
  260. return len(lines)
  261. }
  262. numLines := 0
  263. for i := 0; i < len(lines)-1; i++ {
  264. numLines++
  265. if len(lines[i]) > terminalWidth {
  266. numLines += len(lines[i]) / terminalWidth
  267. }
  268. }
  269. return numLines
  270. }