这个是很多人的痛,如果遇到D哥C哥一晚上起来房子就不见了。
这个代码会检测套餐流量包使用情况,如果低于限定值就停机,扔进crontab定时执行一下就好了。安心睡觉吧。

package main

import (
    "fmt"

    openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    swas_open20200601 "github.com/alibabacloud-go/swas-open-20200601/client"
    "github.com/alibabacloud-go/tea/tea"
)

const (
    ReservedGB = 10                                 // 预留流量GB,低于此值将自动关机
    RegionId   = "cn-hongkong"                      //区域ID
    Key        = "XXXX"         //AccessKey
    Secret     = "XXXX"   //AccessSecret
    InstanceID = "XXXX" //实例ID
)

func CreateClient(Key, Secret string) (_result *swas_open20200601.Client, _err error) {
    config := &openapi.Config{
        AccessKeyId:     tea.String(Key),
        AccessKeySecret: tea.String(Secret),
    }
    config.Endpoint = tea.String("swas." + RegionId + ".aliyuncs.com")
    _result = &swas_open20200601.Client{}
    _result, _err = swas_open20200601.NewClient(config)
    return _result, _err
}

// 返回套餐已用流量,总流量,错误信息
func GetTrafficQuota(Key, Secret, InstanceID string) (int, int, error) {
    client, err := CreateClient(Key, Secret)
    if err != nil {
        return 0, 0, err
    }

    request := &swas_open20200601.ListInstancesTrafficPackagesRequest{
        InstanceIds: tea.String("[\"" + InstanceID + "\"]"),
        RegionId:    tea.String(RegionId),
    }

    response, err := client.ListInstancesTrafficPackages(request)
    if err != nil {
        return 0, 0, err
    }

    return int(*response.Body.InstanceTrafficPackageUsages[0].TrafficUsed), int(*response.Body.InstanceTrafficPackageUsages[0].TrafficPackageTotal), nil
}

func HaltServer(Key, Secret, InstanceID string) error {
    client, err := CreateClient(Key, Secret)
    if err != nil {
        return err
    }

    request := &swas_open20200601.StopInstanceRequest{
        InstanceId: tea.String(InstanceID),
        RegionId:   tea.String(RegionId),
    }

    _, err = client.StopInstance(request)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    Used, Total, err := GetTrafficQuota(Key, Secret, InstanceID)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("Used: %d GB, Total: %d GB\n", BytesToGB(Used), BytesToGB(Total))
    if BytesToGB(Total-Used) < ReservedGB {
        fmt.Printf("Warning: The remaining traffic is less than %dGB,server halt!\n", ReservedGB)
        HaltServer(Key, Secret, InstanceID)
    } else {
        fmt.Println("The remaining traffic is enough!")
    }
}

func BytesToGB(b int) int {
    return b / 1024 / 1024 / 1024
}

标签: none

添加新评论

*如果只是需要与我沟通联系,请telegram @ohyessure, 而不要用评论方式,因为没有你的个人资料,我无法回复及联络你。