工作用 java 业余用 golang
golang 写的一个小工具,配合 crontab 实现定时生成 vultr 快照
package main
import (
"os/exec"
"encoding/json"
"time"
"os"
"log"
"fmt"
)
const (
CMD = "curl"
// Api 密钥
API_KEY = "API-Key:xxx"
SNAPSHOT_LIST_URL = "
https://api.vultr.com/v1/snapshot/list"
SNAPSHOT_DESTROY_URL= "
https://api.vultr.com/v1/snapshot/destroy"
SNAPSHOT_CREATE_URL = "
https://api.vultr.com/v1/snapshot/create"
// 实例 id
SUB_ID = "xxx"
H_ARG = "-H"
DATA_ARG = "--data"
)
type Snapshot struct {
ID string `json:"SNAPSHOTID"`
CreateDate string `json:"date_created"`
Description string `json:"description"`
Size string `json:"size"`
Status string `json:"status"`
}
func main() {
// 日志记录到文件
var fileName string
fileName = time.Now().Format("2006-01-02") + ".txt"
logFile,err := os.Create(fileName)
defer logFile.Close()
if err != nil {
log.Fatalln("open file error !")
}
log.SetOutput(logFile)
log.Println(time.Now().Format("2006-01-02 15:04:05"), "task start...")
// 获取快照列表
var needDestory bool = true
snapshotsCmd := exec.Command(CMD, H_ARG , API_KEY, SNAPSHOT_LIST_URL)
snapshotsResponse, _ := snapshotsCmd.Output()
var snapshots map[string]Snapshot
json.Unmarshal(snapshotsResponse, &snapshots)
// 快照数量
if len(snapshots) < 11 {
needDestory = false
}
log.Println(time.Now().Format("2006-01-02 15:04:05"), "snapshot number ", len(snapshots))
// 如果快照数量超过最大限制 11 时,则删除最早的那个快照
if needDestory {
var destroyID string
var theEarliestDate= time.Now()
for _, value := range snapshots {
tempDate, _ := time.Parse("2006-01-02 15:04:05", value.CreateDate)
if tempDate.Before(theEarliestDate) {
theEarliestDate = tempDate
destroyID =
value.ID }
}
log.Println(time.Now().Format("2006-01-02 15:04:05"), "destroy snapshot ", destroyID)
destroySnapshotCmd := exec.Command(CMD, H_ARG, API_KEY, SNAPSHOT_DESTROY_URL, DATA_ARG, fmt.Sprintf("SNAPSHOTID=%v", destroyID))
destroySnapshotCmd.Output()
// 延时 30 秒,防止删除快照时,出现未知错误
time.Sleep(time.Second * 10)
}
// 创建一个快照
createSnapshotCmd := exec.Command(CMD, H_ARG, API_KEY, SNAPSHOT_CREATE_URL, DATA_ARG, fmt.Sprintf("SUBID=%v", SUB_ID))
createSnapshotResponse, _ := createSnapshotCmd.Output()
var createSnapshot map[string]string
json.Unmarshal(createSnapshotResponse, &createSnapshot)
createSnapshotID := createSnapshot["SNAPSHOTID"]
log.Println(time.Now().Format("2006-01-02 15:04:05"), "create snapshot", createSnapshotID)
log.Println(time.Now().Format("2006-01-02 15:04:05"), "task end")
}