全部产品
Search
文档中心

Go SDK使用示例

更新时间: 2021-07-02

本文介绍如何使用ECI的Go SDK,并给出基本操作示例。

安装SDK

您可以从GitHub获取Go SDK。

代码示例

const.go

package eci
type ContainerGroupStatus string
const (
        Scheduling     = ContainerGroupStatus("Scheduling")
        Pending        = ContainerGroupStatus("Pending")
        Running        = ContainerGroupStatus("Running")
        Succeeded      = ContainerGroupStatus("Succeeded")
        Failed         = ContainerGroupStatus("Failed")
        Restarting     = ContainerGroupStatus("Restarting")
        Updating       = ContainerGroupStatus("Updating")
        ScheduleFailed = ContainerGroupStatus("ScheduleFailed")
)
type ContainerStatus string
const (
        waiting    = ContainerStatus("Waiting")
        running    = ContainerStatus("Running")
        terminated = ContainerStatus("Terminated")
)

config.conf

[eci_conf]
#测试账号ak
access_key = xxx
secret_key = xxx
#region
region_id=cn-hangzhou
#每个region下的资源信息,json格式
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参数参考如下:

{
    "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"
    },
    "ap-southeast-1": {
        "securityGroupId": "sg-t4n23ppw7fm5to7cnib9",
        "vSwitchId": "vsw-t4nr1xt8zupxg00unnmg9",
        "zoneId": "ap-southeast-1b"
    },
    "cn-zhangjiakou": {
        "securityGroupId": "sg-8vb96lku1dgq71ckh98g",
        "vSwitchId": "vsw-8vbtnz5878r3bcio7cpyx",
        "zoneId": "cn-zhangjiakou-a"
    }
}

eci.go

package eci
import (
        "encoding/json"
        "fmt"
        "github.com/Unknwon/goconfig"
        "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
        "github.com/aliyun/alibaba-cloud-sdk-go/services/eci"
        "math"
        "os"
        "reflect"
        "strconv"
        "time"
)
var accessKey string
var secretKey string
var regionId string
var zoneId string
var securityGroupId string
var vSwitchId string
var client *eci.Client
/**
获取配置信息
 */
func init() {
        var cfg *goconfig.ConfigFile
        config, err := goconfig.LoadConfigFile("./eci/config.conf") //加载配置文件
        if err != nil {
                fmt.Println("get config file error:", err.Error())
                os.Exit(-1)
        }
        cfg = config
        accessKey, _ = cfg.GetValue("eci_conf", "access_key")
        secretKey, _ = cfg.GetValue("eci_conf", "secret_key")
        regionId, _ = cfg.GetValue("eci_conf", "region_id")
        var regionInfo map[string](map[string](string));
        value, _ := cfg.GetValue("eci_conf", "region_info")
        json.Unmarshal([]byte(value), &regionInfo)
        zoneId = regionInfo[regionId]["zoneId"]
        securityGroupId = regionInfo[regionId]["securityGroupId"]
        vSwitchId = regionInfo[regionId]["vSwitchId"]
        fmt.Printf("init success[ access_key:%s, secret_key:%s, region_id:%s, zoneId:%s, vSwitchId:%s, securityGroupId:%s]\n",
                accessKey, secretKey, regionId, zoneId, vSwitchId, securityGroupId)
    //初始化client
    client, err = eci.NewClientWithAccessKey(regionId, accessKey, secretKey)
        if err != nil {
                panic(err)
        }
}
/**
创建
*/
func createContainerGroup ()(string)  {
        // Create Container Group
        createContainerRequest := eci.CreateCreateContainerGroupRequest()
        // required
        createContainerRequest.RegionId = regionId;
        createContainerRequest.SecurityGroupId = securityGroupId
        createContainerRequest.VSwitchId = vSwitchId
        createContainerRequest.ContainerGroupName = "test-go-sdk"
        createContainerRequest.RestartPolicy = "Never"
        createContainerRequestVolume := make([]eci.CreateContainerGroupVolume, 1)
        volume1 := &eci.CreateContainerGroupNFSVolume{
                Path:"/",
                Server:"0a1bf4a604-jaq68.cn-hangzhou.nas.aliyuncs.com",
        }
        createContainerRequestVolume[0].Name = "volume1"
        createContainerRequestVolume[0].Type ="NFSVolume"
        createContainerRequestVolume[0].NFSVolume=*volume1
        createContainerRequest.Volume = &createContainerRequestVolume
        createContainerRequestContainer := make([]eci.CreateContainerGroupContainer, 1)
        createContainerRequestContainer[0].Image = "nginx"
        createContainerRequestContainer[0].Name = "nginx-liu"
        // option
        createContainerRequestContainer[0].Cpu = requests.NewFloat(0.25)
        createContainerRequestContainer[0].Memory = requests.NewFloat(0.5)
        createContainerRequestContainer[0].ImagePullPolicy = "IfNotPresent"
        createContainerRequest.Container = &createContainerRequestContainer
        //sdk-core默认的重试次数为3,在没有加幂等的条件下,资源创建的接口底层不需要自动重试
        client.GetConfig().MaxRetryTime = 0
        createContainerGroupResponse, err := client.CreateContainerGroup(createContainerRequest)
        if err != nil {
                panic(err)
        }
        containerGroupId := createContainerGroupResponse.ContainerGroupId
        fmt.Println(containerGroupId)
        return containerGroupId
}
/**
删除
*/
func deleteContainerGroup(containerGroupId string) {
        deleteContainerGroupRequest := eci.CreateDeleteContainerGroupRequest()
        deleteContainerGroupRequest.RegionId = regionId
        deleteContainerGroupRequest.ContainerGroupId = containerGroupId
    _, err := client.DeleteContainerGroup(deleteContainerGroupRequest)
        if err != nil {
                panic(err)
        }
        fmt.Println("DeleteContainerGroup ContainerGroupId :", containerGroupId)
}
/**
查询
*/
func describeContainerGroup(containerGroupId string) (eci.DescribeContainerGroupsContainerGroup0)  {
        // Describe Container Groups
        describeContainerGroupsRequest := eci.CreateDescribeContainerGroupsRequest()
        describeContainerGroupsRequest.RegionId = regionId
        containerGroupIds := append([]string{}, containerGroupId)
        containerGroupIdsString, err := json.Marshal(containerGroupIds)
        describeContainerGroupsRequest.ContainerGroupIds = string(containerGroupIdsString)
        describeContainerGroupsResponse, err := client.DescribeContainerGroups(describeContainerGroupsRequest)
        if err != nil {
                panic(err)
        }
        describeContainerGroupNumber := len(describeContainerGroupsResponse.ContainerGroups)
        if describeContainerGroupsResponse.TotalCount != 1 && describeContainerGroupNumber != 1 {
                fmt.Println("Invalid ContainerGroups count", describeContainerGroupsResponse.TotalCount, describeContainerGroupNumber)
                panic("Invalid ContainerGroups count")
        }
        fmt.Println("ContainerGroup status:", describeContainerGroupsResponse.ContainerGroups[0].Status, containerGroupId,)
        // container groups
        return describeContainerGroupsResponse.ContainerGroups[0]
}
func describeContainerGroupMetric(containerGroupId string)  {
        describeContainerGroupMetricRequest :=eci.CreateDescribeContainerGroupMetricRequest()
        describeContainerGroupMetricRequest.RegionId = regionId
        describeContainerGroupMetricRequest.ContainerGroupId=containerGroupId
        response, err := client.DescribeContainerGroupMetric(describeContainerGroupMetricRequest)
        if err != nil {
                panic(err)
        }
        data, _ :=json.Marshal(response)
        fmt.Printf("Metrics for %s:%s\n", containerGroupId, string(data))
}
func describeMultiContainerGroupMetric(containerGroupIds []string)  {
        describeContainerGroupMetricRequest
    :=eci.CreateDescribeMultiContainerGroupMetricRequest()
        describeContainerGroupMetricRequest.RegionId = regionId
        data,_ :=json.Marshal(containerGroupIds)
        describeContainerGroupMetricRequest.ContainerGroupIds=string(data)
        response, err := client.DescribeMultiContainerGroupMetric(describeContainerGroupMetricRequest)
        if err != nil {
                panic(err)
        }
        data, _ = json.Marshal(response)
        fmt.Printf("Metrics:%s\n", string(data))
}
func Test() {
        containerGroupIds := make(chan string)
        go func() {
                for i := 0; i < 1; i++ {
                        containerGroupId := createContainerGroup()
                        containerGroupIds <- containerGroupId
                }
        }()
        go func() {
                for containerGroupId := range containerGroupIds {
                        for i := 0; i < 10; i++ {
                                status := describeContainerGroup(containerGroupId).Status
                                if Running == ContainerGroupStatus(status) {
                                        break
                                } else {
                                        time.Sleep(5 * time.Second)
                                }
                        }
                        //deleteContainerGroupById(containerGroupId)
                }
        }()
        //阻塞等待异步执行完,不然会提前退出。
        var input string
        fmt.Println("waiting for input to finish:")
        fmt.Scanln(&input)
        fmt.Println("test done!")
}

main.go

func main() {
        eci.Test()
}