aci.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package azure
  2. import (
  3. "bufio"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "os/signal"
  10. "runtime"
  11. "strings"
  12. "github.com/docker/api/context/store"
  13. "github.com/gobwas/ws"
  14. "github.com/gobwas/ws/wsutil"
  15. "github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
  16. "github.com/Azure/azure-sdk-for-go/services/keyvault/auth"
  17. "github.com/Azure/go-autorest/autorest"
  18. "github.com/Azure/go-autorest/autorest/to"
  19. tm "github.com/buger/goterm"
  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. _ = os.Setenv("AZURE_KEYVAULT_RESOURCE", "https://management.azure.com")
  24. }
  25. func createACIContainers(ctx context.Context, aciContext store.AciContext, groupDefinition containerinstance.ContainerGroup) (containerinstance.ContainerGroup, error) {
  26. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  27. if err != nil {
  28. return c, fmt.Errorf("cannot get container group client: %v", err)
  29. }
  30. // Check if the container group already exists
  31. _, err = containerGroupsClient.Get(ctx, aciContext.ResourceGroup, *groupDefinition.Name)
  32. if err != nil {
  33. if err, ok := err.(autorest.DetailedError); ok {
  34. if err.StatusCode != http.StatusNotFound {
  35. return c, err
  36. }
  37. } else {
  38. return c, err
  39. }
  40. } else {
  41. return c, fmt.Errorf("container group %q already exists", *groupDefinition.Name)
  42. }
  43. future, err := containerGroupsClient.CreateOrUpdate(
  44. ctx,
  45. aciContext.ResourceGroup,
  46. *groupDefinition.Name,
  47. groupDefinition,
  48. )
  49. if err != nil {
  50. return c, err
  51. }
  52. err = future.WaitForCompletionRef(ctx, containerGroupsClient.Client)
  53. if err != nil {
  54. return c, err
  55. }
  56. containerGroup, err := future.Result(containerGroupsClient)
  57. if err != nil {
  58. return c, err
  59. }
  60. if len(*containerGroup.Containers) > 1 {
  61. var commands []string
  62. for _, container := range *containerGroup.Containers {
  63. commands = append(commands, fmt.Sprintf("echo 127.0.0.1 %s >> /etc/hosts", *container.Name))
  64. }
  65. commands = append(commands, "exit")
  66. containers := *containerGroup.Containers
  67. container := containers[0]
  68. response, err := execACIContainer(ctx, "/bin/sh", *containerGroup.Name, *container.Name, aciContext)
  69. if err != nil {
  70. return c, err
  71. }
  72. err = execWebSocketLoopWithCmd(
  73. ctx,
  74. *response.WebSocketURI,
  75. *response.Password,
  76. commands,
  77. false)
  78. if err != nil {
  79. return containerinstance.ContainerGroup{}, err
  80. }
  81. }
  82. return containerGroup, err
  83. }
  84. func listACIContainers(aciContext store.AciContext) (c []containerinstance.ContainerGroup, err error) {
  85. ctx := context.TODO()
  86. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  87. if err != nil {
  88. return c, fmt.Errorf("cannot get container group client: %v", err)
  89. }
  90. var containers []containerinstance.ContainerGroup
  91. result, err := containerGroupsClient.ListByResourceGroup(ctx, aciContext.ResourceGroup)
  92. if err != nil {
  93. return []containerinstance.ContainerGroup{}, err
  94. }
  95. for result.NotDone() {
  96. containers = append(containers, result.Values()...)
  97. if err := result.NextWithContext(ctx); err != nil {
  98. return []containerinstance.ContainerGroup{}, err
  99. }
  100. }
  101. return containers, err
  102. }
  103. func execACIContainer(ctx context.Context, command, containerGroup string, containerName string, aciContext store.AciContext) (c containerinstance.ContainerExecResponse, err error) {
  104. containerClient := getContainerClient(aciContext.SubscriptionID)
  105. rows, cols := getTermSize()
  106. containerExecRequest := containerinstance.ContainerExecRequest{
  107. Command: to.StringPtr(command),
  108. TerminalSize: &containerinstance.ContainerExecRequestTerminalSize{
  109. Rows: rows,
  110. Cols: cols,
  111. },
  112. }
  113. return containerClient.ExecuteCommand(
  114. ctx,
  115. aciContext.ResourceGroup,
  116. containerGroup,
  117. containerName,
  118. containerExecRequest)
  119. }
  120. func getTermSize() (*int32, *int32) {
  121. rows := tm.Height()
  122. cols := tm.Width()
  123. return to.Int32Ptr(int32(rows)), to.Int32Ptr(int32(cols))
  124. }
  125. func execWebSocketLoop(ctx context.Context, wsURL, passwd string) error {
  126. return execWebSocketLoopWithCmd(ctx, wsURL, passwd, []string{}, true)
  127. }
  128. func execWebSocketLoopWithCmd(ctx context.Context, wsURL, passwd string, commands []string, outputEnabled bool) error {
  129. ctx, cancel := context.WithCancel(ctx)
  130. conn, _, _, err := ws.DefaultDialer.Dial(ctx, wsURL)
  131. if err != nil {
  132. cancel()
  133. return err
  134. }
  135. err = wsutil.WriteClientMessage(conn, ws.OpText, []byte(passwd))
  136. if err != nil {
  137. cancel()
  138. return err
  139. }
  140. lastCommandLen := 0
  141. done := make(chan struct{})
  142. go func() {
  143. defer close(done)
  144. for {
  145. msg, _, err := wsutil.ReadServerData(conn)
  146. if err != nil {
  147. if err != io.EOF {
  148. fmt.Printf("read error: %s\n", err)
  149. }
  150. return
  151. }
  152. lines := strings.Split(string(msg), "\n")
  153. lastCommandLen = len(lines[len(lines)-1])
  154. if outputEnabled {
  155. fmt.Printf("%s", msg)
  156. }
  157. }
  158. }()
  159. interrupt := make(chan os.Signal, 1)
  160. signal.Notify(interrupt, os.Interrupt)
  161. scanner := bufio.NewScanner(os.Stdin)
  162. rc := make(chan string, 10)
  163. if len(commands) > 0 {
  164. for _, command := range commands {
  165. rc <- command
  166. }
  167. }
  168. go func() {
  169. for {
  170. if !scanner.Scan() {
  171. close(done)
  172. cancel()
  173. fmt.Println("exiting...")
  174. break
  175. }
  176. t := scanner.Text()
  177. rc <- t
  178. cleanLastCommand(lastCommandLen)
  179. }
  180. }()
  181. for {
  182. select {
  183. case <-done:
  184. return nil
  185. case line := <-rc:
  186. err = wsutil.WriteClientMessage(conn, ws.OpText, []byte(line+"\n"))
  187. if err != nil {
  188. fmt.Println("write: ", err)
  189. return nil
  190. }
  191. case <-interrupt:
  192. fmt.Println("interrupted...")
  193. close(done)
  194. cancel()
  195. return nil
  196. }
  197. }
  198. }
  199. func cleanLastCommand(lastCommandLen int) {
  200. tm.MoveCursorUp(1)
  201. tm.MoveCursorForward(lastCommandLen)
  202. if runtime.GOOS != "windows" {
  203. for i := 0; i < tm.Width(); i++ {
  204. _, _ = tm.Print(" ")
  205. }
  206. tm.MoveCursorUp(1)
  207. }
  208. tm.Flush()
  209. }
  210. func getContainerGroupsClient(subscriptionID string) (containerinstance.ContainerGroupsClient, error) {
  211. auth, _ := auth.NewAuthorizerFromCLI()
  212. containerGroupsClient := containerinstance.NewContainerGroupsClient(subscriptionID)
  213. containerGroupsClient.Authorizer = auth
  214. return containerGroupsClient, nil
  215. }
  216. func getContainerClient(subscriptionID string) containerinstance.ContainerClient {
  217. auth, _ := auth.NewAuthorizerFromCLI()
  218. containerClient := containerinstance.NewContainerClient(subscriptionID)
  219. containerClient.Authorizer = auth
  220. return containerClient
  221. }