forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.go
137 lines (112 loc) · 3.95 KB
/
extension.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Copyright The OpenTelemetry 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 httpforwarder // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/httpforwarder"
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"go.opentelemetry.io/collector/component"
"go.uber.org/zap"
)
type httpForwarder struct {
forwardTo *url.URL
httpClient *http.Client
server *http.Server
settings component.TelemetrySettings
config *Config
}
var _ component.Extension = (*httpForwarder)(nil)
func (h *httpForwarder) Start(_ context.Context, host component.Host) error {
listener, err := h.config.Ingress.ToListener()
if err != nil {
return fmt.Errorf("failed to bind to address %s: %w", h.config.Ingress.Endpoint, err)
}
httpClient, err := h.config.Egress.ToClient(host, h.settings)
if err != nil {
return fmt.Errorf("failed to create HTTP Client: %w", err)
}
h.httpClient = httpClient
handler := http.NewServeMux()
handler.HandleFunc("/", h.forwardRequest)
h.server, err = h.config.Ingress.ToServer(host, h.settings, handler)
if err != nil {
return fmt.Errorf("failed to create HTTP Client: %w", err)
}
go func() {
if errHTTP := h.server.Serve(listener); !errors.Is(errHTTP, http.ErrServerClosed) && errHTTP != nil {
host.ReportFatalError(errHTTP)
}
}()
return nil
}
func (h *httpForwarder) Shutdown(_ context.Context) error {
return h.server.Close()
}
func (h *httpForwarder) forwardRequest(writer http.ResponseWriter, request *http.Request) {
forwarderRequest := request.Clone(request.Context())
forwarderRequest.URL.Host = h.forwardTo.Host
forwarderRequest.URL.Scheme = h.forwardTo.Scheme
forwarderRequest.Host = h.forwardTo.Host
// Clear RequestURI to avoid getting "http: Request.RequestURI can't be set in client requests" error.
forwarderRequest.RequestURI = ""
// Add additional headers.
for k, v := range h.config.Egress.Headers {
forwarderRequest.Header.Add(k, v)
}
// Add "Via" header for tracking purposes on both the outgoing requests and responses.
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Via.
addViaHeader(forwarderRequest.Header, request.Proto, request.Host)
response, err := h.httpClient.Do(forwarderRequest)
if err != nil {
http.Error(writer, err.Error(), http.StatusBadGateway)
}
if response == nil {
return
}
defer response.Body.Close()
// Copy over response from the final destination.
for k := range response.Header {
writer.Header().Set(k, response.Header.Get(k))
}
addViaHeader(writer.Header(), response.Proto, request.Host)
writer.WriteHeader(response.StatusCode)
written, err := io.Copy(writer, response.Body)
if err != nil {
h.settings.Logger.Warn("Error writing HTTP response message", zap.Error(err))
}
if response.ContentLength != written {
h.settings.Logger.Warn("Response from target not fully copied, body might be corrupted")
}
}
func addViaHeader(header http.Header, protocol string, host string) {
header.Add("Via", fmt.Sprintf("%s %s", protocol, host))
}
func newHTTPForwarder(config *Config, settings component.TelemetrySettings) (component.Extension, error) {
if config.Egress.Endpoint == "" {
return nil, errors.New("'egress.endpoint' config option cannot be empty")
}
var url, err = url.Parse(config.Egress.Endpoint)
if err != nil {
return nil, fmt.Errorf("enter a valid URL for 'egress.endpoint': %w", err)
}
h := &httpForwarder{
config: config,
forwardTo: url,
settings: settings,
}
return h, nil
}