github.com/kubewharf/katalyst-core@v0.5.3/pkg/metaserver/agent/metric/provisioner/rodan/client/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 client 18 19 import ( 20 "fmt" 21 "io" 22 "net/http" 23 24 "github.com/kubewharf/katalyst-core/pkg/metaserver/agent/metric/provisioner/rodan/types" 25 "github.com/kubewharf/katalyst-core/pkg/metaserver/agent/pod" 26 ) 27 28 type RodanClient struct { 29 urls map[string]string 30 31 fetcher pod.PodFetcher 32 33 metricFunc MetricFunc 34 } 35 36 func NewRodanClient(fetcher pod.PodFetcher, metricFunc MetricFunc, port int) *RodanClient { 37 urls := make(map[string]string) 38 for path := range types.MetricsMap { 39 urls[path] = fmt.Sprintf("http://localhost:%d%s", port, path) 40 } 41 42 if metricFunc == nil { 43 metricFunc = getMetrics 44 } 45 46 return &RodanClient{ 47 fetcher: fetcher, 48 urls: urls, 49 metricFunc: metricFunc, 50 } 51 } 52 53 type MetricFunc func(url string, params map[string]string) ([]byte, error) 54 55 func getMetrics(url string, params map[string]string) ([]byte, error) { 56 if len(params) != 0 { 57 firstParam := true 58 59 for k, v := range params { 60 if firstParam { 61 url += "?" 62 firstParam = false 63 } else { 64 url += "&" 65 } 66 url = fmt.Sprintf("%s%s=%s", url, k, v) 67 } 68 } 69 70 rsp, err := http.Get(url) 71 if err != nil { 72 return nil, fmt.Errorf("failed to get metrics, url: %v, err: %v", url, err) 73 } 74 defer func() { _ = rsp.Body.Close() }() 75 76 if rsp.StatusCode != 200 { 77 return nil, fmt.Errorf("invalid http response status code %d, status: %s, url: %s", rsp.StatusCode, rsp.Status, url) 78 } 79 80 return io.ReadAll(rsp.Body) 81 }