-
Notifications
You must be signed in to change notification settings - Fork 0
/
deployment_json.go
72 lines (61 loc) · 1.83 KB
/
deployment_json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package k8s_info
import (
"encoding/json"
"fmt"
"log"
"os/exec"
"strings"
"sync"
"gopkg.in/natefinch/lumberjack.v2"
)
// version v0.1.13
var (
DeploymentData []map[string]interface{} // 将变量名首字母大写以导出
DeploymentDataMutex sync.RWMutex
kubeconfigPath string
)
func SetKubeconfigPath(path string) {
kubeconfigPath = path
}
// UpdateDeploymentData 获取k8s deployment资源生成json数据
func UpdateDeploymentData(namespaces ...string) {
log.Println("执行kubectl命令")
cmd := exec.Command("kubectl", "--kubeconfig="+kubeconfigPath, "--output", "json", "get", "deployment", "-A")
stdout, err := cmd.Output()
if err != nil {
log.Printf("Error executing kubectl command: %s\n", err)
return
}
log.Println("JSON解码")
var data map[string]interface{}
if err := json.Unmarshal(stdout, &data); err != nil {
log.Printf("Error unmarshalling JSON data: %s\n", err)
return
}
log.Println("正在生成新的Deployment数据")
items := data["items"].([]interface{})
var newDeploymentData []map[string]interface{}
for _, item := range items {
app := item.(map[string]interface{})
metadata := app["metadata"].(map[string]interface{})
name := metadata["name"].(string)
namespace := metadata["namespace"].(string)
for _, ns := range namespaces {
if strings.Contains(namespace, ns) {
newDeploymentData = append(newDeploymentData, map[string]interface{}{
"name": fmt.Sprintf("%s/%s", namespace, name),
"value": fmt.Sprintf("export APP_NAME=%s;export NAME_SPACE=%s;", name, namespace),
"ns": namespace,
})
}
}
}
log.Println("Deployment数据更新完成")
DeploymentDataMutex.Lock()
DeploymentData = newDeploymentData
DeploymentDataMutex.Unlock()
}
// SetLogger 设置k8s_info包的日志输出
func SetLogger(logger *lumberjack.Logger) {
log.SetOutput(logger)
}