aci.go 6.7 KB

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