aci.go 7.6 KB

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