-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
handler.go
131 lines (111 loc) · 4.37 KB
/
handler.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
/*
Copyright 2018 The Knative 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 handler
import (
"context"
"errors"
"net/http"
"net/http/httputil"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/trace"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/types"
network "knative.dev/networking/pkg"
"knative.dev/pkg/logging/logkey"
pkghandler "knative.dev/pkg/network/handlers"
tracingconfig "knative.dev/pkg/tracing/config"
"knative.dev/pkg/tracing/propagation/tracecontextb3"
"knative.dev/serving/pkg/activator"
activatorconfig "knative.dev/serving/pkg/activator/config"
pkghttp "knative.dev/serving/pkg/http"
"knative.dev/serving/pkg/queue"
"knative.dev/serving/pkg/reconciler/serverlessservice/resources/names"
)
// Throttler is the interface that Handler calls to Try to proxy the user request.
type Throttler interface {
Try(ctx context.Context, revID types.NamespacedName, fn func(string) error) error
}
// activationHandler will wait for an active endpoint for a revision
// to be available before proxying the request
type activationHandler struct {
transport http.RoundTripper
tracingTransport http.RoundTripper
usePassthroughLb bool
throttler Throttler
bufferPool httputil.BufferPool
logger *zap.SugaredLogger
}
// New constructs a new http.Handler that deals with revision activation.
func New(_ context.Context, t Throttler, transport http.RoundTripper, usePassthroughLb bool, logger *zap.SugaredLogger) http.Handler {
return &activationHandler{
transport: transport,
tracingTransport: &ochttp.Transport{
Base: transport,
Propagation: tracecontextb3.TraceContextB3Egress,
},
usePassthroughLb: usePassthroughLb,
throttler: t,
bufferPool: network.NewBufferPool(),
logger: logger,
}
}
func (a *activationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
config := activatorconfig.FromContext(r.Context())
tracingEnabled := config.Tracing.Backend != tracingconfig.None
tryContext, trySpan := r.Context(), (*trace.Span)(nil)
if tracingEnabled {
tryContext, trySpan = trace.StartSpan(r.Context(), "throttler_try")
}
revID := RevIDFrom(r.Context())
if err := a.throttler.Try(tryContext, revID, func(dest string) error {
trySpan.End()
proxyCtx, proxySpan := r.Context(), (*trace.Span)(nil)
if tracingEnabled {
proxyCtx, proxySpan = trace.StartSpan(r.Context(), "activator_proxy")
}
a.proxyRequest(revID, w, r.WithContext(proxyCtx), dest, tracingEnabled, a.usePassthroughLb)
proxySpan.End()
return nil
}); err != nil {
// Set error on our capacity waiting span and end it.
trySpan.Annotate([]trace.Attribute{trace.StringAttribute("activator.throttler.error", err.Error())}, "ThrottlerTry")
trySpan.End()
a.logger.Errorw("Throttler try error", zap.String(logkey.Key, revID.String()), zap.Error(err))
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, queue.ErrRequestQueueFull) {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
}
func (a *activationHandler) proxyRequest(revID types.NamespacedName, w http.ResponseWriter,
r *http.Request, target string, tracingEnabled bool, usePassthroughLb bool) {
network.RewriteHostIn(r)
r.Header.Set(network.ProxyHeaderName, activator.Name)
// Set up the reverse proxy.
hostOverride := pkghttp.NoHostOverride
if usePassthroughLb {
hostOverride = names.PrivateService(revID.Name) + "." + revID.Namespace
}
proxy := pkghttp.NewHeaderPruningReverseProxy(target, hostOverride, activator.RevisionHeaders)
proxy.BufferPool = a.bufferPool
proxy.Transport = a.transport
if tracingEnabled {
proxy.Transport = a.tracingTransport
}
proxy.FlushInterval = network.FlushInterval
proxy.ErrorHandler = func(w http.ResponseWriter, req *http.Request, err error) {
pkghandler.Error(a.logger.With(zap.String(logkey.Key, revID.String())))(w, req, err)
}
proxy.ServeHTTP(w, r)
}