/
http_channel.go
263 lines (216 loc) · 7.6 KB
/
http_channel.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*
Copyright 2021 The Dapr 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 http
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
nethttp "net/http"
"github.com/valyala/fasthttp"
"go.opencensus.io/plugin/ochttp/propagation/tracecontext"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dapr/dapr/pkg/channel"
"github.com/dapr/dapr/pkg/config"
diag "github.com/dapr/dapr/pkg/diagnostics"
diag_utils "github.com/dapr/dapr/pkg/diagnostics/utils"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
auth "github.com/dapr/dapr/pkg/runtime/security"
)
const (
// HTTPStatusCode is an dapr http channel status code.
HTTPStatusCode = "http.status_code"
httpScheme = "http"
httpsScheme = "https"
appConfigEndpoint = "dapr/config"
)
// Channel is an HTTP implementation of an AppChannel.
type Channel struct {
client *fasthttp.Client
baseAddress string
ch chan int
tracingSpec config.TracingSpec
appHeaderToken string
maxResponseBodySize int
}
// CreateLocalChannel creates an HTTP AppChannel
// nolint:gosec
func CreateLocalChannel(port, maxConcurrency int, spec config.TracingSpec, sslEnabled bool, maxRequestBodySize int, readBufferSize int) (channel.AppChannel, error) {
scheme := httpScheme
if sslEnabled {
scheme = httpsScheme
}
c := &Channel{
client: &fasthttp.Client{
MaxConnsPerHost: 1000000,
MaxIdemponentCallAttempts: 0,
MaxResponseBodySize: maxRequestBodySize * 1024 * 1024,
ReadBufferSize: readBufferSize * 1024,
DisablePathNormalizing: true,
},
baseAddress: fmt.Sprintf("%s://%s:%d", scheme, channel.DefaultChannelAddress, port),
tracingSpec: spec,
appHeaderToken: auth.GetAppToken(),
maxResponseBodySize: maxRequestBodySize,
}
if sslEnabled {
c.client.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
if maxConcurrency > 0 {
c.ch = make(chan int, maxConcurrency)
}
return c, nil
}
// GetBaseAddress returns the application base address.
func (h *Channel) GetBaseAddress() string {
return h.baseAddress
}
// GetAppConfig gets application config from user application
// GET http://localhost:<app_port>/dapr/config
func (h *Channel) GetAppConfig() (*config.ApplicationConfig, error) {
req := invokev1.NewInvokeMethodRequest(appConfigEndpoint)
req.WithHTTPExtension(nethttp.MethodGet, "")
req.WithRawData(nil, invokev1.JSONContentType)
// TODO Propagate context
ctx := context.Background()
resp, err := h.InvokeMethod(ctx, req)
if err != nil {
return nil, err
}
var config config.ApplicationConfig
if resp.Status().Code != nethttp.StatusOK {
return &config, nil
}
// Get versioning info, currently only v1 is supported.
headers := resp.Headers()
var version string
if val, ok := headers["dapr-app-config-version"]; ok {
if len(val.Values) == 1 {
version = val.Values[0]
}
}
switch version {
case "v1":
fallthrough
default:
_, body := resp.RawData()
if err = json.Unmarshal(body, &config); err != nil {
return nil, err
}
}
return &config, nil
}
// InvokeMethod invokes user code via HTTP.
func (h *Channel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
// Check if HTTP Extension is given. Otherwise, it will return error.
httpExt := req.Message().GetHttpExtension()
if httpExt == nil {
return nil, status.Error(codes.InvalidArgument, "missing HTTP extension field")
}
if httpExt.GetVerb() == commonv1pb.HTTPExtension_NONE {
return nil, status.Error(codes.InvalidArgument, "invalid HTTP verb")
}
var rsp *invokev1.InvokeMethodResponse
var err error
switch req.APIVersion() {
case internalv1pb.APIVersion_V1:
rsp, err = h.invokeMethodV1(ctx, req)
default:
// Reject unsupported version
err = status.Error(codes.Unimplemented, fmt.Sprintf("Unsupported spec version: %d", req.APIVersion()))
}
return rsp, err
}
func (h *Channel) invokeMethodV1(ctx context.Context, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
channelReq := h.constructRequest(ctx, req)
if h.ch != nil {
h.ch <- 1
}
// Emit metric when request is sent
verb := string(channelReq.Header.Method())
diag.DefaultHTTPMonitoring.ClientRequestStarted(ctx, verb, req.Message().Method, int64(len(req.Message().Data.GetValue())))
startRequest := time.Now()
// Send request to user application
resp := fasthttp.AcquireResponse()
err := h.client.Do(channelReq, resp)
defer func() {
fasthttp.ReleaseRequest(channelReq)
fasthttp.ReleaseResponse(resp)
}()
elapsedMs := float64(time.Since(startRequest) / time.Millisecond)
if err != nil {
diag.DefaultHTTPMonitoring.ClientRequestCompleted(ctx, verb, req.Message().GetMethod(), strconv.Itoa(nethttp.StatusInternalServerError), int64(resp.Header.ContentLength()), elapsedMs)
return nil, err
}
if h.ch != nil {
<-h.ch
}
rsp := h.parseChannelResponse(req, resp)
diag.DefaultHTTPMonitoring.ClientRequestCompleted(ctx, verb, req.Message().GetMethod(), strconv.Itoa(int(rsp.Status().Code)), int64(resp.Header.ContentLength()), elapsedMs)
return rsp, nil
}
func (h *Channel) constructRequest(ctx context.Context, req *invokev1.InvokeMethodRequest) *fasthttp.Request {
channelReq := fasthttp.AcquireRequest()
// Construct app channel URI: VERB http://localhost:3000/method?query1=value1
var uri string
method := req.Message().GetMethod()
if strings.HasPrefix(method, "/") {
uri = fmt.Sprintf("%s%s", h.baseAddress, method)
} else {
uri = fmt.Sprintf("%s/%s", h.baseAddress, method)
}
channelReq.URI().Update(uri)
channelReq.URI().DisablePathNormalizing = true
channelReq.URI().SetQueryString(req.EncodeHTTPQueryString())
channelReq.Header.SetMethod(req.Message().HttpExtension.Verb.String())
// Recover headers
invokev1.InternalMetadataToHTTPHeader(ctx, req.Metadata(), channelReq.Header.Set)
// HTTP client needs to inject traceparent header for proper tracing stack.
span := diag_utils.SpanFromContext(ctx)
httpFormat := &tracecontext.HTTPFormat{}
tp, ts := httpFormat.SpanContextToHeaders(span.SpanContext())
channelReq.Header.Set("traceparent", tp)
if ts != "" {
channelReq.Header.Set("tracestate", ts)
}
if h.appHeaderToken != "" {
channelReq.Header.Set(auth.APITokenHeader, h.appHeaderToken)
}
// Set Content body and types
contentType, body := req.RawData()
channelReq.Header.SetContentType(contentType)
channelReq.SetBody(body)
return channelReq
}
func (h *Channel) parseChannelResponse(req *invokev1.InvokeMethodRequest, resp *fasthttp.Response) *invokev1.InvokeMethodResponse {
var statusCode int
var contentType string
var body []byte
statusCode = resp.StatusCode()
// TODO: Remove entire block when feature is finalized
if config.GetNoDefaultContentType() {
resp.Header.SetNoDefaultContentType(true)
}
contentType = (string)(resp.Header.ContentType())
body = resp.Body()
// Convert status code
rsp := invokev1.NewInvokeMethodResponse(int32(statusCode), "", nil)
rsp.WithFastHTTPHeaders(&resp.Header).WithRawData(body, contentType)
return rsp
}