get prometheus info from api. code skelton

This commit is contained in:
Ulric Qin 2022-05-22 16:56:58 +08:00
parent 6a7b543ad6
commit f81888cd8a
1 changed files with 54 additions and 8 deletions

View File

@ -3,6 +3,7 @@ package prom
import ( import (
"net" "net"
"net/http" "net/http"
"strings"
"sync" "sync"
"time" "time"
@ -15,26 +16,71 @@ type ClusterType struct {
} }
type ClustersType struct { type ClustersType struct {
datas map[string]ClusterType datas map[string]*ClusterType
mutex *sync.RWMutex mutex *sync.RWMutex
} }
func (cs *ClustersType) Put(name string, cluster ClusterType) { func (cs *ClustersType) Put(name string, cluster *ClusterType) {
cs.mutex.Lock() cs.mutex.Lock()
cs.datas[name] = cluster cs.datas[name] = cluster
cs.mutex.Unlock() cs.mutex.Unlock()
} }
func (cs *ClustersType) Get(name string) (ClusterType, bool) { func (cs *ClustersType) Get(name string) (*ClusterType, bool) {
cs.mutex.RLock() cf := strings.ToLower(strings.TrimSpace(config.C.ClustersFrom))
defer cs.mutex.RUnlock()
cs.mutex.RLock()
c, has := cs.datas[name] c, has := cs.datas[name]
return c, has cs.mutex.RUnlock()
if has {
return c, true
}
if cf == "" || cf == "config" {
return nil, false
}
// read from api
if cf == "api" {
return cs.GetFromAPI(name)
}
return nil, false
}
func (cs *ClustersType) GetFromAPI(name string) (*ClusterType, bool) {
// get from api, parse body
// 1. not found? return nil, false
// 2. found? new ClusterType, put, return
opt := config.ClusterOptions{
Name: "",
Prom: "",
BasicAuthUser: "",
BasicAuthPass: "",
Timeout: 60000,
DialTimeout: 5000,
MaxIdleConnsPerHost: 32,
}
cluster := &ClusterType{
Opts: opt,
Transport: &http.Transport{
// TLSClientConfig: tlsConfig,
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: time.Duration(opt.DialTimeout) * time.Millisecond,
}).DialContext,
ResponseHeaderTimeout: time.Duration(opt.Timeout) * time.Millisecond,
MaxIdleConnsPerHost: opt.MaxIdleConnsPerHost,
},
}
cs.Put(opt.Name, cluster)
return cluster, true
} }
var Clusters = ClustersType{ var Clusters = ClustersType{
datas: make(map[string]ClusterType), datas: make(map[string]*ClusterType),
mutex: new(sync.RWMutex), mutex: new(sync.RWMutex),
} }
@ -46,7 +92,7 @@ func Init() error {
opts := config.C.Clusters opts := config.C.Clusters
for i := 0; i < len(opts); i++ { for i := 0; i < len(opts); i++ {
cluster := ClusterType{ cluster := &ClusterType{
Opts: opts[i], Opts: opts[i],
Transport: &http.Transport{ Transport: &http.Transport{
// TLSClientConfig: tlsConfig, // TLSClientConfig: tlsConfig,