库
"github.com/prometheus/client_golang/api"
Pro "github.com/prometheus/client_golang/api/prometheus/v1"
获取平台已部署的prometheus的client
var systemPublicEndpoint api.Client
//连接prometheus,无多集群管理时无需传入集群ID
func ConnectPro(clusterID string) api.Client {
ns := "System" //部署在哪个命名空间
name := "prometheus:prometheus-server" //prometheus-server 组件地址(对应k8s集群中prometheus应用组件的id)
if nil != systemPublicEndpoint {
return systemPublicEndpoint
}
cli, _ := utils.GetPrometheusPublicCli(clusterID, ns, name)
systemPublicEndpoint = cli
return cli
}
func GetPrometheusPublicCli(clusterID, namespace, name string) (api.Client, error) {
//省略获取普罗米修斯server暴露的访问地址逻辑,获取地址addr后组成Config传入
cfg := api.Config{Address: "http://" + addr} //地址示例:http://192.168.104.65:30870
c, err := api.NewClient(cfg)
return c, err
}
以节点cpu的平均使用率为例调api查询:
c1 := ConnectPro(s.Get(consts.KeyCluster).(string))
//mon.Start与mon.End为起始、终止时间,mon为前端传入的对象
sta, _ := strconv.Atoi(mon.Start)
en, _ := strconv.Atoi(mon.End)
rat := en - sta
rat = rat + 60
if rat < 120 {
rat = 120
}
//分子/分母=比率,mon.Node为节点名称
q1 := "sum(rate (container_cpu_usage_seconds_total{id='/',kubernetes_io_hostname=~'" + mon.Node + "$'" + "}[" + strconv.Itoa(rat) + "s]))"
q2 := "/sum (machine_cpu_cores{kubernetes_io_hostname=~'" + mon.Node + "$'})*100"
q := q1 + q2
c, err := pro.NewAPI(c1).Query(context.Background(), q, mon.End)
if err != nil {
errMsg := fmt.Sprint("failed to Query NodeCpuRate:", err.Error())
logError(errMsg)
ctx.Resp.Header().Set(consts.KeyErrorInfo, errMsg)
return macaron.ReturnStruct{Code: http.StatusBadRequest, Msg: errMsg}
}
return macaron.ReturnStruct{Data: c}
查询返回:
{"message":"","code":200,"data":[{"metric":{},"value":[1572431847,"15.910989253603638"]}]}
即15.9%