aci.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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() 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) (c containerinstance.ContainerGroup, err 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. // ListACIContainers List available containers
  85. func ListACIContainers(aciContext store.AciContext) (c []containerinstance.ContainerGroup, err error) {
  86. ctx := context.TODO()
  87. containerGroupsClient, err := getContainerGroupsClient(aciContext.SubscriptionID)
  88. if err != nil {
  89. return c, fmt.Errorf("cannot get container group client: %v", err)
  90. }
  91. var containers []containerinstance.ContainerGroup
  92. result, err := containerGroupsClient.ListByResourceGroup(ctx, aciContext.ResourceGroup)
  93. if err != nil {
  94. return []containerinstance.ContainerGroup{}, err
  95. }
  96. for result.NotDone() {
  97. containers = append(containers, result.Values()...)
  98. if err := result.NextWithContext(ctx); err != nil {
  99. return []containerinstance.ContainerGroup{}, err
  100. }
  101. }
  102. return containers, err
  103. }
  104. func ExecACIContainer(ctx context.Context, command, containerGroup string, containerName string, aciContext store.AciContext) (c containerinstance.ContainerExecResponse, err error) {
  105. containerClient := getContainerClient(aciContext.SubscriptionID)
  106. rows, cols := getTermSize()
  107. containerExecRequest := containerinstance.ContainerExecRequest{
  108. Command: to.StringPtr(command),
  109. TerminalSize: &containerinstance.ContainerExecRequestTerminalSize{
  110. Rows: rows,
  111. Cols: cols,
  112. },
  113. }
  114. return containerClient.ExecuteCommand(
  115. ctx,
  116. aciContext.ResourceGroup,
  117. containerGroup,
  118. containerName,
  119. containerExecRequest)
  120. }
  121. func getTermSize() (*int32, *int32) {
  122. rows := tm.Height()
  123. cols := tm.Width()
  124. return to.Int32Ptr(int32(rows)), to.Int32Ptr(int32(cols))
  125. }
  126. func ExecWebSocketLoop(ctx context.Context, wsURL, passwd string) error {
  127. return ExecWebSocketLoopWithCmd(ctx, wsURL, passwd, []string{}, true)
  128. }
  129. func ExecWebSocketLoopWithCmd(ctx context.Context, wsURL, passwd string, commands []string, outputEnabled bool) error {
  130. ctx, cancel := context.WithCancel(ctx)
  131. conn, _, _, err := ws.DefaultDialer.Dial(ctx, wsURL)
  132. if err != nil {
  133. cancel()
  134. return err
  135. }
  136. err = wsutil.WriteClientMessage(conn, ws.OpText, []byte(passwd))
  137. if err != nil {
  138. cancel()
  139. return err
  140. }
  141. lastCommandLen := 0
  142. done := make(chan struct{})
  143. go func() {
  144. defer close(done)
  145. for {
  146. msg, _, err := wsutil.ReadServerData(conn)
  147. if err != nil {
  148. if err != io.EOF {
  149. fmt.Printf("read error: %s\n", err)
  150. }
  151. return
  152. }
  153. lines := strings.Split(string(msg), "\n")
  154. lastCommandLen = len(lines[len(lines)-1])
  155. if outputEnabled {
  156. fmt.Printf("%s", msg)
  157. }
  158. }
  159. }()
  160. interrupt := make(chan os.Signal, 1)
  161. signal.Notify(interrupt, os.Interrupt)
  162. scanner := bufio.NewScanner(os.Stdin)
  163. rc := make(chan string, 10)
  164. if len(commands) > 0 {
  165. for _, command := range commands {
  166. rc <- command
  167. }
  168. }
  169. go func() {
  170. for {
  171. if !scanner.Scan() {
  172. close(done)
  173. cancel()
  174. fmt.Println("exiting...")
  175. break
  176. }
  177. t := scanner.Text()
  178. rc <- t
  179. cleanLastCommand(lastCommandLen)
  180. }
  181. }()
  182. for {
  183. select {
  184. case <-done:
  185. return nil
  186. case line := <-rc:
  187. err = wsutil.WriteClientMessage(conn, ws.OpText, []byte(line+"\n"))
  188. if err != nil {
  189. fmt.Println("write: ", err)
  190. return nil
  191. }
  192. case <-interrupt:
  193. fmt.Println("interrupted...")
  194. close(done)
  195. cancel()
  196. return nil
  197. }
  198. }
  199. }
  200. func cleanLastCommand(lastCommandLen int) {
  201. tm.MoveCursorUp(1)
  202. tm.MoveCursorForward(lastCommandLen)
  203. if runtime.GOOS != "windows" {
  204. for i := 0; i < tm.Width(); i++ {
  205. _, _ = tm.Print(" ")
  206. }
  207. tm.MoveCursorUp(1)
  208. }
  209. tm.Flush()
  210. }
  211. func getContainerGroupsClient(subscriptionID string) (containerinstance.ContainerGroupsClient, error) {
  212. auth, _ := auth.NewAuthorizerFromCLI()
  213. containerGroupsClient := containerinstance.NewContainerGroupsClient(subscriptionID)
  214. containerGroupsClient.Authorizer = auth
  215. return containerGroupsClient, nil
  216. }
  217. func getContainerClient(subscriptionID string) containerinstance.ContainerClient {
  218. auth, _ := auth.NewAuthorizerFromCLI()
  219. containerClient := containerinstance.NewContainerClient(subscriptionID)
  220. containerClient.Authorizer = auth
  221. return containerClient
  222. }