/
cluster_eventingmgr.go
966 lines (845 loc) · 36.1 KB
/
cluster_eventingmgr.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
package gocb
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"strings"
"time"
)
// EventingFunctionManager provides methods for performing eventing function management operations.
// This manager is designed to work only against Couchbase Server 7.0+, it might work against earlier server
// versions but that is not tested and is not supported.
// UNCOMMITTED: This API may change in the future.
type EventingFunctionManager struct {
mgmtProvider mgmtProvider
tracer RequestTracer
meter *meterWrapper
}
func (efm *EventingFunctionManager) doMgmtRequest(ctx context.Context, req mgmtRequest) (*mgmtResponse, error) {
resp, err := efm.mgmtProvider.executeMgmtRequest(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
}
func (efm *EventingFunctionManager) tryParseErrorMessage(req *mgmtRequest, resp *mgmtResponse) error {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
logDebugf("Failed to read eventing function response body: %s", err)
return nil
}
var baseErr error
strBody := string(b)
if strings.Contains(strBody, "ERR_APP_NOT_FOUND_TS") {
baseErr = ErrEventingFunctionNotFound
} else if strings.Contains(strBody, "ERR_APP_NOT_DEPLOYED") {
baseErr = ErrEventingFunctionNotDeployed
} else if strings.Contains(strBody, "ERR_HANDLER_COMPILATION") {
baseErr = ErrEventingFunctionCompilationFailure
} else if strings.Contains(strBody, "ERR_SRC_MB_SAME") {
baseErr = ErrEventingFunctionIdenticalKeyspace
} else if strings.Contains(strBody, "ERR_APP_NOT_BOOTSTRAPPED") {
baseErr = ErrEventingFunctionNotBootstrapped
} else if strings.Contains(strBody, "ERR_APP_NOT_UNDEPLOYED") {
baseErr = ErrEventingFunctionDeployed
} else if strings.Contains(strBody, "ERR_COLLECTION_MISSING") {
baseErr = ErrCollectionNotFound
} else if strings.Contains(strBody, "ERR_BUCKET_MISSING") {
baseErr = ErrBucketNotFound
} else {
baseErr = errors.New(string(b))
}
return makeGenericMgmtError(baseErr, req, resp, strBody)
}
type jsonEventingFunction struct {
Name string `json:"appname"`
Code string `json:"appcode"`
Version string `json:"version"`
EnforceSchema bool `json:"enforce_schema,omitempty"`
HandlerUUID int `json:"handleruuid,omitempty"`
FunctionInstanceID string `json:"function_instance_id,omitempty"`
Settings jsonEventingFunctionSettings `json:"settings"`
DeploymentConfig jsonEventingFunctionDeploymentConfig `json:"depcfg"`
}
type jsonEventingFunctionSettings struct {
CPPWorkerThreadCount int `json:"cpp_worker_thread_count,omitempty"`
DCPStreamBoundary EventingFunctionDCPBoundary `json:"dcp_stream_boundary,omitempty"`
Description string `json:"description,omitempty"`
DeploymentStatus EventingFunctionDeploymentStatus `json:"deployment_status"`
ProcessingStatus EventingFunctionProcessingStatus `json:"processing_status"`
LanguageCompatibility EventingFunctionLanguageCompatibility `json:"language_compatibility,omitempty"`
LogLevel EventingFunctionLogLevel `json:"log_level,omitempty"`
ExecutionTimeout int `json:"execution_timeout,omitempty"`
LCBInstCapacity int `json:"lcb_inst_capacity,omitempty"`
LCBRetryCount int `json:"lcb_retry_count,omitempty"`
LCBTimeout int `json:"lcb_timeout,omitempty"`
QueryConsistency QueryScanConsistency `json:"n1ql_consistency,omitempty"`
NumTimerPartitions int `json:"num_timer_partitions,omitempty"`
SockBatchSize int `json:"sock_batch_size,omitempty"`
TickDuration int `json:"tick_duration,omitempty"`
TimerContextSize int `json:"timer_context_size,omitempty"`
UserPrefix string `json:"user_prefix,omitempty"`
BucketCacheSize int `json:"bucket_cache_size,omitempty"`
BucketCacheAge int `json:"bucket_cache_age,omitempty"`
CurlMaxAllowedRespSize int `json:"curl_max_allowed_resp_size,omitempty"`
QueryPrepareAll bool `json:"n1ql_prepare_all,omitempty"`
WorkerCount int `json:"worker_count,omitempty"`
HandlerHeaders []string `json:"handler_headers,omitempty"`
HandlerFooters []string `json:"handler_footers,omitempty"`
EnableAppLogRotation bool `json:"enable_applog_rotation,omitempty"`
AppLogDir string `json:"app_log_dir,omitempty"`
AppLogMaxSize int `json:"app_log_max_size,omitempty"`
AppLogMaxFiles int `json:"app_log_max_files,omitempty"`
CheckpointInterval int `json:"checkpoint_interval,omitempty"`
}
type jsonEventingFunctionDeploymentConfig struct {
MetadataBucket string `json:"metadata_bucket"`
MetadataScope string `json:"metadata_scope,omitempty"`
MetadataCollection string `json:"metadata_collection,omitempty"`
SourceBucket string `json:"source_bucket"`
SourceScope string `json:"source_scope,omitempty"`
SourceCollection string `json:"source_collection,omitempty"`
BucketBindings []jsonEventingFunctionBucketBinding `json:"buckets,omitempty"`
UrlBindings []jsonEventingFunctionUrlBinding `json:"curl,omitempty"`
ConstantBindings []jsonEventingFunctionConstantBinding `json:"constants,omitempty"`
}
type jsonEventingFunctionBucketBinding struct {
Alias string `json:"alias"`
Bucket string `json:"bucket_name"`
Scope string `json:"scope_name,omitempty"`
Collection string `json:"collection_name,omitempty"`
Access EventingFunctionBucketAccess `json:"access"`
}
type jsonEventingFunctionUrlBinding struct {
Hostname string `json:"hostname"`
Alias string `json:"value"`
AuthType string `json:"auth_type"`
AllowCookies bool `json:"allow_cookies"`
ValidateSSLCertificate bool `json:"validate_ssl_certificate"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
BearerKey string `json:"bearer_key,omitempty"`
}
type jsonEventingFunctionConstantBinding struct {
Alias string `json:"value"`
Literal string `json:"literal"`
}
type jsonEventingFunctionsStatusApp struct {
CompositeStatus EventingFunctionStatus `json:"composite_status"`
Name string `json:"name"`
NumBootstrappingNodes int `json:"num_bootstrapping_nodes"`
NumDeployedNodes int `json:"num_deployed_nodes"`
DeploymentStatus EventingFunctionDeploymentStatus `json:"deployment_status"`
ProcessingStatus EventingFunctionProcessingStatus `json:"processing_status"`
}
type jsonEventingFunctionsStatus struct {
Apps []jsonEventingFunctionsStatusApp `json:"apps"`
NumEventingNodes int `json:"num_eventing_nodes"`
}
// EventingFunctionStatus describes the current state of an eventing function.
type EventingFunctionStatus string
var (
// EventingFunctionStateUndeployed represents that the eventing function is undeployed.
EventingFunctionStateUndeployed EventingFunctionStatus = "undeployed"
// EventingFunctionStateDeploying represents that the eventing function is deploying.
EventingFunctionStateDeploying EventingFunctionStatus = "deploying"
// EventingFunctionStateDeployed represents that the eventing function is deployed.
EventingFunctionStateDeployed EventingFunctionStatus = "deployed"
// EventingFunctionStateUndeploying represents that the eventing function is undeploying.
EventingFunctionStateUndeploying EventingFunctionStatus = "undeploying"
// EventingFunctionStatePaused represents that the eventing function is paused.
EventingFunctionStatePaused EventingFunctionStatus = "paused"
// EventingFunctionStatePausing represents that the eventing function is pausing.
EventingFunctionStatePausing EventingFunctionStatus = "pausing"
)
// EventingFunctionDCPBoundary sets what data mutations to deploy the eventing function for.
type EventingFunctionDCPBoundary string
var (
// EventingFunctionDCPBoundaryEverything will deploy the eventing function for all data mutations.
EventingFunctionDCPBoundaryEverything EventingFunctionDCPBoundary = "everything"
// EventingFunctionDCPBoundaryFromNow will deploy the eventing function for only data mutations occurring post deployment.
EventingFunctionDCPBoundaryFromNow EventingFunctionDCPBoundary = "from_now"
)
// EventingFunctionDeploymentStatus represents the current deployment status for the eventing function.
type EventingFunctionDeploymentStatus bool
var (
// EventingFunctionDeploymentStatusDeployed represents that the eventing function is currently deployed.
EventingFunctionDeploymentStatusDeployed EventingFunctionDeploymentStatus = true
// EventingFunctionDeploymentStatusUndeployed represents that the eventing function is currently undeployed.
EventingFunctionDeploymentStatusUndeployed EventingFunctionDeploymentStatus = false
)
// EventingFunctionProcessingStatus represents the current processing status for the eventing function.
type EventingFunctionProcessingStatus bool
var (
// EventingFunctionProcessingStatusRunning represents that the eventing function is currently running.
EventingFunctionProcessingStatusRunning EventingFunctionProcessingStatus = true
// EventingFunctionProcessingStatusPaused represents that the eventing function is currently paused.
EventingFunctionProcessingStatusPaused EventingFunctionProcessingStatus = false
)
// EventingFunctionLanguageCompatibility represents the eventing function language compatibility for backward compatibility.
type EventingFunctionLanguageCompatibility string
var (
// EventingFunctionLanguageCompatibilityVersion600 represents the eventing function language compatibility 6.0.0.
EventingFunctionLanguageCompatibilityVersion600 EventingFunctionLanguageCompatibility = "6.0.0"
// EventingFunctionLanguageCompatibilityVersion650 represents the eventing function language compatibility 6.5.0.
EventingFunctionLanguageCompatibilityVersion650 EventingFunctionLanguageCompatibility = "6.5.0"
// EventingFunctionLanguageCompatibilityVersion662 represents the eventing function language compatibility 6.6.2.
EventingFunctionLanguageCompatibilityVersion662 EventingFunctionLanguageCompatibility = "6.6.2"
)
// EventingFunctionLogLevel represents the granularity at which to log messages for the eventing function.
type EventingFunctionLogLevel string
var (
// EventingFunctionLogLevelInfo represents to log messages at INFO for the eventing function.
EventingFunctionLogLevelInfo EventingFunctionLogLevel = "INFO"
// EventingFunctionLogLevelError represents to log messages at ERROR for the eventing function.
EventingFunctionLogLevelError EventingFunctionLogLevel = "ERROR"
// EventingFunctionLogLevelWarning represents to log messages at WARNING for the eventing function.
EventingFunctionLogLevelWarning EventingFunctionLogLevel = "WARNING"
// EventingFunctionLogLevelDebug represents to log messages at DEBUG for the eventing function.
EventingFunctionLogLevelDebug EventingFunctionLogLevel = "DEBUG"
// EventingFunctionLogLevelTrace represents to log messages at TRACE for the eventing function.
EventingFunctionLogLevelTrace EventingFunctionLogLevel = "TRACE"
)
// EventingFunctionSettings are the settings for an EventingFunction.
type EventingFunctionSettings struct {
CPPWorkerThreadCount int
DCPStreamBoundary EventingFunctionDCPBoundary
Description string
DeploymentStatus EventingFunctionDeploymentStatus
ProcessingStatus EventingFunctionProcessingStatus
LanguageCompatibility EventingFunctionLanguageCompatibility
LogLevel EventingFunctionLogLevel
ExecutionTimeout time.Duration
LCBInstCapacity int
LCBRetryCount int
LCBTimeout time.Duration
QueryConsistency QueryScanConsistency
NumTimerPartitions int
SockBatchSize int
TickDuration time.Duration
TimerContextSize int
UserPrefix string
BucketCacheSize int
BucketCacheAge int
CurlMaxAllowedRespSize int
QueryPrepareAll bool
WorkerCount int
HandlerHeaders []string
HandlerFooters []string
EnableAppLogRotation bool
AppLogDir string
AppLogMaxSize int
AppLogMaxFiles int
CheckpointInterval time.Duration
}
// EventingFunctionBucketAccess represents the level of access an eventing function has to a bucket.
type EventingFunctionBucketAccess string
var (
// EventingFunctionBucketAccessReadOnly represents readonly access to a bucket for an eventing function.
EventingFunctionBucketAccessReadOnly EventingFunctionBucketAccess = "r"
// EventingFunctionBucketAccessReadWrite represents readwrite access to a bucket for an eventing function.
EventingFunctionBucketAccessReadWrite EventingFunctionBucketAccess = "rw"
)
// EventingFunctionUrlAuth represents an authentication method for EventingFunctionUrlBinding for an eventing function.
type EventingFunctionUrlAuth interface {
Method() string
Username() string
Password() string
Key() string
}
// EventingFunctionUrlNoAuth specifies that no authentication is used for the EventingFunctionUrlBinding.
type EventingFunctionUrlNoAuth struct{}
func (ua EventingFunctionUrlNoAuth) Method() string {
return "no-auth"
}
func (ua EventingFunctionUrlNoAuth) Username() string {
return ""
}
func (ua EventingFunctionUrlNoAuth) Password() string {
return ""
}
func (ua EventingFunctionUrlNoAuth) Key() string {
return ""
}
// EventingFunctionUrlAuthBasic specifies that basic authentication is used for the EventingFunctionUrlBinding.
type EventingFunctionUrlAuthBasic struct {
User string
Pass string
}
func (ua EventingFunctionUrlAuthBasic) Method() string {
return "basic"
}
func (ua EventingFunctionUrlAuthBasic) Username() string {
return ua.User
}
func (ua EventingFunctionUrlAuthBasic) Password() string {
return ua.Pass
}
func (ua EventingFunctionUrlAuthBasic) Key() string {
return ""
}
// EventingFunctionUrlAuthDigest specifies that digest authentication is used for the EventingFunctionUrlBinding.
type EventingFunctionUrlAuthDigest struct {
User string
Pass string
}
func (ua EventingFunctionUrlAuthDigest) Method() string {
return "digest"
}
func (ua EventingFunctionUrlAuthDigest) Username() string {
return ua.User
}
func (ua EventingFunctionUrlAuthDigest) Password() string {
return ua.Pass
}
func (ua EventingFunctionUrlAuthDigest) Key() string {
return ""
}
// EventingFunctionUrlAuthBearer specifies that bearer token authentication is used for the EventingFunctionUrlBinding.
type EventingFunctionUrlAuthBearer struct {
BearerKey string
}
func (ua EventingFunctionUrlAuthBearer) Method() string {
return "bearer"
}
func (ua EventingFunctionUrlAuthBearer) Username() string {
return ""
}
func (ua EventingFunctionUrlAuthBearer) Password() string {
return ""
}
func (ua EventingFunctionUrlAuthBearer) Key() string {
return ua.BearerKey
}
// EventingFunctionBucketBinding represents an eventing function binding allowing the function access to buckets,
// scopes, and collections.
type EventingFunctionBucketBinding struct {
Alias string
Name EventingFunctionKeyspace
Access EventingFunctionBucketAccess
}
// EventingFunctionUrlBinding represents an eventing function binding allowing the function access external resources
// via cURL.
type EventingFunctionUrlBinding struct {
Hostname string
Alias string
Auth EventingFunctionUrlAuth
AllowCookies bool
ValidateSSLCertificate bool
}
// EventingFunctionConstantBinding represents an eventing function binding allowing the function to utilize global variables.
type EventingFunctionConstantBinding struct {
Alias string
Literal string
}
// EventingFunctionKeyspace represents a triple of bucket, collection, and scope names.
type EventingFunctionKeyspace struct {
Bucket string
Scope string
Collection string
}
// EventingStatus represents the current state of all eventing functions.
type EventingStatus struct {
NumEventingNodes int
Functions []EventingFunctionState
}
// EventingFunctionState represents the current state of an eventing function.
type EventingFunctionState struct {
Name string
Status EventingFunctionStatus
NumBootstrappingNodes int
NumDeployedNodes int
DeploymentStatus EventingFunctionDeploymentStatus
ProcessingStatus EventingFunctionProcessingStatus
}
func (ef *EventingStatus) UnmarshalJSON(b []byte) error {
var jf jsonEventingFunctionsStatus
err := json.Unmarshal(b, &jf)
if err != nil {
return err
}
var funcs []EventingFunctionState
for _, f := range jf.Apps {
funcs = append(funcs, EventingFunctionState{
Name: f.Name,
Status: f.CompositeStatus,
NumBootstrappingNodes: f.NumBootstrappingNodes,
NumDeployedNodes: f.NumDeployedNodes,
DeploymentStatus: f.DeploymentStatus,
ProcessingStatus: f.ProcessingStatus,
})
}
ef.NumEventingNodes = jf.NumEventingNodes
ef.Functions = funcs
return nil
}
// EventingFunction represents an eventing function.
type EventingFunction struct {
Name string // Required
Code string // Required
Version string
EnforceSchema bool
HandlerUUID int
FunctionInstanceID string
MetadataKeyspace EventingFunctionKeyspace // Required
SourceKeyspace EventingFunctionKeyspace // Required
BucketBindings []EventingFunctionBucketBinding
UrlBindings []EventingFunctionUrlBinding
ConstantBindings []EventingFunctionConstantBinding
Settings EventingFunctionSettings
}
func (ef EventingFunction) MarshalJSON() ([]byte, error) {
var bucketBindings []jsonEventingFunctionBucketBinding
for _, b := range ef.BucketBindings {
bucketBindings = append(bucketBindings, jsonEventingFunctionBucketBinding{
Alias: b.Alias,
Bucket: b.Name.Bucket,
Scope: b.Name.Scope,
Collection: b.Name.Collection,
Access: b.Access,
})
}
var urlBindings []jsonEventingFunctionUrlBinding
for _, b := range ef.UrlBindings {
urlBindings = append(urlBindings, jsonEventingFunctionUrlBinding{
Hostname: b.Hostname,
Alias: b.Alias,
AuthType: b.Auth.Method(),
AllowCookies: b.AllowCookies,
ValidateSSLCertificate: b.ValidateSSLCertificate,
Username: b.Auth.Username(),
Password: b.Auth.Password(),
BearerKey: b.Auth.Key(),
})
}
var constantBindings []jsonEventingFunctionConstantBinding
for _, b := range ef.ConstantBindings {
constantBindings = append(constantBindings, jsonEventingFunctionConstantBinding(b))
}
jsonSettings := jsonEventingFunction{
Name: ef.Name,
Code: ef.Code,
Version: ef.Version,
EnforceSchema: ef.EnforceSchema,
HandlerUUID: ef.HandlerUUID,
FunctionInstanceID: ef.FunctionInstanceID,
Settings: jsonEventingFunctionSettings{
CPPWorkerThreadCount: ef.Settings.CPPWorkerThreadCount,
DCPStreamBoundary: ef.Settings.DCPStreamBoundary,
Description: ef.Settings.Description,
DeploymentStatus: ef.Settings.DeploymentStatus,
ProcessingStatus: ef.Settings.ProcessingStatus,
LanguageCompatibility: ef.Settings.LanguageCompatibility,
LogLevel: ef.Settings.LogLevel,
ExecutionTimeout: int(ef.Settings.ExecutionTimeout.Seconds()),
LCBInstCapacity: ef.Settings.LCBInstCapacity,
LCBRetryCount: ef.Settings.LCBRetryCount,
LCBTimeout: int(ef.Settings.LCBTimeout.Seconds()),
QueryConsistency: ef.Settings.QueryConsistency,
NumTimerPartitions: ef.Settings.NumTimerPartitions,
SockBatchSize: ef.Settings.SockBatchSize,
TickDuration: int(ef.Settings.TickDuration.Milliseconds()),
TimerContextSize: ef.Settings.TimerContextSize,
UserPrefix: ef.Settings.UserPrefix,
BucketCacheSize: ef.Settings.BucketCacheSize,
BucketCacheAge: ef.Settings.BucketCacheAge,
CurlMaxAllowedRespSize: ef.Settings.CurlMaxAllowedRespSize,
QueryPrepareAll: ef.Settings.QueryPrepareAll,
WorkerCount: ef.Settings.WorkerCount,
HandlerHeaders: ef.Settings.HandlerHeaders,
HandlerFooters: ef.Settings.HandlerFooters,
EnableAppLogRotation: ef.Settings.EnableAppLogRotation,
AppLogDir: ef.Settings.AppLogDir,
AppLogMaxSize: ef.Settings.AppLogMaxSize,
AppLogMaxFiles: ef.Settings.AppLogMaxFiles,
CheckpointInterval: int(ef.Settings.CheckpointInterval.Seconds()),
},
DeploymentConfig: jsonEventingFunctionDeploymentConfig{
MetadataBucket: ef.MetadataKeyspace.Bucket,
MetadataScope: ef.MetadataKeyspace.Scope,
MetadataCollection: ef.MetadataKeyspace.Collection,
SourceBucket: ef.SourceKeyspace.Bucket,
SourceScope: ef.SourceKeyspace.Scope,
SourceCollection: ef.SourceKeyspace.Collection,
BucketBindings: bucketBindings,
UrlBindings: urlBindings,
ConstantBindings: constantBindings,
},
}
return json.Marshal(jsonSettings)
}
func (ef *EventingFunction) UnmarshalJSON(b []byte) error {
var jf jsonEventingFunction
err := json.Unmarshal(b, &jf)
if err != nil {
return err
}
var bucketBindings []EventingFunctionBucketBinding
for _, b := range jf.DeploymentConfig.BucketBindings {
bucketBindings = append(bucketBindings, EventingFunctionBucketBinding{
Alias: b.Alias,
Name: EventingFunctionKeyspace{
Bucket: b.Bucket,
Scope: b.Scope,
Collection: b.Collection,
},
Access: b.Access,
})
}
var urlBindings []EventingFunctionUrlBinding
for _, b := range jf.DeploymentConfig.UrlBindings {
var auth EventingFunctionUrlAuth
switch b.AuthType {
case "no-auth":
auth = EventingFunctionUrlNoAuth{}
case "basic":
auth = EventingFunctionUrlAuthBasic{
User: b.Username,
}
case "digest":
auth = EventingFunctionUrlAuthDigest{
User: b.Username,
}
case "bearer":
auth = EventingFunctionUrlAuthBearer{}
}
urlBindings = append(urlBindings, EventingFunctionUrlBinding{
Hostname: b.Hostname,
Alias: b.Alias,
Auth: auth,
AllowCookies: b.AllowCookies,
ValidateSSLCertificate: b.ValidateSSLCertificate,
})
}
var constantBindings []EventingFunctionConstantBinding
for _, b := range jf.DeploymentConfig.ConstantBindings {
constantBindings = append(constantBindings, EventingFunctionConstantBinding(b))
}
ef.Name = jf.Name
ef.Code = jf.Code
ef.Version = jf.Version
ef.EnforceSchema = jf.EnforceSchema
ef.HandlerUUID = jf.HandlerUUID
ef.FunctionInstanceID = jf.FunctionInstanceID
ef.Settings = EventingFunctionSettings{
CPPWorkerThreadCount: jf.Settings.CPPWorkerThreadCount,
DCPStreamBoundary: jf.Settings.DCPStreamBoundary,
Description: jf.Settings.Description,
DeploymentStatus: jf.Settings.DeploymentStatus,
ProcessingStatus: jf.Settings.ProcessingStatus,
LanguageCompatibility: jf.Settings.LanguageCompatibility,
LogLevel: jf.Settings.LogLevel,
ExecutionTimeout: time.Duration(jf.Settings.ExecutionTimeout) * time.Second,
LCBInstCapacity: jf.Settings.LCBInstCapacity,
LCBRetryCount: jf.Settings.LCBRetryCount,
LCBTimeout: time.Duration(jf.Settings.LCBTimeout) * time.Second,
QueryConsistency: jf.Settings.QueryConsistency,
NumTimerPartitions: jf.Settings.NumTimerPartitions,
SockBatchSize: jf.Settings.SockBatchSize,
TickDuration: time.Duration(jf.Settings.TickDuration) * time.Millisecond,
TimerContextSize: jf.Settings.TimerContextSize,
UserPrefix: jf.Settings.UserPrefix,
BucketCacheSize: jf.Settings.BucketCacheSize,
BucketCacheAge: jf.Settings.BucketCacheAge,
CurlMaxAllowedRespSize: jf.Settings.CurlMaxAllowedRespSize,
QueryPrepareAll: jf.Settings.QueryPrepareAll,
WorkerCount: jf.Settings.WorkerCount,
HandlerHeaders: jf.Settings.HandlerHeaders,
HandlerFooters: jf.Settings.HandlerFooters,
EnableAppLogRotation: jf.Settings.EnableAppLogRotation,
AppLogDir: jf.Settings.AppLogDir,
AppLogMaxSize: jf.Settings.AppLogMaxSize,
AppLogMaxFiles: jf.Settings.AppLogMaxFiles,
CheckpointInterval: time.Duration(jf.Settings.CheckpointInterval) * time.Second,
}
ef.MetadataKeyspace = EventingFunctionKeyspace{
Bucket: jf.DeploymentConfig.MetadataBucket,
Scope: jf.DeploymentConfig.MetadataScope,
Collection: jf.DeploymentConfig.MetadataCollection,
}
ef.SourceKeyspace = EventingFunctionKeyspace{
Bucket: jf.DeploymentConfig.SourceBucket,
Scope: jf.DeploymentConfig.SourceScope,
Collection: jf.DeploymentConfig.SourceCollection,
}
ef.BucketBindings = bucketBindings
ef.UrlBindings = urlBindings
ef.ConstantBindings = constantBindings
return nil
}
type eventingRequestOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
Context context.Context
}
func (efm *EventingFunctionManager) doRequest(path string, method string, opName string, function *EventingFunction,
target interface{}, opts eventingRequestOptions) error {
start := time.Now()
defer efm.meter.ValueRecord(meterValueServiceManagement, opName, start)
op := "manager_eventing_" + opName
span := createSpan(efm.tracer, opts.ParentSpan, op, "management")
span.SetAttribute("db.operation", method+" "+path)
defer span.End()
var b []byte
if function != nil {
var err error
b, err = json.Marshal(function)
if err != nil {
return err
}
}
req := mgmtRequest{
Service: ServiceTypeEventing,
Method: method,
Path: path,
RetryStrategy: opts.RetryStrategy,
Timeout: opts.Timeout,
parentSpanCtx: span.Context(),
Body: b,
}
resp, err := efm.doMgmtRequest(opts.Context, req)
if err != nil {
return err
}
defer ensureBodyClosed(resp.Body)
if resp.StatusCode != 200 {
idxErr := efm.tryParseErrorMessage(&req, resp)
if idxErr != nil {
return idxErr
}
return makeMgmtBadStatusError("failed eventing "+opName, &req, resp)
}
if target != nil {
jsonDec := json.NewDecoder(resp.Body)
err = jsonDec.Decode(target)
if err != nil {
return err
}
}
return nil
}
// UpsertEventingFunctionOptions are the options available when using the UpsertFunction operation.
type UpsertEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// UpsertFunction inserts or updates an eventing function.
func (efm *EventingFunctionManager) UpsertFunction(function EventingFunction, opts *UpsertEventingFunctionOptions) error {
if opts == nil {
opts = &UpsertEventingFunctionOptions{}
}
return efm.doRequest(fmt.Sprintf("/api/v1/functions/%s", function.Name), "POST",
"upsert_function", &function, nil, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
}
// DropEventingFunctionOptions are the options available when using the DropFunction operation.
type DropEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// DropFunction drops an eventing function.
func (efm *EventingFunctionManager) DropFunction(name string, opts *DropEventingFunctionOptions) error {
if opts == nil {
opts = &DropEventingFunctionOptions{}
}
return efm.doRequest(fmt.Sprintf("/api/v1/functions/%s", name), "DELETE",
"drop_function", nil, nil, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
}
// DeployEventingFunctionOptions are the options available when using the DeployFunction operation.
type DeployEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// DeployFunction deploys an eventing function.
func (efm *EventingFunctionManager) DeployFunction(name string, opts *DeployEventingFunctionOptions) error {
if opts == nil {
opts = &DeployEventingFunctionOptions{}
}
return efm.doRequest(fmt.Sprintf("/api/v1/functions/%s/deploy", name), "POST",
"deploy_function", nil, nil, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
}
// UndeployEventingFunctionOptions are the options available when using the UndeployFunction operation.
type UndeployEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// UndeployFunction undeploys an eventing function.
func (efm *EventingFunctionManager) UndeployFunction(name string, opts *UndeployEventingFunctionOptions) error {
if opts == nil {
opts = &UndeployEventingFunctionOptions{}
}
return efm.doRequest(fmt.Sprintf("/api/v1/functions/%s/undeploy", name), "POST",
"undeploy_function", nil, nil, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
}
// GetAllEventingFunctionsOptions are the options available when using the GetAllFunctions operation.
type GetAllEventingFunctionsOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// GetAllFunctions fetches all of the eventing functions.
func (efm *EventingFunctionManager) GetAllFunctions(opts *GetAllEventingFunctionsOptions) ([]EventingFunction, error) {
if opts == nil {
opts = &GetAllEventingFunctionsOptions{}
}
var functions []EventingFunction
err := efm.doRequest("/api/v1/functions", "GET",
"get_all_functions", nil, &functions, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
if err != nil {
return nil, err
}
return functions, nil
}
// GetEventingFunctionOptions are the options available when using the GetFunction operation.
type GetEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// GetFunction fetches an eventing function.
func (efm *EventingFunctionManager) GetFunction(name string, opts *GetEventingFunctionOptions) (*EventingFunction, error) {
if opts == nil {
opts = &GetEventingFunctionOptions{}
}
var function *EventingFunction
err := efm.doRequest(fmt.Sprintf("/api/v1/functions/%s", name), "GET",
"get_function", nil, &function, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
if err != nil {
return nil, err
}
return function, nil
}
// PauseEventingFunctionOptions are the options available when using the PauseFunction operation.
type PauseEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// PauseFunction pauses an eventing function.
func (efm *EventingFunctionManager) PauseFunction(name string, opts *PauseEventingFunctionOptions) error {
if opts == nil {
opts = &PauseEventingFunctionOptions{}
}
return efm.doRequest(fmt.Sprintf("/api/v1/functions/%s/pause", name), "POST",
"pause_function", nil, nil, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
}
// ResumeEventingFunctionOptions are the options available when using the ResumeFunction operation.
type ResumeEventingFunctionOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// ResumeFunction resumes an eventing function.
func (efm *EventingFunctionManager) ResumeFunction(name string, opts *ResumeEventingFunctionOptions) error {
if opts == nil {
opts = &ResumeEventingFunctionOptions{}
}
return efm.doRequest(fmt.Sprintf("/api/v1/functions/%s/resume", name), "POST",
"resume_function", nil, nil, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
}
// EventingFunctionsStatusOptions are the options available when using the FunctionsStatus operation.
type EventingFunctionsStatusOptions struct {
Timeout time.Duration
RetryStrategy RetryStrategy
ParentSpan RequestSpan
// Using a deadlined Context alongside a Timeout will cause the shorter of the two to cause cancellation, this
// also applies to global level timeouts.
// UNCOMMITTED: This API may change in the future.
Context context.Context
}
// FunctionsStatus fetches the current status of all eventing functions.
func (efm *EventingFunctionManager) FunctionsStatus(opts *EventingFunctionsStatusOptions) (*EventingStatus, error) {
if opts == nil {
opts = &EventingFunctionsStatusOptions{}
}
var functions *EventingStatus
err := efm.doRequest("/api/v1/status", "GET",
"functions_status", nil, &functions, eventingRequestOptions{
Timeout: opts.Timeout,
RetryStrategy: opts.RetryStrategy,
ParentSpan: opts.ParentSpan,
Context: opts.Context,
})
if err != nil {
return nil, err
}
return functions, nil
}