github.com/kubewharf/katalyst-core@v0.5.3/pkg/controller/resource-recommend/datasource/prometheus/prometheus_client.go (about) 1 /* 2 Copyright 2022 The Katalyst Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package prometheus 18 19 import ( 20 "context" 21 "crypto/tls" 22 "net" 23 "net/http" 24 "net/url" 25 "time" 26 27 prometheusapi "github.com/prometheus/client_golang/api" 28 29 "github.com/kubewharf/katalyst-core/pkg/controller/resource-recommend/datasource/prometheus/auth" 30 ) 31 32 // PromConfig represents the config of prometheus 33 type PromConfig struct { 34 Address string 35 Timeout time.Duration 36 KeepAlive time.Duration 37 InsecureSkipVerify bool 38 Auth auth.ClientAuth 39 40 QueryConcurrency int 41 BRateLimit bool 42 MaxPointsLimitPerTimeSeries int 43 TLSHandshakeTimeoutInSecond time.Duration 44 45 BaseFilter string 46 } 47 48 type prometheusAuthClient struct { 49 client prometheusapi.Client 50 } 51 52 // URL implements prometheus client interface 53 func (p *prometheusAuthClient) URL(ep string, args map[string]string) *url.URL { 54 return p.client.URL(ep, args) 55 } 56 57 // Do implements prometheus client interface, wrapped with an auth info 58 func (p *prometheusAuthClient) Do(ctx context.Context, request *http.Request) (*http.Response, []byte, error) { 59 return p.client.Do(ctx, request) 60 } 61 62 // NewPrometheusClient returns a prometheus.Client 63 func NewPrometheusClient(config *PromConfig) (prometheusapi.Client, error) { 64 tlsConfig := &tls.Config{InsecureSkipVerify: config.InsecureSkipVerify} 65 66 var rt http.RoundTripper = &http.Transport{ 67 Proxy: http.ProxyFromEnvironment, 68 DialContext: (&net.Dialer{ 69 Timeout: config.Timeout, 70 KeepAlive: config.KeepAlive, 71 }).DialContext, 72 TLSHandshakeTimeout: config.TLSHandshakeTimeoutInSecond, 73 TLSClientConfig: tlsConfig, 74 } 75 76 t, err := auth.GetRoundTripper(&config.Auth, rt, auth.GetRegisteredRoundTripperFactoryInitializers()) 77 if err != nil { 78 return nil, err 79 } 80 81 pc := prometheusapi.Config{ 82 Address: config.Address, 83 RoundTripper: t, 84 } 85 return newPrometheusAuthClient(pc) 86 } 87 88 func newPrometheusAuthClient(config prometheusapi.Config) (prometheusapi.Client, error) { 89 c, err := prometheusapi.NewClient(config) 90 if err != nil { 91 return nil, err 92 } 93 94 client := &prometheusAuthClient{ 95 client: c, 96 } 97 98 return client, nil 99 }