-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Add transportlogger util #40579
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
smallinsky
wants to merge
2
commits into
master
Choose a base branch
from
smallinsky/transport_logger_util
base: master
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
Add transportlogger util #40579
Changes from all commits
Commits
Show all changes
2 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
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 |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| /* | ||
| Copyright 2021 Gravitational, Inc. | ||
|
|
||
| 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 common | ||
|
|
||
| import "time" | ||
|
|
||
| // Result is the result of the HTTP API call. | ||
| type Result struct { | ||
| // Information obtained from metricsInfoKey | ||
| Name string | ||
| // URL is the URL of the request. | ||
| URL string | ||
| // Host is the hostname of the request. | ||
| Host string | ||
| // Method is the HTTP method of the request. | ||
| Method string | ||
| // Err is the error that occurred during the call. | ||
| Err error | ||
| // HttpStatusCode is the HTTP status code of the response. | ||
| HttpStatusCode int | ||
| // Duration is the duration of the call. | ||
| Duration time.Duration | ||
| // Service is the service name. | ||
| Service string | ||
| } | ||
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,90 @@ | ||
| /* | ||
| Copyright 2024 Gravitational, Inc. | ||
|
|
||
| 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 transportlogger | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
|
|
||
| "github.com/jonboulle/clockwork" | ||
|
|
||
| "github.com/gravitational/teleport/api/utils/transportlogger/common" | ||
| "github.com/gravitational/teleport/api/utils/transportlogger/providers/prometheus" | ||
| ) | ||
|
|
||
| type options struct { | ||
| roundTripper http.RoundTripper | ||
| loggers []LoggerFunc | ||
| clock clockwork.Clock | ||
| serviceName string | ||
| } | ||
|
|
||
| func (o *options) checkAndSetDefaults() error { | ||
| if o.roundTripper == nil { | ||
| o.roundTripper = http.DefaultTransport | ||
| } | ||
| if o.clock == nil { | ||
| o.clock = clockwork.NewRealClock() | ||
| } | ||
| if len(o.loggers) == 0 { | ||
| o.loggers = append(o.loggers, prometheus.Logger) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| type OptionFunc func(o *options) | ||
|
|
||
| // WithRoundTripper sets the underlying http.RoundTripper to use for making requests. | ||
| func WithRoundTripper(rt http.RoundTripper) OptionFunc { | ||
| return func(o *options) { | ||
| o.roundTripper = rt | ||
| } | ||
| } | ||
|
|
||
| // WithClock sets the underlying http.RoundTripper to use for making requests. | ||
| func WithClock(clock clockwork.Clock) OptionFunc { | ||
| return func(o *options) { | ||
| o.clock = clock | ||
| } | ||
| } | ||
|
|
||
| // WithServiceName sets the service name to use for making requests. | ||
| func WithServiceName(name string) OptionFunc { | ||
| return func(o *options) { | ||
| o.serviceName = name | ||
| } | ||
| } | ||
|
|
||
| // WithPrometheusLogger adds a Prometheus logger to the transport. | ||
| // This logger will report the result of the API call as Prometheus metrics. | ||
| func WithPrometheusLogger() OptionFunc { | ||
| return func(o *options) { | ||
| o.loggers = append(o.loggers, prometheus.Logger) | ||
| } | ||
| } | ||
|
|
||
| // LoggerFunc is a function that logs the result of a call. | ||
| type LoggerFunc func(ctx context.Context, result *common.Result) | ||
|
|
||
| func (t *Transport) report(ctx context.Context, r *common.Result) { | ||
| for _, logFn := range t.loggers { | ||
| if logFn == nil { | ||
| continue | ||
| } | ||
| logFn(ctx, r) | ||
| } | ||
| } |
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,82 @@ | ||
| /* | ||
| Copyright 2024 Gravitational, Inc. | ||
|
|
||
| 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 transportlogger | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus/testutil" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/gravitational/teleport/api/utils/transportlogger/providers/prometheus" | ||
| ) | ||
|
|
||
| func TestLogger(t *testing.T) { | ||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| if r.URL.Path == "/ok" { | ||
| w.WriteHeader(http.StatusOK) | ||
| } else if r.URL.Path == "/not_found" { | ||
| w.WriteHeader(http.StatusNotFound) | ||
| } | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| transport, err := NewTransport( | ||
| WithRoundTripper(srv.Client().Transport), | ||
| WithServiceName("test_api"), | ||
| ) | ||
| require.NoError(t, err) | ||
|
|
||
| httpClient := &http.Client{ | ||
| Transport: transport, | ||
| } | ||
| ctx := context.Background() | ||
| req, err := http.NewRequest(http.MethodPost, srv.URL+"/ok", nil) | ||
| require.NoError(t, err) | ||
| if false { | ||
| resp, err := httpClient.Do(req.WithContext(WithMetricInfo(ctx, MetricsInfo{CallName: "ok_endpoint"}))) | ||
| require.NoError(t, err) | ||
| defer resp.Body.Close() | ||
|
|
||
| req, err = http.NewRequest(http.MethodGet, srv.URL+"/not_found", nil) | ||
| require.NoError(t, err) | ||
| resp, err = httpClient.Do(req.WithContext(WithMetricInfo(ctx, MetricsInfo{CallName: "not_found_endpoint"}))) | ||
| require.NoError(t, err) | ||
| defer resp.Body.Close() | ||
|
|
||
| want := ` | ||
| # HELP teleport_api_call_status Track calls to 3th party API | ||
| # TYPE teleport_api_call_status counter | ||
| teleport_api_call_status{endpoint="not_found_endpoint",http_method="GET",http_status="404",service="test_api"} 1 | ||
| teleport_api_call_status{endpoint="ok_endpoint",http_method="POST",http_status="200",service="test_api"} 1 | ||
| ` | ||
| err = testutil.CollectAndCompare(prometheus.ExternalAPICallMetric, bytes.NewBufferString(want)) | ||
| require.NoError(t, err) | ||
|
|
||
| prometheus.ExternalAPICallMetric.Reset() | ||
| } | ||
| req, err = http.NewRequest(http.MethodGet, srv.URL+"/not_found", nil) | ||
| require.NoError(t, err) | ||
| resp, err := httpClient.Do(req) | ||
| require.NoError(t, err) | ||
| defer resp.Body.Close() | ||
|
|
||
| } |
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,34 @@ | ||
| /* | ||
| Copyright 2024 Gravitational, Inc. | ||
|
|
||
| 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 transportlogger | ||
|
|
||
| import "context" | ||
|
|
||
| var metricsInfoKey struct{} | ||
|
|
||
| // MetricsInfo is a struct that contains information about the call that is being made. | ||
| type MetricsInfo struct { | ||
| // CallName is the name of the call that is being made. | ||
| // Many REST endpoint uses uuid in the URL, so it's for metrics entropy. | ||
| // CallName allow to set limited values for the REST API call that will be used for metrics. | ||
| CallName string | ||
| } | ||
|
|
||
| // WithMetricInfo sets the metrics information for the call. | ||
| func WithMetricInfo(ctx context.Context, info MetricsInfo) context.Context { | ||
| return context.WithValue(ctx, metricsInfoKey, info) | ||
| } |
34 changes: 34 additions & 0 deletions
34
api/utils/transportlogger/providers/prometheus/http_internals.go
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,34 @@ | ||
| /* | ||
| Copyright 2024 Gravitational, Inc. | ||
|
|
||
| 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 prometheus | ||
|
|
||
| import ( | ||
| _ "net/http" | ||
| _ "unsafe" | ||
| ) | ||
|
|
||
| // Link local error variables to unexported errors from http package by using | ||
| // go:linkname directive. | ||
|
|
||
| //go:linkname errTimeout net/http.errTimeout | ||
| var errTimeout error | ||
|
|
||
| //go:linkname errRequestCanceled net/http.errRequestCanceled | ||
| var errRequestCanceled error | ||
|
|
||
| //go:linkname errRequestCanceledConn net/http.errRequestCanceledConn | ||
| var errRequestCanceledConn error |
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.
nit