-
Notifications
You must be signed in to change notification settings - Fork 780
feat(provider): add External Metrics provider #1863
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jlore-decathlon
wants to merge
3
commits into
fluxcd:main
Choose a base branch
from
jlore-decathlon:feat/externalmetrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1344,6 +1344,7 @@ spec: | |
| - prometheus | ||
| - influxdb | ||
| - datadog | ||
| - externalmetrics | ||
| - stackdriver | ||
| - cloudwatch | ||
| - newrelic | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1344,6 +1344,7 @@ spec: | |
| - prometheus | ||
| - influxdb | ||
| - datadog | ||
| - externalmetrics | ||
| - stackdriver | ||
| - cloudwatch | ||
| - newrelic | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1344,6 +1344,7 @@ spec: | |
| - prometheus | ||
| - influxdb | ||
| - datadog | ||
| - externalmetrics | ||
| - stackdriver | ||
| - cloudwatch | ||
| - newrelic | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| /* | ||
| Copyright 2020 The Flux authors | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package providers | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/tls" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net" | ||
| "net/http" | ||
| "net/url" | ||
| "os" | ||
| "time" | ||
|
|
||
| flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1" | ||
| "k8s.io/metrics/pkg/apis/external_metrics" | ||
| ) | ||
|
|
||
| const ( | ||
| metricServiceEndpointPath = "/apis/external.metrics.k8s.io/v1beta1" | ||
| namespacesPath = "/namespaces/" | ||
|
|
||
| authorizationHeaderKey = "Authorization" | ||
| applicationBearerToken = "token" | ||
| ) | ||
|
|
||
| // ExternalMetricsProvider fetches metrics from an ExternalMetricsProvider. | ||
| type ExternalMetricsProvider struct { | ||
| metricServiceEndpoint string | ||
| bearerToken string | ||
|
|
||
| timeout time.Duration | ||
| client *http.Client | ||
| } | ||
|
|
||
| // NewExternalMetricsProvider takes a canary spec, a provider spec, and | ||
| // returns a client ready to execute queries against the Service | ||
| func NewExternalMetricsProvider(metricInterval string, | ||
| provider flaggerv1.MetricTemplateProvider, | ||
| credentials map[string][]byte) (*ExternalMetricsProvider, error) { | ||
|
|
||
| if provider.Address == "" { | ||
| return nil, fmt.Errorf("the Url of the external metric service must be provided") | ||
| } | ||
|
|
||
| emp := ExternalMetricsProvider{ | ||
| metricServiceEndpoint: fmt.Sprintf("%s%s", provider.Address, metricServiceEndpointPath), | ||
| timeout: 5 * time.Second, | ||
| client: http.DefaultClient, | ||
| } | ||
|
|
||
| if provider.InsecureSkipVerify { | ||
| t := http.DefaultTransport.(*http.Transport).Clone() | ||
| t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} | ||
| emp.client = &http.Client{Transport: t} | ||
| } | ||
|
|
||
| if b, ok := credentials[applicationBearerToken]; ok { | ||
| emp.bearerToken = string(b) | ||
| } else { | ||
| // In the absence of a provided token, | ||
| // read service account token from volume mount | ||
| token, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token") | ||
| if err != nil { | ||
| return nil, fmt.Errorf("error reading service account token: %w", err) | ||
| } | ||
| if len(token) == 0 { | ||
| return nil, fmt.Errorf("pod's service account token is empty") | ||
| } | ||
| emp.bearerToken = string(token) | ||
| } | ||
|
|
||
| return &emp, nil | ||
| } | ||
|
|
||
| // RunQuery retrieves the ExternalMetricValue from the ExternalMetricsProvider.metricServiceUrl | ||
| // and returns the first result as a float64 | ||
| func (p *ExternalMetricsProvider) RunQuery(query string) (float64, error) { | ||
| u := fmt.Sprintf("%s%s%s", p.metricServiceEndpoint, namespacesPath, query) | ||
|
|
||
| req, err := http.NewRequest("GET", u, nil) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("error http.NewRequest: %w", err) | ||
| } | ||
| if p.bearerToken != "" { | ||
| req.Header.Add(authorizationHeaderKey, fmt.Sprintf("Bearer %s", p.bearerToken)) | ||
| } | ||
|
|
||
| ctx, cancel := context.WithTimeout(req.Context(), p.timeout) | ||
| defer cancel() | ||
| r, err := p.client.Do(req.WithContext(ctx)) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("request failed: %w", err) | ||
| } | ||
|
|
||
| defer r.Body.Close() | ||
| b, err := io.ReadAll(r.Body) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("error reading body: %w", err) | ||
| } | ||
|
|
||
| if r.StatusCode != http.StatusOK { | ||
| return 0, fmt.Errorf("error response: %s: %w", string(b), err) | ||
| } | ||
|
|
||
| var res external_metrics.ExternalMetricValueList | ||
| if err := json.Unmarshal(b, &res); err != nil { | ||
| return 0, fmt.Errorf("error unmarshaling result: %w, '%s'", err, string(b)) | ||
| } | ||
|
|
||
| if len(res.Items) < 1 { | ||
| return 0, fmt.Errorf("invalid response: %s: %w", string(b), ErrNoValuesFound) | ||
| } | ||
|
|
||
| vs := res.Items[0].Value.AsApproximateFloat64() | ||
|
|
||
| return vs, nil | ||
| } | ||
|
|
||
| // IsOnline will only check the TCP endpoint reachability, | ||
| // given that external metric servers don't have a standard health check endpoint defined | ||
| func (p *ExternalMetricsProvider) IsOnline() (bool, error) { | ||
| var d net.Dialer | ||
|
|
||
| ctx, cancel := context.WithTimeout(context.Background(), p.timeout) | ||
| defer cancel() | ||
|
|
||
| u, err := url.Parse(p.metricServiceEndpoint) | ||
| if err != nil { | ||
| return false, fmt.Errorf("error parsing metric service url: %w", err) | ||
| } | ||
|
|
||
| conn, err := d.DialContext(ctx, "tcp", u.Host) | ||
| defer conn.Close() | ||
| if err != nil { | ||
| return false, fmt.Errorf("connection failed: %w", err) | ||
| } | ||
| return true, err | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we use an
ExternalMetricsClientobject created by to fetch theexternal_metrics.ExternalMetricValueList? we can create one using theNewForConfigfunction in this package. it takes care of loading the service account token automatically and provides a nice interface to fetch the metrics?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems to expose all the attributes of a Rest client so overloading of the host (as we don't want to default to the cluster's API server in case the provider hasn't registered)
We'll have to give it a try, stay tuned.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've got a version that compiles but I'm running it against my colleague's review and we'll probably want to test it after that.
Having a busy schedule for the next 3 weeks (talking about Flagger at Cloud Native Days Paris ^^), likely don't expect news until February.