全部产品
云市场

Go SDK 使用示例

更新时间:2019-09-06 14:43:27

Go sdk 地址

样例:

const.go

  1. package eci
  2. type ContainerGroupStatus string
  3. const (
  4. Scheduling = ContainerGroupStatus("Scheduling")
  5. Pending = ContainerGroupStatus("Pending")
  6. Running = ContainerGroupStatus("Running")
  7. Succeeded = ContainerGroupStatus("Succeeded")
  8. Failed = ContainerGroupStatus("Failed")
  9. Restarting = ContainerGroupStatus("Restarting")
  10. Updating = ContainerGroupStatus("Updating")
  11. ScheduleFailed = ContainerGroupStatus("ScheduleFailed")
  12. )
  13. type ContainerStatus string
  14. const (
  15. waiting = ContainerStatus("Waiting")
  16. running = ContainerStatus("Running")
  17. terminated = ContainerStatus("Terminated")
  18. )

config.conf

  1. [eci_conf]
  2. #测试账号ak
  3. access_key = xxx
  4. secret_key = xxx
  5. #region
  6. region_id=cn-hangzhou
  7. #每个region下的资源信息,json格式
  8. region_info={"cn-hangzhou": {"securityGroupId": "sg-bp118knl07ymorgzfhyw","vSwitchId": "vsw-bp1jrgfqqy54kg5hcf8bc","zoneId": "cn-hangzhou-h"},"cn-shanghai": {"securityGroupId": "sg-uf62jug0dt92nfy630cs","vSwitchId": "vsw-uf6cb39ub5urw82bv3w70","zoneId": "cn-shanghai-g"},"cn-beijing": {"securityGroupId": "sg-2ze6uv80a8s4yk04dmyu","vSwitchId": "vsw-2zegtxf8q29d8tt1xtcjk","zoneId": "cn-beijing-h"},"cn-shenzhen":{"securityGroupId": "sg-wz96x4kv4edy97q6jjzn","vSwitchId": "vsw-wz9rn33jwilodp24klo0q","zoneId": "cn-shenzhen-a"},"cn-hongkong":{"securityGroupId": "sg-j6cjajpf7f4ybda7h19w","vSwitchId": "vsw-j6c9c9fit5owbbc0ids6c","zoneId": "cn-hongkong-b"},"us-west-1":{"securityGroupId": "sg-u19hbpj9x","vSwitchId": "vsw-rj9h5vvzhb4fjkuzuyi8j","zoneId": "us-west-1a"},"us-east-1":{"securityGroupId": "sg-0xih51sfoldxzxfsbja5","vSwitchId": "vsw-0xisefewxoqe4f849jbnl","zoneId": "us-east-1b"},"ap-southeast-1":{"securityGroupId": "sg-t4n23ppw7fm5to7cnib9","vSwitchId": "vsw-t4nr1xt8zupxg00unnmg9","zoneId": "ap-southeast-1b"},"cn-zhangjiakou": {"securityGroupId": "sg-8vb96lku1dgq71ckh98g","vSwitchId": "vsw-8vbtnz5878r3bcio7cpyx", "nfs":"9cbb94a474-oav34.cn-zhangjiakou.nas.aliyuncs.com", "zoneId": "cn-zhangjiakou-a"}}

config.conf的region_info参数(仅供参考):

  1. {
  2. "cn-hangzhou": {
  3. "securityGroupId": "sg-bp118knl07ymorgzfhyw",
  4. "vSwitchId": "vsw-bp1jrgfqqy54kg5hcf8bc",
  5. "zoneId": "cn-hangzhou-h"
  6. },
  7. "cn-shanghai": {
  8. "securityGroupId": "sg-uf62jug0dt92nfy630cs",
  9. "vSwitchId": "vsw-uf6cb39ub5urw82bv3w70",
  10. "zoneId": "cn-shanghai-g"
  11. },
  12. "cn-beijing": {
  13. "securityGroupId": "sg-2ze6uv80a8s4yk04dmyu",
  14. "vSwitchId": "vsw-2zegtxf8q29d8tt1xtcjk",
  15. "zoneId": "cn-beijing-h"
  16. },
  17. "cn-shenzhen": {
  18. "securityGroupId": "sg-wz96x4kv4edy97q6jjzn",
  19. "vSwitchId": "vsw-wz9rn33jwilodp24klo0q",
  20. "zoneId": "cn-shenzhen-a"
  21. },
  22. "cn-hongkong": {
  23. "securityGroupId": "sg-j6cjajpf7f4ybda7h19w",
  24. "vSwitchId": "vsw-j6c9c9fit5owbbc0ids6c",
  25. "zoneId": "cn-hongkong-b"
  26. },
  27. "us-west-1": {
  28. "securityGroupId": "sg-u19hbpj9x",
  29. "vSwitchId": "vsw-rj9h5vvzhb4fjkuzuyi8j",
  30. "zoneId": "us-west-1a"
  31. },
  32. "ap-southeast-1": {
  33. "securityGroupId": "sg-t4n23ppw7fm5to7cnib9",
  34. "vSwitchId": "vsw-t4nr1xt8zupxg00unnmg9",
  35. "zoneId": "ap-southeast-1b"
  36. },
  37. "cn-zhangjiakou": {
  38. "securityGroupId": "sg-8vb96lku1dgq71ckh98g",
  39. "vSwitchId": "vsw-8vbtnz5878r3bcio7cpyx",
  40. "zoneId": "cn-zhangjiakou-a"
  41. }
  42. }

eci.go

  1. package eci
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/Unknwon/goconfig"
  6. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  7. "github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
  8. "math"
  9. "os"
  10. "reflect"
  11. "strconv"
  12. "time"
  13. )
  14. var accessKey string
  15. var secretKey string
  16. var regionId string
  17. var zoneId string
  18. var securityGroupId string
  19. var vSwitchId string
  20. var client *eci.Client
  21. /**
  22. 获取配置信息
  23. */
  24. func init() {
  25. var cfg *goconfig.ConfigFile
  26. config, err := goconfig.LoadConfigFile("./eci/config.conf") //加载配置文件
  27. if err != nil {
  28. fmt.Println("get config file error:", err.Error())
  29. os.Exit(-1)
  30. }
  31. cfg = config
  32. accessKey, _ = cfg.GetValue("eci_conf", "access_key")
  33. secretKey, _ = cfg.GetValue("eci_conf", "secret_key")
  34. regionId, _ = cfg.GetValue("eci_conf", "region_id")
  35. var regionInfo map[string](map[string](string));
  36. value, _ := cfg.GetValue("eci_conf", "region_info")
  37. json.Unmarshal([]byte(value), &regionInfo)
  38. zoneId = regionInfo[regionId]["zoneId"]
  39. securityGroupId = regionInfo[regionId]["securityGroupId"]
  40. vSwitchId = regionInfo[regionId]["vSwitchId"]
  41. fmt.Printf("init success[ access_key:%s, secret_key:%s, region_id:%s, zoneId:%s, vSwitchId:%s, securityGroupId:%s]\n",
  42. accessKey, secretKey, regionId, zoneId, vSwitchId, securityGroupId)
  43. //初始化client
  44. client, err = eci.NewClientWithAccessKey(regionId, accessKey, secretKey)
  45. if err != nil {
  46. panic(err)
  47. }
  48. }
  49. /**
  50. 创建
  51. */
  52. func createContainerGroup ()(string) {
  53. // Create Container Group
  54. createContainerRequest := eci.CreateCreateContainerGroupRequest()
  55. // required
  56. createContainerRequest.RegionId = regionId;
  57. createContainerRequest.SecurityGroupId = securityGroupId
  58. createContainerRequest.VSwitchId = vSwitchId
  59. createContainerRequest.ContainerGroupName = "test-go-sdk"
  60. createContainerRequest.RestartPolicy = "Never"
  61. createContainerRequestVolume := make([]eci.CreateContainerGroupVolume, 1)
  62. volume1 := &eci.CreateContainerGroupNFSVolume{
  63. Path:"/",
  64. Server:"0a1bf4a604-jaq68.cn-hangzhou.nas.aliyuncs.com",
  65. }
  66. createContainerRequestVolume[0].Name = "volume1"
  67. createContainerRequestVolume[0].Type ="NFSVolume"
  68. createContainerRequestVolume[0].NFSVolume=*volume1
  69. createContainerRequest.Volume = &createContainerRequestVolume
  70. createContainerRequestContainer := make([]eci.CreateContainerGroupContainer, 1)
  71. createContainerRequestContainer[0].Image = "nginx"
  72. createContainerRequestContainer[0].Name = "nginx-liu"
  73. // option
  74. createContainerRequestContainer[0].Cpu = requests.NewFloat(0.25)
  75. createContainerRequestContainer[0].Memory = requests.NewFloat(0.5)
  76. createContainerRequestContainer[0].ImagePullPolicy = "IfNotPresent"
  77. createContainerRequest.Container = &createContainerRequestContainer
  78. //sdk-core默认的重试次数为3,在没有加幂等的条件下,资源创建的接口底层不需要自动重试
  79. client.GetConfig().MaxRetryTime = 0
  80. createContainerGroupResponse, err := client.CreateContainerGroup(createContainerRequest)
  81. if err != nil {
  82. panic(err)
  83. }
  84. containerGroupId := createContainerGroupResponse.ContainerGroupId
  85. fmt.Println(containerGroupId)
  86. return containerGroupId
  87. }
  88. /**
  89. 删除
  90. */
  91. func deleteContainerGroup(containerGroupId string) {
  92. deleteContainerGroupRequest := eci.CreateDeleteContainerGroupRequest()
  93. deleteContainerGroupRequest.RegionId = regionId
  94. deleteContainerGroupRequest.ContainerGroupId = containerGroupId
  95. _, err := client.DeleteContainerGroup(deleteContainerGroupRequest)
  96. if err != nil {
  97. panic(err)
  98. }
  99. fmt.Println("DeleteContainerGroup ContainerGroupId :", containerGroupId)
  100. }
  101. /**
  102. 查询
  103. */
  104. func describeContainerGroup(containerGroupId string) (eci.DescribeContainerGroupsContainerGroup0) {
  105. // Describe Container Groups
  106. describeContainerGroupsRequest := eci.CreateDescribeContainerGroupsRequest()
  107. describeContainerGroupsRequest.RegionId = regionId
  108. containerGroupIds := append([]string{}, containerGroupId)
  109. containerGroupIdsString, err := json.Marshal(containerGroupIds)
  110. describeContainerGroupsRequest.ContainerGroupIds = string(containerGroupIdsString)
  111. describeContainerGroupsResponse, err := client.DescribeContainerGroups(describeContainerGroupsRequest)
  112. if err != nil {
  113. panic(err)
  114. }
  115. describeContainerGroupNumber := len(describeContainerGroupsResponse.ContainerGroups)
  116. if describeContainerGroupsResponse.TotalCount != 1 && describeContainerGroupNumber != 1 {
  117. fmt.Println("Invalid ContainerGroups count", describeContainerGroupsResponse.TotalCount, describeContainerGroupNumber)
  118. panic("Invalid ContainerGroups count")
  119. }
  120. fmt.Println("ContainerGroup status:", describeContainerGroupsResponse.ContainerGroups[0].Status, containerGroupId,)
  121. // container groups
  122. return describeContainerGroupsResponse.ContainerGroups[0]
  123. }
  124. func describeContainerGroupMetric(containerGroupId string) {
  125. describeContainerGroupMetricRequest :=eci.CreateDescribeContainerGroupMetricRequest()
  126. describeContainerGroupMetricRequest.RegionId = regionId
  127. describeContainerGroupMetricRequest.ContainerGroupId=containerGroupId
  128. response, err := client.DescribeContainerGroupMetric(describeContainerGroupMetricRequest)
  129. if err != nil {
  130. panic(err)
  131. }
  132. data, _ :=json.Marshal(response)
  133. fmt.Printf("Metrics for %s:%s\n", containerGroupId, string(data))
  134. }
  135. func describeMultiContainerGroupMetric(containerGroupIds []string) {
  136. describeContainerGroupMetricRequest
  137. :=eci.CreateDescribeMultiContainerGroupMetricRequest()
  138. describeContainerGroupMetricRequest.RegionId = regionId
  139. data,_ :=json.Marshal(containerGroupIds)
  140. describeContainerGroupMetricRequest.ContainerGroupIds=string(data)
  141. response, err := client.DescribeMultiContainerGroupMetric(describeContainerGroupMetricRequest)
  142. if err != nil {
  143. panic(err)
  144. }
  145. data, _ = json.Marshal(response)
  146. fmt.Printf("Metrics:%s\n", string(data))
  147. }
  148. func Test() {
  149. containerGroupIds := make(chan string)
  150. go func() {
  151. for i := 0; i < 1; i++ {
  152. containerGroupId := createContainerGroup()
  153. containerGroupIds <- containerGroupId
  154. }
  155. }()
  156. go func() {
  157. for containerGroupId := range containerGroupIds {
  158. for i := 0; i < 10; i++ {
  159. status := describeContainerGroup(containerGroupId).Status
  160. if Running == ContainerGroupStatus(status) {
  161. break
  162. } else {
  163. time.Sleep(5 * time.Second)
  164. }
  165. }
  166. //deleteContainerGroupById(containerGroupId)
  167. }
  168. }()
  169. //阻塞等待异步执行完,不然会提前退出。
  170. var input string
  171. fmt.Println("waiting for input to finish:")
  172. fmt.Scanln(&input)
  173. fmt.Println("test done!")
  174. }

main.go

  1. func main() {
  2. eci.Test()
  3. }