-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
daprinternal.go
347 lines (302 loc) · 10.2 KB
/
daprinternal.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
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 grpc
import (
"context"
"errors"
"fmt"
"io"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/anypb"
"github.com/dapr/dapr/pkg/acl"
actorerrors "github.com/dapr/dapr/pkg/actors/errors"
"github.com/dapr/dapr/pkg/api/grpc/metadata"
diag "github.com/dapr/dapr/pkg/diagnostics"
diagConsts "github.com/dapr/dapr/pkg/diagnostics/consts"
"github.com/dapr/dapr/pkg/messages"
"github.com/dapr/dapr/pkg/messaging"
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"
)
// CallLocal is used for internal dapr to dapr calls. It is invoked by another Dapr instance with a request to the local app.
func (a *api) CallLocal(ctx context.Context, in *internalv1pb.InternalInvokeRequest) (*internalv1pb.InternalInvokeResponse, error) {
appChannel := a.channels.AppChannel()
if appChannel == nil {
return nil, status.Error(codes.Internal, messages.ErrChannelNotFound)
}
req, err := invokev1.FromInternalInvokeRequest(in)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, messages.ErrInternalInvokeRequest, err.Error())
}
defer req.Close()
// Check the ACL
err = a.callLocalValidateACL(ctx, req)
if err != nil {
return nil, err
}
// Diagnostics
callerAppID := a.callLocalRecordRequest(req.Proto())
var statusCode int32
defer func() {
diag.DefaultMonitoring.ServiceInvocationResponseSent(callerAppID, statusCode)
}()
// stausCode will be read by the deferred method above
res, err := appChannel.InvokeMethod(ctx, req, "")
if err != nil {
statusCode = int32(codes.Internal)
return nil, status.Errorf(codes.Internal, messages.ErrChannelInvoke, err)
} else {
statusCode = res.Status().GetCode()
}
defer res.Close()
return res.ProtoWithData()
}
// CallLocalStream is a variant of CallLocal that uses gRPC streams to send data in chunks, rather than in an unary RPC.
// It is invoked by another Dapr instance with a request to the local app.
func (a *api) CallLocalStream(stream internalv1pb.ServiceInvocation_CallLocalStreamServer) error { //nolint:nosnakecase
appChannel := a.channels.AppChannel()
if appChannel == nil {
return status.Error(codes.Internal, messages.ErrChannelNotFound)
}
// Read the first chunk of the incoming request
// This contains the metadata of the request
chunk := &internalv1pb.InternalInvokeRequestStream{}
err := stream.RecvMsg(chunk)
if err != nil {
return err
}
if chunk.GetRequest().GetMetadata() == nil || chunk.GetRequest().GetMessage() == nil {
return status.Errorf(codes.InvalidArgument, messages.ErrInternalInvokeRequest, "request does not contain the required fields in the leading chunk")
}
// Append the invoked method to the context's metadata so we can use it for tracing
if md, ok := metadata.FromIncomingContext(stream.Context()); ok {
md[diagConsts.DaprCallLocalStreamMethodKey] = []string{chunk.GetRequest().GetMessage().GetMethod()}
}
// Create the request object
// The "rawData" of the object will be a pipe to which content is added chunk-by-chunk
pr, pw := io.Pipe()
req, err := invokev1.FromInternalInvokeRequest(chunk.GetRequest())
if err != nil {
return status.Errorf(codes.InvalidArgument, messages.ErrInternalInvokeRequest, err.Error())
}
req.WithRawData(pr).
WithContentType(chunk.GetRequest().GetMessage().GetContentType())
defer req.Close()
// If the data has a type_url, set that in the object too
// This is necessary to support the gRPC->gRPC service invocation (legacy, non-proxy) path correctly
// (Note that GetTypeUrl could return an empty value, so this call becomes a no-op)
req.WithDataTypeURL(chunk.GetRequest().GetMessage().GetData().GetTypeUrl())
ctx, cancel := context.WithCancel(stream.Context())
defer cancel()
a.wg.Add(1)
go func() {
defer a.wg.Done()
select {
case <-ctx.Done():
case <-a.closeCh:
cancel()
}
}()
// Check the ACL
err = a.callLocalValidateACL(ctx, req)
if err != nil {
return err
}
// Diagnostics
callerAppID := a.callLocalRecordRequest(req.Proto())
var statusCode int32
defer func() {
diag.DefaultMonitoring.ServiceInvocationResponseSent(callerAppID, statusCode)
}()
// Read the rest of the data in background as we submit the request
a.wg.Add(1)
go func() {
defer a.wg.Done()
var (
expectSeq uint64
readSeq uint64
payload *commonv1pb.StreamPayload
readErr error
)
for {
if ctx.Err() != nil {
pw.CloseWithError(ctx.Err())
return
}
// Get the payload from the chunk that was previously read
payload = chunk.GetPayload()
if payload != nil {
readSeq, readErr = messaging.ReadChunk(payload, pw)
if readErr != nil {
pw.CloseWithError(readErr)
return
}
// Check if the sequence number is greater than the previous
if readSeq != expectSeq {
pw.CloseWithError(fmt.Errorf("invalid sequence number received: %d (expected: %d)", readSeq, expectSeq))
return
}
expectSeq++
}
// Read the next chunk
readErr = stream.RecvMsg(chunk)
if errors.Is(readErr, io.EOF) {
// Receiving an io.EOF signifies that the client has stopped sending data over the pipe, so we can stop reading
break
} else if readErr != nil {
pw.CloseWithError(fmt.Errorf("error receiving message: %w", readErr))
return
}
if chunk.GetRequest().GetMetadata() != nil || chunk.GetRequest().GetMessage() != nil {
pw.CloseWithError(errors.New("request metadata found in non-leading chunk"))
return
}
}
pw.Close()
}()
// Submit the request to the app
res, err := appChannel.InvokeMethod(ctx, req, "")
if err != nil {
statusCode = int32(codes.Internal)
return status.Errorf(codes.Internal, messages.ErrChannelInvoke, err)
}
defer res.Close()
statusCode = res.Status().GetCode()
// Respond to the caller
buf := invokev1.BufPool.Get().(*[]byte)
defer func() {
invokev1.BufPool.Put(buf)
}()
r := res.RawData()
resProto := res.Proto()
// If there's a message in the proto, we remove it from the message we send to avoid sending it twice
// We re-add it when the method ends to ensure we can perform retries
messageData := resProto.GetMessage().GetData()
messageDataValue := messageData.GetValue()
if len(messageDataValue) > 0 {
messageData.Value = nil
defer func() {
messageData.Value = messageDataValue
}()
}
proto := &internalv1pb.InternalInvokeResponseStream{}
var (
n int
seq uint64
done bool
)
for {
if ctx.Err() != nil {
return ctx.Err()
}
// First message only - add the response
if resProto != nil {
proto.Response = resProto
resProto = nil
} else {
// Reset the object so we can re-use it
proto.Reset()
}
if r != nil {
n, err = r.Read(*buf)
if errors.Is(err, io.EOF) {
done = true
} else if err != nil {
return err
}
if n > 0 {
proto.Payload = &commonv1pb.StreamPayload{
Data: (*buf)[:n],
Seq: seq,
}
seq++
}
} else {
done = true
}
// Send the chunk if there's anything to send
if proto.GetResponse() != nil || proto.GetPayload() != nil {
err = stream.SendMsg(proto)
if err != nil {
return fmt.Errorf("error sending message: %w", err)
}
}
// Stop with the last chunk
// This will make the method return and close the stream
if done {
break
}
}
return nil
}
// CallActor invokes a virtual actor.
func (a *api) CallActor(ctx context.Context, in *internalv1pb.InternalInvokeRequest) (*internalv1pb.InternalInvokeResponse, error) {
// We don't do resiliency here as it is handled in the API layer. See InvokeActor().
res, err := a.Actors().Call(ctx, in)
if err != nil {
actorErr, isActorErr := actorerrors.As(err)
if res != nil && isActorErr {
// We have to remove the error to keep the body, so callers must re-inspect for the header in the actual response.
res.Message.Data = &anypb.Any{
Value: actorErr.Body(),
}
res.Headers = actorErr.Headers()
return res, nil
}
err = status.Errorf(codes.Internal, messages.ErrActorInvoke, err)
return nil, err
}
return res, nil
}
// Used by CallLocal and CallLocalStream to check the request against the access control list
func (a *api) callLocalValidateACL(ctx context.Context, req *invokev1.InvokeMethodRequest) error {
if a.accessControlList != nil {
// An access control policy has been specified for the app. Apply the policies.
operation := req.Message().GetMethod()
var httpVerb commonv1pb.HTTPExtension_Verb //nolint:nosnakecase
// Get the HTTP verb in case the application protocol is "http"
appProtocolIsHTTP := a.Universal.AppConnectionConfig().Protocol.IsHTTP()
if appProtocolIsHTTP && req.Metadata() != nil && len(req.Metadata()) > 0 {
httpExt := req.Message().GetHttpExtension()
if httpExt != nil {
httpVerb = httpExt.GetVerb()
}
}
callAllowed, errMsg := acl.ApplyAccessControlPolicies(ctx, operation, httpVerb, appProtocolIsHTTP, a.accessControlList)
if !callAllowed {
return status.Errorf(codes.PermissionDenied, errMsg)
}
}
return nil
}
// Internal function that records the received request for diagnostics
// After invoking this method, make sure to `defer` a call like:
//
// ```go
// var statusCode int32
// defer func() {
// diag.DefaultMonitoring.ServiceInvocationResponseSent(callerAppID, req.Message().Method, statusCode)
// }()
// ```
func (a *api) callLocalRecordRequest(req *internalv1pb.InternalInvokeRequest) (callerAppID string) {
callerIDHeader, ok := req.GetMetadata()[invokev1.CallerIDHeader]
if ok && len(callerIDHeader.GetValues()) > 0 {
callerAppID = callerIDHeader.GetValues()[0]
} else {
callerAppID = "unknown"
}
diag.DefaultMonitoring.ServiceInvocationRequestReceived(callerAppID)
return
}