-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
runtime.go
3300 lines (2873 loc) · 108 KB
/
runtime.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 runtime
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net"
nethttp "net/http"
"os"
"os/signal"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"github.com/hashicorp/go-multierror"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
otlptracegrpc "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
otlptracehttp "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/exporters/zipkin"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.10.0"
"go.opentelemetry.io/otel/trace"
gogrpc "google.golang.org/grpc"
"google.golang.org/grpc/codes"
md "google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/structpb"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/dapr/dapr/pkg/actors"
componentsV1alpha1 "github.com/dapr/dapr/pkg/apis/components/v1alpha1"
"github.com/dapr/dapr/pkg/apphealth"
"github.com/dapr/dapr/pkg/channel"
httpChannel "github.com/dapr/dapr/pkg/channel/http"
"github.com/dapr/dapr/pkg/components"
"github.com/dapr/dapr/pkg/config"
diag "github.com/dapr/dapr/pkg/diagnostics"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
"github.com/dapr/dapr/pkg/encryption"
"github.com/dapr/dapr/pkg/grpc"
"github.com/dapr/dapr/pkg/http"
"github.com/dapr/dapr/pkg/messaging"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
httpMiddleware "github.com/dapr/dapr/pkg/middleware/http"
"github.com/dapr/dapr/pkg/modes"
"github.com/dapr/dapr/pkg/operator/client"
"github.com/dapr/dapr/pkg/resiliency"
runtimePubsub "github.com/dapr/dapr/pkg/runtime/pubsub"
"github.com/dapr/dapr/pkg/runtime/security"
"github.com/dapr/dapr/pkg/runtime/wfengine"
"github.com/dapr/dapr/pkg/scopes"
"github.com/dapr/dapr/utils"
"github.com/dapr/kit/logger"
operatorv1pb "github.com/dapr/dapr/pkg/proto/operator/v1"
runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1"
wfs "github.com/dapr/components-contrib/workflows"
bindingsLoader "github.com/dapr/dapr/pkg/components/bindings"
configurationLoader "github.com/dapr/dapr/pkg/components/configuration"
lockLoader "github.com/dapr/dapr/pkg/components/lock"
httpMiddlewareLoader "github.com/dapr/dapr/pkg/components/middleware/http"
nrLoader "github.com/dapr/dapr/pkg/components/nameresolution"
"github.com/dapr/dapr/pkg/components/pluggable"
pubsubLoader "github.com/dapr/dapr/pkg/components/pubsub"
secretstoresLoader "github.com/dapr/dapr/pkg/components/secretstores"
stateLoader "github.com/dapr/dapr/pkg/components/state"
workflowsLoader "github.com/dapr/dapr/pkg/components/workflows"
"github.com/dapr/components-contrib/bindings"
"github.com/dapr/components-contrib/configuration"
"github.com/dapr/components-contrib/contenttype"
"github.com/dapr/components-contrib/lock"
contribMetadata "github.com/dapr/components-contrib/metadata"
"github.com/dapr/components-contrib/middleware"
nr "github.com/dapr/components-contrib/nameresolution"
"github.com/dapr/components-contrib/pubsub"
"github.com/dapr/components-contrib/secretstores"
"github.com/dapr/components-contrib/state"
)
const (
actorStateStore = "actorStateStore"
// output bindings concurrency.
bindingsConcurrencyParallel = "parallel"
bindingsConcurrencySequential = "sequential"
pubsubName = "pubsubName"
// hot reloading is currently unsupported, but
// setting this environment variable restores the
// partial hot reloading support for k8s.
hotReloadingEnvVar = "DAPR_ENABLE_HOT_RELOADING"
defaultComponentInitTimeout = time.Second * 5
)
type ComponentCategory string
var componentCategoriesNeedProcess = []components.Category{
components.CategoryBindings,
components.CategoryPubSub,
components.CategorySecretStore,
components.CategoryStateStore,
components.CategoryMiddleware,
components.CategoryConfiguration,
components.CategoryLock,
components.CategoryWorkflow,
}
var log = logger.NewLogger("dapr.runtime")
// ErrUnexpectedEnvelopeData denotes that an unexpected data type
// was encountered when processing a cloud event's data property.
var ErrUnexpectedEnvelopeData = errors.New("unexpected data type encountered in envelope")
var cloudEventDuplicateKeys = sets.NewString(pubsub.IDField, pubsub.SourceField, pubsub.DataContentTypeField, pubsub.TypeField, pubsub.SpecVersionField, pubsub.DataField, pubsub.DataBase64Field)
type TopicRoutes map[string]TopicRouteElem
type TopicRouteElem struct {
metadata map[string]string
rules []*runtimePubsub.Rule
deadLetterTopic string
bulkSubscribe *runtimePubsub.BulkSubscribe
}
// Type of function that determines if a component is authorized.
// The function receives the component and must return true if the component is authorized.
type ComponentAuthorizer func(component componentsV1alpha1.Component) bool
// DaprRuntime holds all the core components of the runtime.
type DaprRuntime struct {
ctx context.Context
cancel context.CancelFunc
runtimeConfig *Config
globalConfig *config.Configuration
accessControlList *config.AccessControlList
componentsLock *sync.RWMutex
components []componentsV1alpha1.Component
grpc *grpc.Manager
appChannel channel.AppChannel
appConfig config.ApplicationConfig
directMessaging messaging.DirectMessaging
stateStoreRegistry *stateLoader.Registry
secretStoresRegistry *secretstoresLoader.Registry
nameResolutionRegistry *nrLoader.Registry
workflowComponentRegistry *workflowsLoader.Registry
stateStores map[string]state.Store
actor actors.Actors
bindingsRegistry *bindingsLoader.Registry
subscribeBindingList []string
inputBindings map[string]bindings.InputBinding
outputBindings map[string]bindings.OutputBinding
inputBindingsCtx context.Context
inputBindingsCancel context.CancelFunc
secretStores map[string]secretstores.SecretStore
pubSubRegistry *pubsubLoader.Registry
pubSubs map[string]pubsubItem // Key is "componentName"
workflowComponents map[string]wfs.Workflow
nameResolver nr.Resolver
httpMiddlewareRegistry *httpMiddlewareLoader.Registry
hostAddress string
actorStateStoreName string
actorStateStoreLock *sync.RWMutex
authenticator security.Authenticator
namespace string
podName string
daprHTTPAPI http.API
daprGRPCAPI grpc.API
operatorClient operatorv1pb.OperatorClient
pubsubCtx context.Context
pubsubCancel context.CancelFunc
topicsLock *sync.RWMutex
topicRoutes map[string]TopicRoutes // Key is "componentName"
topicCtxCancels map[string]context.CancelFunc // Key is "componentName||topicName"
subscriptions []runtimePubsub.Subscription
inputBindingRoutes map[string]string
shutdownC chan error
running atomic.Bool
apiClosers []io.Closer
componentAuthorizers []ComponentAuthorizer
appHealth *apphealth.AppHealth
appHealthReady func() // Invoked the first time the app health becomes ready
appHealthLock *sync.Mutex
bulkSubLock *sync.Mutex
appHTTPClient *nethttp.Client
secretsConfiguration map[string]config.SecretsScope
configurationStoreRegistry *configurationLoader.Registry
configurationStores map[string]configuration.Store
lockStoreRegistry *lockLoader.Registry
lockStores map[string]lock.Store
pendingComponents chan componentsV1alpha1.Component
pendingComponentDependents map[string][]componentsV1alpha1.Component
proxy messaging.Proxy
resiliency resiliency.Provider
tracerProvider *sdktrace.TracerProvider
workflowEngine *wfengine.WorkflowEngine
}
type ComponentsCallback func(components ComponentRegistry) error
type ComponentRegistry struct {
Actors actors.Actors
DirectMessaging messaging.DirectMessaging
StateStores map[string]state.Store
InputBindings map[string]bindings.InputBinding
OutputBindings map[string]bindings.OutputBinding
SecretStores map[string]secretstores.SecretStore
PubSubs map[string]pubsub.PubSub
Workflows map[string]wfs.Workflow
}
type componentPreprocessRes struct {
unreadyDependency string
}
type pubsubSubscribedMessage struct {
cloudEvent map[string]interface{}
data []byte
topic string
metadata map[string]string
path string
pubsub string
}
type pubsubItem struct {
component pubsub.PubSub
scopedSubscriptions []string
scopedPublishings []string
allowedTopics []string
namespaceScoped bool
}
// NewDaprRuntime returns a new runtime with the given runtime config and global config.
func NewDaprRuntime(runtimeConfig *Config, globalConfig *config.Configuration, accessControlList *config.AccessControlList, resiliencyProvider resiliency.Provider) *DaprRuntime {
ctx, cancel := context.WithCancel(context.Background())
rt := &DaprRuntime{
ctx: ctx,
cancel: cancel,
runtimeConfig: runtimeConfig,
globalConfig: globalConfig,
accessControlList: accessControlList,
componentsLock: &sync.RWMutex{},
components: make([]componentsV1alpha1.Component, 0),
actorStateStoreLock: &sync.RWMutex{},
grpc: createGRPCManager(runtimeConfig, globalConfig),
inputBindings: map[string]bindings.InputBinding{},
outputBindings: map[string]bindings.OutputBinding{},
secretStores: map[string]secretstores.SecretStore{},
stateStores: map[string]state.Store{},
pubSubs: map[string]pubsubItem{},
topicsLock: &sync.RWMutex{},
inputBindingRoutes: map[string]string{},
secretsConfiguration: map[string]config.SecretsScope{},
configurationStores: map[string]configuration.Store{},
lockStores: map[string]lock.Store{},
workflowComponents: map[string]wfs.Workflow{},
pendingComponents: make(chan componentsV1alpha1.Component),
pendingComponentDependents: map[string][]componentsV1alpha1.Component{},
shutdownC: make(chan error, 1),
tracerProvider: nil,
resiliency: resiliencyProvider,
workflowEngine: wfengine.NewWorkflowEngine(),
appHealthReady: nil,
appHealthLock: &sync.Mutex{},
bulkSubLock: &sync.Mutex{},
}
rt.componentAuthorizers = []ComponentAuthorizer{rt.namespaceComponentAuthorizer}
if globalConfig != nil && len(globalConfig.Spec.ComponentsSpec.Deny) > 0 {
dl := newComponentDenyList(globalConfig.Spec.ComponentsSpec.Deny)
rt.componentAuthorizers = append(rt.componentAuthorizers, dl.IsAllowed)
}
rt.initAppHTTPClient()
return rt
}
// Run performs initialization of the runtime with the runtime and global configurations.
func (a *DaprRuntime) Run(opts ...Option) error {
start := time.Now()
log.Infof("%s mode configured", a.runtimeConfig.Mode)
log.Infof("app id: %s", a.runtimeConfig.ID)
var o runtimeOpts
for _, opt := range opts {
opt(&o)
}
if err := a.initRuntime(&o); err != nil {
return err
}
a.running.Store(true)
d := time.Since(start).Milliseconds()
log.Infof("dapr initialized. Status: Running. Init Elapsed %vms", d)
if a.daprHTTPAPI != nil {
// gRPC server start failure is logged as Fatal in initRuntime method. Setting the status only when runtime is initialized.
a.daprHTTPAPI.MarkStatusAsReady()
}
return nil
}
func (a *DaprRuntime) getNamespace() string {
return os.Getenv("NAMESPACE")
}
func (a *DaprRuntime) getPodName() string {
return os.Getenv("POD_NAME")
}
func (a *DaprRuntime) getOperatorClient() (operatorv1pb.OperatorClient, error) {
if a.runtimeConfig.Mode == modes.KubernetesMode {
client, _, err := client.GetOperatorClient(a.runtimeConfig.Kubernetes.ControlPlaneAddress, security.TLSServerName, a.runtimeConfig.CertChain)
if err != nil {
return nil, fmt.Errorf("error creating operator client: %w", err)
}
return client, nil
}
return nil, nil
}
// setupTracing set up the trace exporters. Technically we don't need to pass `hostAddress` in,
// but we do so here to explicitly call out the dependency on having `hostAddress` computed.
func (a *DaprRuntime) setupTracing(hostAddress string, tpStore tracerProviderStore) error {
tracingSpec := a.globalConfig.Spec.TracingSpec
// Register stdout trace exporter if user wants to debug requests or log as Info level.
if tracingSpec.Stdout {
tpStore.RegisterExporter(diagUtils.NewStdOutExporter())
}
// Register zipkin trace exporter if ZipkinSpec is specified
if tracingSpec.Zipkin.EndpointAddress != "" {
zipkinExporter, err := zipkin.New(tracingSpec.Zipkin.EndpointAddress)
if err != nil {
return err
}
tpStore.RegisterExporter(zipkinExporter)
}
// Register otel trace exporter if OtelSpec is specified
if tracingSpec.Otel.EndpointAddress != "" && tracingSpec.Otel.Protocol != "" {
endpoint := tracingSpec.Otel.EndpointAddress
protocol := tracingSpec.Otel.Protocol
if protocol != "http" && protocol != "grpc" {
return fmt.Errorf("invalid protocol %v provided for Otel endpoint", protocol)
}
isSecure := tracingSpec.Otel.IsSecure
var client otlptrace.Client
if protocol == "http" {
clientOptions := []otlptracehttp.Option{otlptracehttp.WithEndpoint(endpoint)}
if !isSecure {
clientOptions = append(clientOptions, otlptracehttp.WithInsecure())
}
client = otlptracehttp.NewClient(clientOptions...)
} else {
clientOptions := []otlptracegrpc.Option{otlptracegrpc.WithEndpoint(endpoint)}
if !isSecure {
clientOptions = append(clientOptions, otlptracegrpc.WithInsecure())
}
client = otlptracegrpc.NewClient(clientOptions...)
}
otelExporter, err := otlptrace.New(a.ctx, client)
if err != nil {
return err
}
tpStore.RegisterExporter(otelExporter)
}
// Register a resource
r := resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(a.runtimeConfig.ID),
)
tpStore.RegisterResource(r)
// Register a trace sampler based on Sampling settings
daprTraceSampler := diag.NewDaprTraceSampler(tracingSpec.SamplingRate)
log.Infof("Dapr trace sampler initialized: %s", daprTraceSampler.Description())
tpStore.RegisterSampler(daprTraceSampler)
a.tracerProvider = tpStore.RegisterTracerProvider()
return nil
}
func (a *DaprRuntime) initRuntime(opts *runtimeOpts) error {
a.namespace = a.getNamespace()
err := a.establishSecurity(a.runtimeConfig.SentryServiceAddress)
if err != nil {
return err
}
a.podName = a.getPodName()
a.operatorClient, err = a.getOperatorClient()
if err != nil {
return err
}
if a.hostAddress, err = utils.GetHostAddress(); err != nil {
return fmt.Errorf("failed to determine host address: %w", err)
}
if err = a.setupTracing(a.hostAddress, newOpentelemetryTracerProviderStore()); err != nil {
return fmt.Errorf("failed to setup tracing: %w", err)
}
// Register and initialize name resolution for service discovery.
a.nameResolutionRegistry = opts.nameResolutionRegistry
err = a.initNameResolution()
if err != nil {
log.Errorf(err.Error())
}
a.pubSubRegistry = opts.pubsubRegistry
a.secretStoresRegistry = opts.secretStoreRegistry
a.stateStoreRegistry = opts.stateRegistry
a.configurationStoreRegistry = opts.configurationRegistry
a.bindingsRegistry = opts.bindingRegistry
a.httpMiddlewareRegistry = opts.httpMiddlewareRegistry
a.lockStoreRegistry = opts.lockRegistry
a.workflowComponentRegistry = opts.workflowComponentRegistry
a.initPluggableComponents()
go a.processComponents()
if _, ok := os.LookupEnv(hotReloadingEnvVar); ok {
log.Debug("starting to watch component updates")
err = a.beginComponentsUpdates()
if err != nil {
log.Warnf("failed to watch component updates: %s", err)
}
}
a.appendBuiltinSecretStore()
err = a.loadComponents(opts)
if err != nil {
log.Warnf("failed to load components: %s", err)
}
a.flushOutstandingComponents()
pipeline, err := a.buildHTTPPipeline()
if err != nil {
log.Warnf("failed to build HTTP pipeline: %s", err)
}
// Setup allow/deny list for secrets
a.populateSecretsConfiguration()
// Start proxy
a.initProxy()
// Create and start internal and external gRPC servers
a.daprGRPCAPI = a.getGRPCAPI()
err = a.startGRPCAPIServer(a.daprGRPCAPI, a.runtimeConfig.APIGRPCPort)
if err != nil {
log.Fatalf("failed to start API gRPC server: %s", err)
}
if a.runtimeConfig.UnixDomainSocket != "" {
log.Info("API gRPC server is running on a unix domain socket")
} else {
log.Infof("API gRPC server is running on port %v", a.runtimeConfig.APIGRPCPort)
}
a.initDirectMessaging(a.nameResolver)
// Start HTTP Server
err = a.startHTTPServer(a.runtimeConfig.HTTPPort, a.runtimeConfig.PublicPort, a.runtimeConfig.ProfilePort, a.runtimeConfig.AllowedOrigins, pipeline)
if err != nil {
log.Fatalf("failed to start HTTP server: %s", err)
}
if a.runtimeConfig.UnixDomainSocket != "" {
log.Info("http server is running on a unix domain socket")
} else {
log.Infof("http server is running on port %v", a.runtimeConfig.HTTPPort)
}
log.Infof("The request body size parameter is: %v", a.runtimeConfig.MaxRequestBodySize)
err = a.startGRPCInternalServer(a.daprGRPCAPI, a.runtimeConfig.InternalGRPCPort)
if err != nil {
log.Fatalf("failed to start internal gRPC server: %s", err)
}
log.Infof("internal gRPC server is running on port %v", a.runtimeConfig.InternalGRPCPort)
if a.daprHTTPAPI != nil {
a.daprHTTPAPI.MarkStatusAsOutboundReady()
}
a.blockUntilAppIsReady()
err = a.createAppChannel()
if err != nil {
log.Warnf("failed to open %s channel to app: %s", string(a.runtimeConfig.ApplicationProtocol), err)
}
a.daprHTTPAPI.SetAppChannel(a.appChannel)
a.daprGRPCAPI.SetAppChannel(a.appChannel)
a.directMessaging.SetAppChannel(a.appChannel)
a.initDirectMessaging(a.nameResolver)
a.daprHTTPAPI.SetDirectMessaging(a.directMessaging)
a.daprGRPCAPI.SetDirectMessaging(a.directMessaging)
if a.runtimeConfig.MaxConcurrency > 0 {
log.Infof("app max concurrency set to %v", a.runtimeConfig.MaxConcurrency)
}
a.appHealthReady = func() {
a.appHealthReadyInit(opts)
}
if a.runtimeConfig.AppHealthCheck != nil && a.appChannel != nil {
// We can't just pass "a.appChannel.HealthProbe" because appChannel may be re-created
a.appHealth = apphealth.NewAppHealth(a.runtimeConfig.AppHealthCheck, func(ctx context.Context) (bool, error) {
return a.appChannel.HealthProbe(ctx)
})
a.appHealth.OnHealthChange(a.appHealthChanged)
a.appHealth.StartProbes(a.ctx)
// Set the appHealth object in the channel so it's aware of the app's health status
a.appChannel.SetAppHealth(a.appHealth)
// Enqueue a probe right away
// This will also start the input components once the app is healthy
a.appHealth.Enqueue()
} else {
// If there's no health check, mark the app as healthy right away so subscriptions can start
a.appHealthChanged(apphealth.AppStatusHealthy)
}
return nil
}
// appHealthReadyInit completes the initialization phase and is invoked after the app is healthy
func (a *DaprRuntime) appHealthReadyInit(opts *runtimeOpts) {
var err error
// Load app configuration (for actors) and init actors
a.loadAppConfiguration()
if len(a.runtimeConfig.PlacementAddresses) != 0 {
err = a.initActors()
if err != nil {
log.Warnf(err.Error())
} else {
a.daprHTTPAPI.SetActorRuntime(a.actor)
a.daprGRPCAPI.SetActorRuntime(a.actor)
// Workflow engine depends on actor runtime being initialized
a.initWorkflowEngine()
}
}
if opts.componentsCallback != nil {
pubsubs := make(map[string]pubsub.PubSub, len(a.pubSubs))
for k, v := range a.pubSubs {
pubsubs[k] = v.component
}
if err = opts.componentsCallback(ComponentRegistry{
Actors: a.actor,
DirectMessaging: a.directMessaging,
StateStores: a.stateStores,
InputBindings: a.inputBindings,
OutputBindings: a.outputBindings,
SecretStores: a.secretStores,
PubSubs: pubsubs,
Workflows: a.workflowComponents,
}); err != nil {
log.Fatalf("failed to register components with callback: %s", err)
}
}
}
func (a *DaprRuntime) initWorkflowEngine() {
wfComponentFactory := wfengine.BuiltinWorkflowFactory(a.workflowEngine)
if wfInitErr := a.workflowEngine.SetActorRuntime(a.actor); wfInitErr != nil {
log.Warnf("Failed to set actor runtime for Dapr workflow engine - workflow engine will not start: %w", wfInitErr)
} else {
if a.workflowComponentRegistry != nil {
log.Infof("Registering component for dapr workflow engine...")
a.workflowComponentRegistry.RegisterComponent(wfComponentFactory, "dapr")
if componentInitErr := a.initWorkflowComponent(wfengine.ComponentDefinition); componentInitErr != nil {
log.Warnf("Failed to initialize Dapr workflow component: %v", componentInitErr)
}
} else {
log.Infof("No workflow registry available, not registering Dapr workflow component...")
}
}
}
// initPluggableComponents discover pluggable components and initialize with their respective registries.
func (a *DaprRuntime) initPluggableComponents() {
if runtime.GOOS == "windows" {
log.Debugf("the current OS does not support pluggable components feature, skipping initialization")
return
}
if err := pluggable.Discover(a.ctx); err != nil {
log.Errorf("could not initialize pluggable components %v", err)
}
}
// Sets the status of the app to healthy or un-healthy
// Callback for apphealth when the detected status changed
func (a *DaprRuntime) appHealthChanged(status uint8) {
a.appHealthLock.Lock()
defer a.appHealthLock.Unlock()
switch status {
case apphealth.AppStatusHealthy:
// First time the app becomes healthy, complete the init process
if a.appHealthReady != nil {
a.appHealthReady()
a.appHealthReady = nil
}
// Start subscribing to topics and reading from input bindings
a.startSubscriptions()
err := a.startReadingFromBindings()
if err != nil {
log.Warnf("failed to read from bindings: %s ", err)
}
case apphealth.AppStatusUnhealthy:
// Stop topic subscriptions and input bindings
a.stopSubscriptions()
a.stopReadingFromBindings()
}
}
func (a *DaprRuntime) populateSecretsConfiguration() {
// Populate in a map for easy lookup by store name.
for _, scope := range a.globalConfig.Spec.Secrets.Scopes {
a.secretsConfiguration[scope.StoreName] = scope
}
}
func (a *DaprRuntime) buildHTTPPipelineForSpec(spec config.PipelineSpec, targetPipeline string) (pipeline httpMiddleware.Pipeline, err error) {
if a.globalConfig != nil {
pipeline.Handlers = make([]func(next nethttp.Handler) nethttp.Handler, 0, len(spec.Handlers))
for i := 0; i < len(spec.Handlers); i++ {
middlewareSpec := spec.Handlers[i]
component, exists := a.getComponent(middlewareSpec.Type, middlewareSpec.Name)
if !exists {
// Log the error but continue with initializing the pipeline
log.Error("couldn't find middleware component defined in configuration with name %s and type %s/%s",
middlewareSpec.Name, middlewareSpec.Type, middlewareSpec.Version)
continue
}
md := middleware.Metadata{Base: a.toBaseMetadata(component)}
handler, err := a.httpMiddlewareRegistry.Create(middlewareSpec.Type, middlewareSpec.Version, md, middlewareSpec.LogName())
if err != nil {
e := fmt.Sprintf("process component %s error: %s", component.Name, err.Error())
if !component.Spec.IgnoreErrors {
log.Warn("error processing middleware component, daprd process will exit gracefully")
a.Shutdown(a.runtimeConfig.GracefulShutdownDuration)
log.Fatal(e)
// This error is only caught by tests, since during normal execution we panic
return pipeline, errors.New("dapr panicked")
}
log.Error(e)
continue
}
log.Infof("enabled %s/%s %s middleware", middlewareSpec.Type, targetPipeline, middlewareSpec.Version)
pipeline.Handlers = append(pipeline.Handlers, handler)
}
}
return pipeline, nil
}
func (a *DaprRuntime) buildHTTPPipeline() (httpMiddleware.Pipeline, error) {
return a.buildHTTPPipelineForSpec(a.globalConfig.Spec.HTTPPipelineSpec, "http")
}
func (a *DaprRuntime) buildAppHTTPPipeline() (httpMiddleware.Pipeline, error) {
return a.buildHTTPPipelineForSpec(a.globalConfig.Spec.AppHTTPPipelineSpec, "app channel")
}
func (a *DaprRuntime) initBinding(c componentsV1alpha1.Component) error {
if a.bindingsRegistry.HasOutputBinding(c.Spec.Type, c.Spec.Version) {
if err := a.initOutputBinding(c); err != nil {
return err
}
}
if a.bindingsRegistry.HasInputBinding(c.Spec.Type, c.Spec.Version) {
if err := a.initInputBinding(c); err != nil {
return err
}
}
return nil
}
func (a *DaprRuntime) sendToDeadLetter(name string, msg *pubsub.NewMessage, deadLetterTopic string) (err error) {
req := &pubsub.PublishRequest{
Data: msg.Data,
PubsubName: name,
Topic: deadLetterTopic,
Metadata: msg.Metadata,
ContentType: msg.ContentType,
}
err = a.Publish(req)
if err != nil {
log.Errorf("error sending message to dead letter, origin topic: %s dead letter topic %s err: %w", msg.Topic, deadLetterTopic, err)
return err
}
return nil
}
func (a *DaprRuntime) subscribeTopic(parentCtx context.Context, name string, topic string, route TopicRouteElem) error {
subKey := pubsubTopicKey(name, topic)
a.topicsLock.Lock()
defer a.topicsLock.Unlock()
allowed := a.isPubSubOperationAllowed(name, topic, a.pubSubs[name].scopedSubscriptions)
if !allowed {
return fmt.Errorf("subscription to topic '%s' on pubsub '%s' is not allowed", topic, name)
}
log.Debugf("subscribing to topic='%s' on pubsub='%s'", topic, name)
if _, ok := a.topicCtxCancels[subKey]; ok {
return fmt.Errorf("cannot subscribe to topic '%s' on pubsub '%s': the subscription already exists", topic, name)
}
ctx, cancel := context.WithCancel(parentCtx)
policyDef := a.resiliency.ComponentInboundPolicy(name, resiliency.Pubsub)
routeMetadata := route.metadata
namespaced := a.pubSubs[name].namespaceScoped
if route.bulkSubscribe != nil && route.bulkSubscribe.Enabled {
err := a.bulkSubscribeTopic(ctx, policyDef, name, topic, route, namespaced)
if err != nil {
cancel()
return fmt.Errorf("failed to bulk subscribe to topic %s: %w", topic, err)
}
a.topicCtxCancels[subKey] = cancel
return nil
}
subscribeTopic := topic
if namespaced {
subscribeTopic = a.namespace + topic
}
err := a.pubSubs[name].component.Subscribe(ctx, pubsub.SubscribeRequest{
Topic: subscribeTopic,
Metadata: routeMetadata,
}, func(ctx context.Context, msg *pubsub.NewMessage) error {
if msg.Metadata == nil {
msg.Metadata = make(map[string]string, 1)
}
msg.Metadata[pubsubName] = name
msgTopic := msg.Topic
if a.pubSubs[name].namespaceScoped {
msgTopic = strings.Replace(msgTopic, a.namespace, "", 1)
}
rawPayload, err := contribMetadata.IsRawPayload(route.metadata)
if err != nil {
log.Errorf("error deserializing pubsub metadata: %s", err)
if route.deadLetterTopic != "" {
if dlqErr := a.sendToDeadLetter(name, msg, route.deadLetterTopic); dlqErr == nil {
// dlq has been configured and message is successfully sent to dlq.
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Drop)), msgTopic, 0)
return nil
}
}
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Retry)), msgTopic, 0)
return err
}
var cloudEvent map[string]interface{}
data := msg.Data
if rawPayload {
cloudEvent = pubsub.FromRawPayload(msg.Data, msgTopic, name)
data, err = json.Marshal(cloudEvent)
if err != nil {
log.Errorf("error serializing cloud event in pubsub %s and topic %s: %s", name, msgTopic, err)
if route.deadLetterTopic != "" {
if dlqErr := a.sendToDeadLetter(name, msg, route.deadLetterTopic); dlqErr == nil {
// dlq has been configured and message is successfully sent to dlq.
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Drop)), msgTopic, 0)
return nil
}
}
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Retry)), msgTopic, 0)
return err
}
} else {
err = json.Unmarshal(msg.Data, &cloudEvent)
if err != nil {
log.Errorf("error deserializing cloud event in pubsub %s and topic %s: %s", name, msgTopic, err)
if route.deadLetterTopic != "" {
if dlqErr := a.sendToDeadLetter(name, msg, route.deadLetterTopic); dlqErr == nil {
// dlq has been configured and message is successfully sent to dlq.
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Drop)), msgTopic, 0)
return nil
}
}
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Retry)), msgTopic, 0)
return err
}
}
if pubsub.HasExpired(cloudEvent) {
log.Warnf("dropping expired pub/sub event %v as of %v", cloudEvent[pubsub.IDField], cloudEvent[pubsub.ExpirationField])
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Drop)), msgTopic, 0)
if route.deadLetterTopic != "" {
_ = a.sendToDeadLetter(name, msg, route.deadLetterTopic)
}
return nil
}
routePath, shouldProcess, err := findMatchingRoute(route.rules, cloudEvent)
if err != nil {
log.Errorf("error finding matching route for event %v in pubsub %s and topic %s: %s", cloudEvent[pubsub.IDField], name, msgTopic, err)
if route.deadLetterTopic != "" {
if dlqErr := a.sendToDeadLetter(name, msg, route.deadLetterTopic); dlqErr == nil {
// dlq has been configured and message is successfully sent to dlq.
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Drop)), msgTopic, 0)
return nil
}
}
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Retry)), msgTopic, 0)
return err
}
if !shouldProcess {
// The event does not match any route specified so ignore it.
log.Debugf("no matching route for event %v in pubsub %s and topic %s; skipping", cloudEvent[pubsub.IDField], name, msgTopic)
diag.DefaultComponentMonitoring.PubsubIngressEvent(ctx, pubsubName, strings.ToLower(string(pubsub.Drop)), msgTopic, 0)
if route.deadLetterTopic != "" {
_ = a.sendToDeadLetter(name, msg, route.deadLetterTopic)
}
return nil
}
psm := &pubsubSubscribedMessage{
cloudEvent: cloudEvent,
data: data,
topic: msgTopic,
metadata: msg.Metadata,
path: routePath,
pubsub: name,
}
policyRunner := resiliency.NewRunner[any](ctx, policyDef)
_, err = policyRunner(func(ctx context.Context) (any, error) {
var pErr error
switch a.runtimeConfig.ApplicationProtocol {
case HTTPProtocol:
pErr = a.publishMessageHTTP(ctx, psm)
case GRPCProtocol:
pErr = a.publishMessageGRPC(ctx, psm)
default:
pErr = backoff.Permanent(errors.New("invalid application protocol"))
}
return nil, pErr
})
if err != nil && err != context.Canceled {
// Sending msg to dead letter queue.
// If no DLQ is configured, return error for backwards compatibility (component-level retry).
if route.deadLetterTopic == "" {
return err
}
_ = a.sendToDeadLetter(name, msg, route.deadLetterTopic)
return nil
}
return err
})
if err != nil {
cancel()
return fmt.Errorf("failed to subscribe to topic %s: %w", topic, err)
}
a.topicCtxCancels[subKey] = cancel
return nil
}
func (a *DaprRuntime) unsubscribeTopic(name string, topic string) error {
a.topicsLock.Lock()
defer a.topicsLock.Unlock()
subKey := pubsubTopicKey(name, topic)
cancel, ok := a.topicCtxCancels[subKey]
if !ok {
return fmt.Errorf("cannot unsubscribe from topic '%s' on pubsub '%s': the subscription does not exist", topic, name)
}
if cancel != nil {
cancel()
}
delete(a.topicCtxCancels, subKey)
return nil
}
func (a *DaprRuntime) beginPubSub(name string) error {
topicRoutes, err := a.getTopicRoutes()
if err != nil {
return err
}
v, ok := topicRoutes[name]
if !ok {
return nil
}
for topic, route := range v {
err = a.subscribeTopic(a.pubsubCtx, name, topic, route)
if err != nil {
// Log the error only
log.Errorf("error occurred while beginning pubsub for topic %s on component %s: %v", topic, name, err)
}
}
return nil
}
// findMatchingRoute selects the path based on routing rules. If there are
// no matching rules, the route-level path is used.
func findMatchingRoute(rules []*runtimePubsub.Rule, cloudEvent interface{}) (path string, shouldProcess bool, err error) {
hasRules := len(rules) > 0
if hasRules {
data := map[string]interface{}{
"event": cloudEvent,
}
rule, err := matchRoutingRule(rules, data)
if err != nil {
return "", false, err
}
if rule != nil {
return rule.Path, true, nil
}
}
return "", false, nil
}
func matchRoutingRule(rules []*runtimePubsub.Rule, data map[string]interface{}) (*runtimePubsub.Rule, error) {
for _, rule := range rules {
if rule.Match == nil {
return rule, nil
}
iResult, err := rule.Match.Eval(data)
if err != nil {
return nil, err
}
result, ok := iResult.(bool)
if !ok {