背景:
集群中的ds相关的服务,需要指定label的部署
package main
import (
"bytes"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
const logFilePath = "test.log"
func GetTargetIP(config string) []string {
cmd := exec.Command("kubectl", "--kubeconfig", config, "get", "nodes", "--selector=!container-runtime=containerd", "--selector=!ds-schedulable")
var outBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.Fatalf("Error executing kubectl command: %v", err)
return []string{} // 返回一个空切片表示错误
}
dataips := []string{}
// 命令成功执行,继续处理输出
out := strings.TrimSpace(outBuffer.String())
ips := strings.Split(out, "\n")
for _, data := range ips {
if !strings.Contains(data, "NAME") {
lines := strings.Split(data, "\n")
for _, line := range lines {
fileds := strings.Fields(line)
if len(fileds) > 0 {
dataips = append(dataips, fileds[0])
}
}
}
}
return dataips
}
func LabelsIp(config string, ip string) {
cmd := exec.Command("kubectl", "--kubeconfig", config, "label", "node", ip, "ds-schedulable=", "container-runtime=containerd", "--overwrite")
var outBuffer bytes.Buffer
cmd.Stdout = &outBuffer
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.Fatalf("Error executing kubectl command: %v", err)
} else {
log.Printf("lable success ip: %s", ip)
}
}
// 获取目录下的所有文件名
func getFilesInDirectory(directoryPath string) ([]string, error) {
var fileNames []string
// 使用 filepath.Walk 遍历目录
err := filepath.Walk(directoryPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// 忽略目录本身
if path != directoryPath {
// 获取文件或目录的相对路径
relativePath, _ := filepath.Rel(directoryPath, path)
fileNames = append(fileNames, relativePath)
}
return nil
})
if err != nil {
return nil, err
}
return fileNames, nil
}
func crontab() {
logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Error opening log file: %v", err)
}
defer logFile.Close()
directoryPath := "/home/sunlixin/go/feed-node/config"
fileNames, err := getFilesInDirectory(directoryPath)
log.Println(fileNames)
// fmt.Println(fileNames)
if err != nil {
log.Fatalf("Error getting files in directory: %v", err)
}
for _, fileName := range fileNames {
// fmt.Println(fileName)
configpath := directoryPath + "/" + fileName
targetIPs := GetTargetIP(configpath)
// fmt.Println(len(targetIPs))
log.Printf("cluster:%s,num:%d", fileName, len(targetIPs))
for _, ip := range targetIPs {
LabelsIp(configpath, ip)
}
}
}
func main(){
interval := 10 * time.Minute
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
crontab()
}
}
}
标签:node,log,err,nil,cmd,label,集群,os,string From: https://www.cnblogs.com/Direction-of-efforts/p/18065085