aci.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  11. "github.com/Azure/go-autorest/autorest"
  12. "github.com/Azure/go-autorest/autorest/to"
  13. tm "github.com/buger/goterm"
  14. "github.com/gobwas/ws"
  15. "github.com/gobwas/ws/wsutil"
  16. "github.com/pkg/errors"
  17. "github.com/docker/api/azure/login"
  18. "github.com/docker/api/context/store"
  19. )
  20. const aciDockerUserAgent = "docker-cli"
  21. func createACIContainers(ctx context.Context, aciContext store.AciContext, groupDefinition containerinstance.ContainerGroup) error {
  22. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  23. if err != nil {
  24. return errors.Wrapf(err, "cannot get container group client")
  25. }
  26. // Check if the container group already exists
  27. _, err = containerGroupsClient.Get(ctx, aciContext.ResourceGroup, *groupDefinition.Name)
  28. if err != nil {
  29. if err, ok := err.(autorest.DetailedError); ok {
  30. if err.StatusCode != http.StatusNotFound {
  31. return err
  32. }
  33. } else {
  34. return err
  35. }
  36. } else {
  37. return fmt.Errorf("container group %q already exists", *groupDefinition.Name)
  38. }
  39. future, err := containerGroupsClient.CreateOrUpdate(
  40. ctx,
  41. aciContext.ResourceGroup,
  42. *groupDefinition.Name,
  43. groupDefinition,
  44. )
  45. if err != nil {
  46. return err
  47. }
  48. err = future.WaitForCompletionRef(ctx, containerGroupsClient.Client)
  49. if err != nil {
  50. return err
  51. }
  52. containerGroup, err := future.Result(containerGroupsClient)
  53. if err != nil {
  54. return err
  55. }
  56. if len(*containerGroup.Containers) > 1 {
  57. var commands []string
  58. for _, container := range *containerGroup.Containers {
  59. commands = append(commands, fmt.Sprintf("echo 127.0.0.1 %s >> /etc/hosts", *container.Name))
  60. }
  61. commands = append(commands, "exit")
  62. containers := *containerGroup.Containers
  63. container := containers[0]
  64. response, err := execACIContainer(ctx, aciContext, "/bin/sh", *containerGroup.Name, *container.Name)
  65. if err != nil {
  66. return err
  67. }
  68. if err = execCommands(
  69. ctx,
  70. *response.WebSocketURI,
  71. *response.Password,
  72. commands,
  73. ); err != nil {
  74. return err
  75. }
  76. }
  77. return err
  78. }
  79. func getACIContainerGroup(ctx context.Context, aciContext store.AciContext, containerGroupName string) (containerinstance.ContainerGroup, error) {
  80. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  81. if err != nil {
  82. return containerinstance.ContainerGroup{}, fmt.Errorf("cannot get container group client: %v", err)
  83. }
  84. return containerGroupsClient.Get(ctx, aciContext.ResourceGroup, containerGroupName)
  85. }
  86. func deleteACIContainerGroup(ctx context.Context, aciContext store.AciContext, containerGroupName string) (containerinstance.ContainerGroup, error) {
  87. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  88. if err != nil {
  89. return containerinstance.ContainerGroup{}, fmt.Errorf("cannot get container group client: %v", err)
  90. }
  91. return containerGroupsClient.Delete(ctx, aciContext.ResourceGroup, containerGroupName)
  92. }
  93. func execACIContainer(ctx context.Context, aciContext store.AciContext, command, containerGroup string, containerName string) (c containerinstance.ContainerExecResponse, err error) {
  94. containerClient, err := getContainerClient(aciContext.SubscriptionID)
  95. if err != nil {
  96. return c, errors.Wrapf(err, "cannot get container client")
  97. }
  98. rows, cols := getTermSize()
  99. containerExecRequest := containerinstance.ContainerExecRequest{
  100. Command: to.StringPtr(command),
  101. TerminalSize: &containerinstance.ContainerExecRequestTerminalSize{
  102. Rows: rows,
  103. Cols: cols,
  104. },
  105. }
  106. return containerClient.ExecuteCommand(
  107. ctx,
  108. aciContext.ResourceGroup,
  109. containerGroup,
  110. containerName,
  111. containerExecRequest)
  112. }
  113. func getTermSize() (*int32, *int32) {
  114. rows := tm.Height()
  115. cols := tm.Width()
  116. return to.Int32Ptr(int32(rows)), to.Int32Ptr(int32(cols))
  117. }
  118. type commandSender struct {
  119. commands string
  120. }
  121. func (cs *commandSender) Read(p []byte) (int, error) {
  122. if len(cs.commands) == 0 {
  123. return 0, io.EOF
  124. }
  125. var command string
  126. if len(p) >= len(cs.commands) {
  127. command = cs.commands
  128. cs.commands = ""
  129. } else {
  130. command = cs.commands[:len(p)]
  131. cs.commands = cs.commands[len(p):]
  132. }
  133. copy(p, command)
  134. return len(command), nil
  135. }
  136. func execCommands(ctx context.Context, address string, password string, commands []string) error {
  137. writer := ioutil.Discard
  138. reader := &commandSender{
  139. commands: strings.Join(commands, "\n"),
  140. }
  141. return exec(ctx, address, password, reader, writer)
  142. }
  143. func exec(ctx context.Context, address string, password string, reader io.Reader, writer io.Writer) error {
  144. conn, _, _, err := ws.DefaultDialer.Dial(ctx, address)
  145. if err != nil {
  146. return err
  147. }
  148. err = wsutil.WriteClientMessage(conn, ws.OpText, []byte(password))
  149. if err != nil {
  150. return err
  151. }
  152. downstreamChannel := make(chan error, 10)
  153. upstreamChannel := make(chan error, 10)
  154. go func() {
  155. for {
  156. msg, _, err := wsutil.ReadServerData(conn)
  157. if err != nil {
  158. if err == io.EOF {
  159. downstreamChannel <- nil
  160. return
  161. }
  162. downstreamChannel <- err
  163. return
  164. }
  165. fmt.Fprint(writer, string(msg))
  166. }
  167. }()
  168. go func() {
  169. for {
  170. // We send each byte, byte-per-byte over the
  171. // websocket because the console is in raw mode
  172. buffer := make([]byte, 1)
  173. n, err := reader.Read(buffer)
  174. if err != nil {
  175. if err == io.EOF {
  176. upstreamChannel <- nil
  177. return
  178. }
  179. upstreamChannel <- err
  180. return
  181. }
  182. if n > 0 {
  183. err := wsutil.WriteClientMessage(conn, ws.OpText, buffer)
  184. if err != nil {
  185. upstreamChannel <- err
  186. return
  187. }
  188. }
  189. }
  190. }()
  191. for {
  192. select {
  193. case err := <-downstreamChannel:
  194. return errors.Wrap(err, "failed to read input from container")
  195. case err := <-upstreamChannel:
  196. return errors.Wrap(err, "failed to send input to container")
  197. }
  198. }
  199. }
  200. func getACIContainerLogs(ctx context.Context, aciContext store.AciContext, containerGroupName, containerName string) (string, error) {
  201. containerClient, err := getContainerClient(aciContext.SubscriptionID)
  202. if err != nil {
  203. return "", errors.Wrapf(err, "cannot get container client")
  204. }
  205. logs, err := containerClient.ListLogs(ctx, aciContext.ResourceGroup, containerGroupName, containerName, nil)
  206. if err != nil {
  207. return "", fmt.Errorf("cannot get container logs: %v", err)
  208. }
  209. return *logs.Content, err
  210. }
  211. func getContainerGroupsClient(subscriptionID string) (containerinstance.ContainerGroupsClient, error) {
  212. containerGroupsClient := containerinstance.NewContainerGroupsClient(subscriptionID)
  213. err := setupClient(&containerGroupsClient.Client)
  214. if err != nil {
  215. return containerinstance.ContainerGroupsClient{}, err
  216. }
  217. containerGroupsClient.PollingDelay = 5 * time.Second
  218. containerGroupsClient.RetryAttempts = 30
  219. containerGroupsClient.RetryDuration = 1 * time.Second
  220. return containerGroupsClient, nil
  221. }
  222. func setupClient(aciClient *autorest.Client) error {
  223. aciClient.UserAgent = aciDockerUserAgent
  224. auth, err := login.NewAuthorizerFromLogin()
  225. if err != nil {
  226. return err
  227. }
  228. aciClient.Authorizer = auth
  229. return nil
  230. }
  231. func getContainerClient(subscriptionID string) (containerinstance.ContainerClient, error) {
  232. containerClient := containerinstance.NewContainerClient(subscriptionID)
  233. err := setupClient(&containerClient.Client)
  234. if err != nil {
  235. return containerinstance.ContainerClient{}, err
  236. }
  237. return containerClient, nil
  238. }