|
| 1 | +/* |
| 2 | +Copyright 2020 The Flux 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 providers |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "crypto/tls" |
| 22 | + "encoding/json" |
| 23 | + "fmt" |
| 24 | + "io" |
| 25 | + "os" |
| 26 | + "net" |
| 27 | + "net/http" |
| 28 | + "net/url" |
| 29 | + "time" |
| 30 | + |
| 31 | + flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" |
| 32 | + "k8s.io/metrics/pkg/apis/external_metrics" |
| 33 | +) |
| 34 | + |
| 35 | +const ( |
| 36 | + metricServiceEndpointPath = "/apis/external.metrics.k8s.io/v1beta1" |
| 37 | + namespacesPath = "/namespaces/" |
| 38 | + |
| 39 | + authorizationHeaderKey = "Authorization" |
| 40 | + applicationBearerToken = "token" |
| 41 | +) |
| 42 | + |
| 43 | +// ExternalMetricsProvider executes datadog queries |
| 44 | +type ExternalMetricsProvider struct { |
| 45 | + metricServiceEndpoint string |
| 46 | + bearerToken string // Find out if we can get authoritative answer that this is the standard |
| 47 | + |
| 48 | + timeout time.Duration |
| 49 | + client *http.Client |
| 50 | +} |
| 51 | + |
| 52 | +// NewExternalMetricsProvider takes a canary spec, a provider spec, and |
| 53 | +// returns a client ready to execute queries against the Service |
| 54 | +func NewExternalMetricsProvider(metricInterval string, |
| 55 | + provider flaggerv1.MetricTemplateProvider, |
| 56 | + credentials map[string][]byte) (*ExternalMetricsProvider, error) { |
| 57 | + |
| 58 | + if provider.Address == "" { |
| 59 | + return nil, fmt.Errorf("the Url of the external metric service must be provided") |
| 60 | + } |
| 61 | + |
| 62 | + externalMetrics := ExternalMetricsProvider{ |
| 63 | + metricServiceEndpoint: fmt.Sprintf("%s%s", provider.Address, metricServiceEndpointPath), |
| 64 | + timeout: 5 * time.Second, |
| 65 | + client: http.DefaultClient, |
| 66 | + } |
| 67 | + |
| 68 | + if provider.InsecureSkipVerify { |
| 69 | + t := http.DefaultTransport.(*http.Transport).Clone() |
| 70 | + t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} |
| 71 | + externalMetrics.client = &http.Client{Transport: t} |
| 72 | + } |
| 73 | + |
| 74 | + if b, ok := credentials[applicationBearerToken]; ok { |
| 75 | + externalMetrics.bearerToken = string(b) |
| 76 | + } else { |
| 77 | + // Read service account token from volume mount |
| 78 | + token, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token") |
| 79 | + if err != nil { |
| 80 | + return nil, fmt.Errorf("error reading service account token: %w", err) |
| 81 | + } |
| 82 | + if len(token) == 0 { |
| 83 | + return nil, fmt.Errorf("pod's service account token is empty") |
| 84 | + } |
| 85 | + externalMetrics.bearerToken = string(token) |
| 86 | + } |
| 87 | + |
| 88 | + return &externalMetrics, nil |
| 89 | +} |
| 90 | + |
| 91 | +// RunQuery retrieves the ExternalMetricValue from the ExternalMetricsProvider.metricServiceUrl |
| 92 | +// and returns the first result as a float64 |
| 93 | +func (p *ExternalMetricsProvider) RunQuery(query string) (float64, error) { |
| 94 | + |
| 95 | + metricsQueryUrl := fmt.Sprintf("%s%s%s", p.metricServiceEndpoint, namespacesPath, query) |
| 96 | + //TODO add labelSelector as queryString (in the docs of this provider as it's embedded in the query string) |
| 97 | + |
| 98 | + req, err := http.NewRequest("GET", metricsQueryUrl, nil) |
| 99 | + if err != nil { |
| 100 | + return 0, fmt.Errorf("error http.NewRequest: %w", err) |
| 101 | + } |
| 102 | + if p.bearerToken != "" { |
| 103 | + req.Header.Add(authorizationHeaderKey, fmt.Sprintf("Bearer %s", p.bearerToken)) |
| 104 | + } |
| 105 | + |
| 106 | + ctx, cancel := context.WithTimeout(req.Context(), p.timeout) |
| 107 | + defer cancel() |
| 108 | + r, err := p.client.Do(req.WithContext(ctx)) |
| 109 | + if err != nil { |
| 110 | + return 0, fmt.Errorf("request failed: %w", err) |
| 111 | + } |
| 112 | + |
| 113 | + defer r.Body.Close() |
| 114 | + b, err := io.ReadAll(r.Body) |
| 115 | + if err != nil { |
| 116 | + return 0, fmt.Errorf("error reading body: %w", err) |
| 117 | + } |
| 118 | + |
| 119 | + if r.StatusCode != http.StatusOK { |
| 120 | + return 0, fmt.Errorf("error response: %s: %w", string(b), err) |
| 121 | + } |
| 122 | + |
| 123 | + var res external_metrics.ExternalMetricValueList |
| 124 | + if err := json.Unmarshal(b, &res); err != nil { |
| 125 | + return 0, fmt.Errorf("error unmarshaling result: %w, '%s'", err, string(b)) |
| 126 | + } |
| 127 | + |
| 128 | + if len(res.Items) < 1 { |
| 129 | + return 0, fmt.Errorf("invalid response: %s: %w", string(b), ErrNoValuesFound) |
| 130 | + } |
| 131 | + |
| 132 | + vs := res.Items[0].Value.AsApproximateFloat64() |
| 133 | + |
| 134 | + return vs, nil |
| 135 | +} |
| 136 | + |
| 137 | +// IsOnline will only check the TCP endpoint reachability, |
| 138 | +// given that external metric servers don't have a common health check endpoint defined |
| 139 | +func (p *ExternalMetricsProvider) IsOnline() (bool, error) { |
| 140 | + var d net.Dialer |
| 141 | + |
| 142 | + ctx, cancel := context.WithTimeout(context.Background(), p.timeout) |
| 143 | + defer cancel() |
| 144 | + |
| 145 | + metricServiceUrl, err := url.Parse(p.metricServiceEndpoint) |
| 146 | + if err != nil { |
| 147 | + return false, fmt.Errorf("error parsing metric service url: %w", err) |
| 148 | + } |
| 149 | + |
| 150 | + conn, err := d.DialContext(ctx, "tcp", metricServiceUrl.Host) |
| 151 | + defer conn.Close() |
| 152 | + if err != nil { |
| 153 | + return false, fmt.Errorf("connection failed: %w", err) |
| 154 | + } |
| 155 | + return true, err |
| 156 | +} |
0 commit comments