From f81888cd8ab60384a57a389c588753116037397e Mon Sep 17 00:00:00 2001 From: Ulric Qin Date: Sun, 22 May 2022 16:56:58 +0800 Subject: [PATCH] get prometheus info from api. code skelton --- src/webapi/prom/prom.go | 62 +++++++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/src/webapi/prom/prom.go b/src/webapi/prom/prom.go index 849a6b9c..9eab3e5b 100644 --- a/src/webapi/prom/prom.go +++ b/src/webapi/prom/prom.go @@ -3,6 +3,7 @@ package prom import ( "net" "net/http" + "strings" "sync" "time" @@ -15,26 +16,71 @@ type ClusterType struct { } type ClustersType struct { - datas map[string]ClusterType + datas map[string]*ClusterType mutex *sync.RWMutex } -func (cs *ClustersType) Put(name string, cluster ClusterType) { +func (cs *ClustersType) Put(name string, cluster *ClusterType) { cs.mutex.Lock() cs.datas[name] = cluster cs.mutex.Unlock() } -func (cs *ClustersType) Get(name string) (ClusterType, bool) { - cs.mutex.RLock() - defer cs.mutex.RUnlock() +func (cs *ClustersType) Get(name string) (*ClusterType, bool) { + cf := strings.ToLower(strings.TrimSpace(config.C.ClustersFrom)) + cs.mutex.RLock() 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{ - datas: make(map[string]ClusterType), + datas: make(map[string]*ClusterType), mutex: new(sync.RWMutex), } @@ -46,7 +92,7 @@ func Init() error { opts := config.C.Clusters for i := 0; i < len(opts); i++ { - cluster := ClusterType{ + cluster := &ClusterType{ Opts: opts[i], Transport: &http.Transport{ // TLSClientConfig: tlsConfig,