Go:agent构建

时间:Nov. 5, 2020 分类:

目录:

main.go

这里只写启动调用RootCmd.Execute()

package main

func main() {
    if err := RootCmd.Execute(); err != nil {
        panic(err)

    }
}

cmd.go

用于加载配置文件,然后启动真正的服务RunCmd

package main

import (
    goflag "flag"
    "fmt"
    "github.com/spf13/cobra"
    "github.com/spf13/pflag"
    "github.com/spf13/viper"
)

var RootCmd = &cobra.Command{
    Use:   "k8snet-exporter",
    Short: "检查slave网络通讯",
    Long:  "检查slave网络是否存在问题",
    Run: func(cmd *cobra.Command, args []string) {
        cmd.Root().Help()
    },
}
var (
    configPath string
)

// 初始化参数的配置文件目录
func init() {
    RootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "./", "配置文件价路径")
    cobra.OnInitialize(initConfig)
    pflag.CommandLine.AddGoFlagSet(goflag.CommandLine)

}

// 加载参数
func initConfig() {
    viper.SetConfigFile("toml")
    viper.SetConfigName("config")
    viper.SetConfigType("toml")
    viper.AddConfigPath(configPath)
    viper.AutomaticEnv()
    if err := viper.ReadInConfig(); err == nil {
        //fmt.Println("Using config file:", viper.ConfigFileUsed())
    } else {
        fmt.Println(err)
    }
}

// 启动服务
func init() {
    RootCmd.AddCommand(RunCmd)
}

run.go

接收服务参数,启动实际的业务逻辑

package main

import (
    "flag"
    "github.com/golang/glog"
    "github.com/prometheus/client_golang/prometheus/promhttp"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "net/http"
    "time"
)

var RunCmd = &cobra.Command{
    Use:   "run",
    Short: "负责slave网络监控",
    Long:  "定时访问slave上pod,获取网络情况,并保留给prometheus",
    Run: func(cmd *cobra.Command, args []string) {
        flag.Parse()
        defer glog.Flush()
        kubectl, err := KubernetesClient(viper.GetString("kubernetes.host"), viper.GetString("kubernetes.token"), viper.GetString("kubernetes.tls.ca"), viper.GetString("kubernetes.tls.caData"), viper.GetString("kubernetes.userAgent"), viper.GetBool("kubernetes.tls.insecure"))
        if err != nil {
            panic(err)
        }
        http.Handle("/metrics", promhttp.Handler())
        go http.ListenAndServe(":9876", nil)
        for {
            nodeList, err := GetNodeInfo(kubectl)
            ApiserverRequestCounts(viper.GetString("kubernetes.host"))
            if err != nil {
                glog.Errorf("get nodelist error:%s", err.Error())
                Endpoints_status(viper.GetString("kubernetes.host"), 0)
            } else {
                glog.V(15).Infof("get nodelist:%#v", nodeList)
                Endpoints_status(viper.GetString("kubernetes.host"), 1)
            }
            for _, node := range nodeList {
                if node.Checkaddr == nil {
                    glog.Error("node%s no has check pod", node.NodeName)
                    NetworkConitionPodLoss(node.NodeName, 1)
                    NetworkConitionReady(node.NodeName, 0)
                } else {
                    glog.V(3).Infof("node:%s check pod:%s", node.NodeName, node.Checkaddr.Addr)
                    go func(nodename string, addr string) {
                        url := "http://" + addr + "/env/health"
                        _, err := Check(url)
                        if err != nil {
                            glog.Error("node:%s,url:%s error:%s", nodename, url, err.Error())
                            NetworkConitionReady(nodename, 0)
                            NetworkConitionPodLoss(nodename, 0)
                        } else {
                            glog.V(5).Infof("node:%s,url:%s success", nodename, url)
                            NetworkConitionReady(nodename, 1)
                            NetworkConitionPodLoss(nodename, 0)
                        }

                    }(node.NodeName, node.Checkaddr.Addr)
                }
            }
            UpdateNodesmapAndDeleteDisabledLabel(nodeList)
            time.Sleep(1 * time.Minute)
        }

    },
}

// 接收参数
func parameter() {
    RootCmd.PersistentFlags().StringP("token", "", "", "use https token")
    viper.BindPFlag("kubernetes.token", RootCmd.PersistentFlags().Lookup("token"))

    RootCmd.PersistentFlags().StringP("host", "", "", "kubernetes api addr")
    viper.BindPFlag("kubernetes.host", RootCmd.PersistentFlags().Lookup("host"))

    RootCmd.PersistentFlags().StringP("userAgent", "", "", "UserAgent")
    viper.BindPFlag("kubernetes.userAgent", RootCmd.PersistentFlags().Lookup("userAgent"))

    RootCmd.PersistentFlags().IntP("timeout", "", 10, "timeout")
    viper.BindPFlag("kubernetes.timeout", RootCmd.PersistentFlags().Lookup("timeout"))

    RootCmd.PersistentFlags().StringP("ca", "", "", "caFile")
    viper.BindPFlag("kubernetes.tls.ca", RootCmd.PersistentFlags().Lookup("ca"))

    RootCmd.PersistentFlags().StringP("caData", "", "", "caData")
    viper.BindPFlag("kubernetes.tls.caData", RootCmd.PersistentFlags().Lookup("caData"))

    RootCmd.PersistentFlags().BoolP("insecure", "", true, "insecure is")
    viper.BindPFlag("kubernetes.tls.insecure", RootCmd.PersistentFlags().Lookup("insecure"))
}

func init() {
    parameter()
}