aci.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package azure
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "strings"
  10. "time"
  11. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  12. "github.com/Azure/azure-sdk-for-go/services/keyvault/auth"
  13. "github.com/Azure/go-autorest/autorest"
  14. "github.com/Azure/go-autorest/autorest/to"
  15. tm "github.com/buger/goterm"
  16. "github.com/gobwas/ws"
  17. "github.com/gobwas/ws/wsutil"
  18. "github.com/pkg/errors"
  19. "github.com/docker/api/context/store"
  20. )
  21. func init() {
  22. // required to get auth.NewAuthorizerFromCLI() to work, otherwise getting "The access token has been obtained for wrong audience or resource 'https://vault.azure.net'."
  23. err := os.Setenv("AZURE_KEYVAULT_RESOURCE", "https://management.azure.com")
  24. if err != nil {
  25. panic("unable to set environment variable AZURE_KEYVAULT_RESOURCE")
  26. }
  27. }
  28. func createACIContainers(ctx context.Context, aciContext store.AciContext, groupDefinition containerinstance.ContainerGroup) error {
  29. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  30. if err != nil {
  31. return errors.Wrapf(err, "cannot get container group client")
  32. }
  33. // Check if the container group already exists
  34. _, err = containerGroupsClient.Get(ctx, aciContext.ResourceGroup, *groupDefinition.Name)
  35. if err != nil {
  36. if err, ok := err.(autorest.DetailedError); ok {
  37. if err.StatusCode != http.StatusNotFound {
  38. return err
  39. }
  40. } else {
  41. return err
  42. }
  43. } else {
  44. return fmt.Errorf("container group %q already exists", *groupDefinition.Name)
  45. }
  46. future, err := containerGroupsClient.CreateOrUpdate(
  47. ctx,
  48. aciContext.ResourceGroup,
  49. *groupDefinition.Name,
  50. groupDefinition,
  51. )
  52. if err != nil {
  53. return err
  54. }
  55. err = future.WaitForCompletionRef(ctx, containerGroupsClient.Client)
  56. if err != nil {
  57. return err
  58. }
  59. containerGroup, err := future.Result(containerGroupsClient)
  60. if err != nil {
  61. return err
  62. }
  63. if len(*containerGroup.Containers) > 1 {
  64. var commands []string
  65. for _, container := range *containerGroup.Containers {
  66. commands = append(commands, fmt.Sprintf("echo 127.0.0.1 %s >> /etc/hosts", *container.Name))
  67. }
  68. commands = append(commands, "exit")
  69. containers := *containerGroup.Containers
  70. container := containers[0]
  71. response, err := execACIContainer(ctx, aciContext, "/bin/sh", *containerGroup.Name, *container.Name)
  72. if err != nil {
  73. return err
  74. }
  75. if err = execCommands(
  76. ctx,
  77. *response.WebSocketURI,
  78. *response.Password,
  79. commands,
  80. ); err != nil {
  81. return err
  82. }
  83. }
  84. return err
  85. }
  86. func deleteACIContainerGroup(ctx context.Context, aciContext store.AciContext, containerGroupName string) (c containerinstance.ContainerGroup, err error) {
  87. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  88. if err != nil {
  89. return c, 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. auth, err := auth.NewAuthorizerFromCLI()
  213. if err != nil {
  214. return containerinstance.ContainerGroupsClient{}, err
  215. }
  216. containerGroupsClient := containerinstance.NewContainerGroupsClient(subscriptionID)
  217. containerGroupsClient.Authorizer = auth
  218. containerGroupsClient.PollingDelay = 5 * time.Second
  219. containerGroupsClient.RetryAttempts = 30
  220. containerGroupsClient.RetryDuration = 1 * time.Second
  221. return containerGroupsClient, nil
  222. }
  223. func getContainerClient(subscriptionID string) (containerinstance.ContainerClient, error) {
  224. auth, err := auth.NewAuthorizerFromCLI()
  225. if err != nil {
  226. return containerinstance.ContainerClient{}, err
  227. }
  228. containerClient := containerinstance.NewContainerClient(subscriptionID)
  229. containerClient.Authorizer = auth
  230. return containerClient, nil
  231. }