forked from Shuffle/shuffle-shared
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb-connector.go
executable file
·12456 lines (10547 loc) · 339 KB
/
db-connector.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
package shuffle
import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
//"strconv"
//"encoding/binary"
"math"
"math/rand"
"sort"
"strings"
"time"
"cloud.google.com/go/datastore"
"github.com/Masterminds/semver"
"github.com/bradfitz/slice"
uuid "github.com/satori/go.uuid"
//"github.com/frikky/kin-openapi/openapi3"
"github.com/patrickmn/go-cache"
"google.golang.org/api/iterator"
"cloud.google.com/go/storage"
gomemcache "github.com/bradfitz/gomemcache/memcache"
"google.golang.org/appengine/memcache"
//opensearch "github.com/shuffle/opensearch-go"
opensearch "github.com/opensearch-project/opensearch-go"
"github.com/opensearch-project/opensearch-go/v2/opensearchapi"
)
var requestCache = cache.New(60*time.Minute, 60*time.Minute)
var memcached = os.Getenv("SHUFFLE_MEMCACHED")
var mc = gomemcache.New(memcached)
var gceProject = os.Getenv("SHUFFLE_GCEPROJECT")
var propagateUrl = os.Getenv("SHUFFLE_PROPAGATE_URL")
var propagateToken = os.Getenv("SHUFFLE_PROPAGATE_TOKEN")
var maxCacheSize = 1020000
// Dumps data from cache to DB for every 5 action (old was 25)
// var dumpInterval = 0x19
// var dumpInterval = 0x1
var dumpInterval = 0x5
type ShuffleStorage struct {
GceProject string
Dbclient datastore.Client
StorageClient storage.Client
Environment string
CacheDb bool
Es opensearch.Client
DbType string
CloudUrl string
BucketName string
}
// Create ElasticSearch/OpenSearch index prefix
// It is used where a single cluster of ElasticSearch/OpenSearch utilized by several
// Shuffle instance
// E.g. Instance1_Workflowapp
func GetESIndexPrefix(index string) string {
prefix := os.Getenv("SHUFFLE_OPENSEARCH_INDEX_PREFIX")
if len(prefix) > 0 {
return fmt.Sprintf("%s_%s", prefix, index)
}
return index
}
// 1. Check list if there is a record for yesterday
// 2. If there isn't, set it and clear out the daily records
// Also: can we dump a list of apps that run? Maybe a list of them?
func handleDailyCacheUpdate(executionInfo *ExecutionInfo) *ExecutionInfo {
timeYesterday := time.Now().AddDate(0, 0, -1)
timeYesterdayFormatted := timeYesterday.Format("2006-12-02")
for _, day := range executionInfo.DailyStatistics {
// Check if the day.Date is the same as yesterday and return if it is
if day.Date.Format("2006-12-02") == timeYesterdayFormatted {
//log.Printf("[DEBUG] Daily stats already updated for %s. Data: %#v", day.Date, day)
return executionInfo
}
}
log.Printf("[DEBUG] Daily stats not updated for %s in org %s. Only have %d stats so far", timeYesterday, executionInfo.OrgId, len(executionInfo.DailyStatistics))
// If we get here, we need to update the daily stats
newDay := DailyStatistics{
Date: timeYesterday,
AppExecutions: executionInfo.DailyAppExecutions,
AppExecutionsFailed: executionInfo.DailyAppExecutionsFailed,
SubflowExecutions: executionInfo.DailySubflowExecutions,
WorkflowExecutions: executionInfo.DailyWorkflowExecutions,
WorkflowExecutionsFinished: executionInfo.DailyWorkflowExecutionsFinished,
WorkflowExecutionsFailed: executionInfo.DailyWorkflowExecutionsFailed,
OrgSyncActions: executionInfo.DailyOrgSyncActions,
CloudExecutions: executionInfo.DailyCloudExecutions,
OnpremExecutions: executionInfo.DailyOnpremExecutions,
AIUsage: executionInfo.DailyAIUsage,
ApiUsage: executionInfo.DailyApiUsage,
}
executionInfo.DailyStatistics = append(executionInfo.DailyStatistics, newDay)
// Reset daily
executionInfo.DailyAppExecutions = 0
executionInfo.DailyAppExecutionsFailed = 0
executionInfo.DailySubflowExecutions = 0
executionInfo.DailyWorkflowExecutions = 0
executionInfo.DailyWorkflowExecutionsFinished = 0
executionInfo.DailyWorkflowExecutionsFailed = 0
executionInfo.DailyOrgSyncActions = 0
executionInfo.DailyCloudExecutions = 0
executionInfo.DailyOnpremExecutions = 0
executionInfo.DailyApiUsage = 0
executionInfo.DailyAIUsage = 0
// Cleaning up old stuff we don't use for now
executionInfo.HourlyAppExecutions = 0
executionInfo.HourlyAppExecutionsFailed = 0
executionInfo.HourlySubflowExecutions = 0
executionInfo.HourlyWorkflowExecutions = 0
executionInfo.HourlyWorkflowExecutionsFinished = 0
executionInfo.HourlyWorkflowExecutionsFailed = 0
executionInfo.HourlyOrgSyncActions = 0
executionInfo.HourlyCloudExecutions = 0
executionInfo.HourlyOnpremExecutions = 0
// Weekly
executionInfo.WeeklyAppExecutions = 0
executionInfo.WeeklyAppExecutionsFailed = 0
executionInfo.WeeklySubflowExecutions = 0
executionInfo.WeeklyWorkflowExecutions = 0
executionInfo.WeeklyWorkflowExecutionsFinished = 0
executionInfo.WeeklyWorkflowExecutionsFailed = 0
executionInfo.WeeklyOrgSyncActions = 0
executionInfo.WeeklyCloudExecutions = 0
executionInfo.WeeklyOnpremExecutions = 0
return executionInfo
}
func HandleIncrement(dataType string, orgStatistics *ExecutionInfo) *ExecutionInfo {
if dataType == "workflow_executions" {
orgStatistics.TotalWorkflowExecutions += int64(dumpInterval)
orgStatistics.MonthlyWorkflowExecutions += int64(dumpInterval)
orgStatistics.WeeklyWorkflowExecutions += int64(dumpInterval)
orgStatistics.DailyWorkflowExecutions += int64(dumpInterval)
orgStatistics.HourlyWorkflowExecutions += int64(dumpInterval)
} else if dataType == "workflow_executions_finished" {
orgStatistics.TotalWorkflowExecutionsFinished += int64(dumpInterval)
orgStatistics.MonthlyWorkflowExecutionsFinished += int64(dumpInterval)
orgStatistics.WeeklyWorkflowExecutionsFinished += int64(dumpInterval)
orgStatistics.DailyWorkflowExecutionsFinished += int64(dumpInterval)
orgStatistics.HourlyWorkflowExecutionsFinished += int64(dumpInterval)
} else if dataType == "workflow_executions_failed" {
orgStatistics.TotalWorkflowExecutionsFailed += int64(dumpInterval)
orgStatistics.MonthlyWorkflowExecutionsFailed += int64(dumpInterval)
orgStatistics.WeeklyWorkflowExecutionsFailed += int64(dumpInterval)
orgStatistics.DailyWorkflowExecutionsFailed += int64(dumpInterval)
orgStatistics.HourlyWorkflowExecutionsFailed += int64(dumpInterval)
} else if dataType == "app_executions" {
orgStatistics.TotalAppExecutions += int64(dumpInterval)
orgStatistics.MonthlyAppExecutions += int64(dumpInterval)
orgStatistics.WeeklyAppExecutions += int64(dumpInterval)
orgStatistics.DailyAppExecutions += int64(dumpInterval)
orgStatistics.HourlyAppExecutions += int64(dumpInterval)
} else if dataType == "app_executions_failed" {
orgStatistics.TotalAppExecutionsFailed += int64(dumpInterval)
orgStatistics.MonthlyAppExecutionsFailed += int64(dumpInterval)
orgStatistics.WeeklyAppExecutionsFailed += int64(dumpInterval)
orgStatistics.DailyAppExecutionsFailed += int64(dumpInterval)
orgStatistics.HourlyAppExecutionsFailed += int64(dumpInterval)
} else if dataType == "subflow_executions" {
orgStatistics.TotalSubflowExecutions += int64(dumpInterval)
orgStatistics.MonthlySubflowExecutions += int64(dumpInterval)
orgStatistics.WeeklySubflowExecutions += int64(dumpInterval)
orgStatistics.DailySubflowExecutions += int64(dumpInterval)
orgStatistics.HourlySubflowExecutions += int64(dumpInterval)
} else if dataType == "org_sync_actions" {
orgStatistics.TotalOrgSyncActions += int64(dumpInterval)
orgStatistics.MonthlyOrgSyncActions += int64(dumpInterval)
orgStatistics.WeeklyOrgSyncActions += int64(dumpInterval)
orgStatistics.DailyOrgSyncActions += int64(dumpInterval)
orgStatistics.HourlyOrgSyncActions += int64(dumpInterval)
} else if dataType == "workflow_executions_cloud" {
orgStatistics.TotalCloudExecutions += int64(dumpInterval)
orgStatistics.MonthlyCloudExecutions += int64(dumpInterval)
orgStatistics.WeeklyCloudExecutions += int64(dumpInterval)
orgStatistics.DailyCloudExecutions += int64(dumpInterval)
orgStatistics.HourlyCloudExecutions += int64(dumpInterval)
} else if dataType == "workflow_executions_onprem" {
orgStatistics.TotalOnpremExecutions += int64(dumpInterval)
orgStatistics.MonthlyOnpremExecutions += int64(dumpInterval)
orgStatistics.WeeklyOnpremExecutions += int64(dumpInterval)
orgStatistics.DailyOnpremExecutions += int64(dumpInterval)
orgStatistics.HourlyOnpremExecutions += int64(dumpInterval)
} else if dataType == "api_usage" {
orgStatistics.TotalApiUsage += int64(dumpInterval)
orgStatistics.MonthlyApiUsage += int64(dumpInterval)
orgStatistics.DailyApiUsage += int64(dumpInterval)
} else if dataType == "ai_executions" {
orgStatistics.TotalAIUsage += int64(dumpInterval)
orgStatistics.MonthlyAIUsage += int64(dumpInterval)
orgStatistics.DailyAIUsage += int64(dumpInterval)
}
return orgStatistics
}
func SetOrgStatistics(ctx context.Context, stats ExecutionInfo, id string) error {
nameKey := "org_statistics"
// dedup based on date
allDates := []string{}
newDaily := []DailyStatistics{}
for _, stat := range stats.OnpremStats {
statdate := stat.Date.Format("2006-12-30")
if !ArrayContains(allDates, statdate) {
newDaily = append(newDaily, stat)
allDates = append(allDates, statdate)
}
}
if len(newDaily) < len(stats.OnpremStats) {
log.Printf("[INFO] Deduped %d stats for org %s", len(stats.OnpremStats)-len(newDaily), id)
}
stats.OnpremStats = newDaily
data, err := json.Marshal(stats)
if err != nil {
log.Printf("[ERROR] Failed marshalling in set stats: %s", err)
return nil
}
if project.DbType == "opensearch" {
err := indexEs(ctx, nameKey, id, data)
if err != nil {
log.Printf("[ERROR] Failed indexing in set stats: %s", err)
return err
}
} else {
key := datastore.NameKey(nameKey, id, nil)
if _, err := project.Dbclient.Put(ctx, key, &stats); err != nil {
log.Printf("[ERROR] Failed adding stats with ID %s: %s", id, err)
return err
}
}
if project.CacheDb {
cacheKey := fmt.Sprintf("%s_%s", nameKey, id)
data, err := json.Marshal(data)
if err != nil {
log.Printf("[WARNING] Failed marshalling in set org stats: %s", err)
return nil
}
err = SetCache(ctx, cacheKey, data, 30)
if err != nil {
log.Printf("[WARNING] Failed setting cache for org stats '%s': %s", cacheKey, err)
}
}
return nil
}
func IncrementCacheDump(ctx context.Context, orgId, dataType string) {
nameKey := "org_statistics"
orgStatistics := &ExecutionInfo{}
if project.DbType == "opensearch" {
// Get it from opensearch (may be prone to more issues at scale (thousands/second) due to no transactional locking)
id := strings.ToLower(orgId)
res, err := project.Es.Get(strings.ToLower(GetESIndexPrefix(nameKey)), id)
if err != nil {
log.Printf("[WARNING] Error in org STATS get: %s", err)
return
}
defer res.Body.Close()
respBody, bodyErr := ioutil.ReadAll(res.Body)
if err != nil || bodyErr != nil || res.StatusCode >= 300 {
log.Printf("[WARNING] Failed getting org STATS body: %s. Resp: %d. Body err: %s", err, res.StatusCode, bodyErr)
// Init the org stats if it doesn't exist
if res.StatusCode == 404 {
orgStatistics.OrgId = orgId
orgStatistics = HandleIncrement(dataType, orgStatistics)
orgStatistics = handleDailyCacheUpdate(orgStatistics)
marshalledData, err := json.Marshal(orgStatistics)
if err != nil {
log.Printf("[ERROR] Failed marshalling org STATS body: %s", err)
} else {
err := indexEs(ctx, nameKey, id, marshalledData)
if err != nil {
log.Printf("[ERROR] Failed indexing org STATS body: %s", err)
} else {
log.Printf("[DEBUG] Indexed org STATS body for %s", orgId)
}
}
}
return
}
orgStatsWrapper := &ExecutionInfoWrapper{}
err = json.Unmarshal(respBody, &orgStatsWrapper)
if err != nil {
log.Printf("[ERROR] Failed unmarshalling org STATS body: %s", err)
return
}
orgStatistics = &orgStatsWrapper.Source
if orgStatistics.OrgName == "" || orgStatistics.OrgName == orgStatistics.OrgId {
org, err := GetOrg(ctx, orgId)
if err == nil {
orgStatistics.OrgName = org.Name
}
orgStatistics.OrgId = orgId
}
orgStatistics = HandleIncrement(dataType, orgStatistics)
orgStatistics = handleDailyCacheUpdate(orgStatistics)
// Set the data back in the database
marshalledData, err := json.Marshal(orgStatistics)
if err != nil {
log.Printf("[ERROR] Failed marshalling org STATS body (2): %s", err)
return
}
err = indexEs(ctx, nameKey, id, marshalledData)
if err != nil {
log.Printf("[ERROR] Failed indexing org STATS body (2): %s", err)
}
//log.Printf("[DEBUG] Incremented org stats for %s", orgId)
} else {
tx, err := project.Dbclient.NewTransaction(ctx)
if err != nil {
log.Printf("[WARNING] Error in cache dump: %s", err)
return
}
key := datastore.NameKey(nameKey, strings.ToLower(orgId), nil)
if err := tx.Get(key, orgStatistics); err != nil {
if strings.Contains(fmt.Sprintf("%s", err), "no such entity") {
log.Printf("[DEBUG] Continuing by creating entity for org %s", orgId)
} else {
log.Printf("[ERROR] Failed getting stats in increment: %s", err)
tx.Rollback()
return
}
}
if orgStatistics.OrgName == "" || orgStatistics.OrgName == orgStatistics.OrgId {
org, err := GetOrg(ctx, orgId)
if err == nil {
orgStatistics.OrgName = org.Name
}
orgStatistics.OrgId = orgId
}
orgStatistics = HandleIncrement(dataType, orgStatistics)
orgStatistics = handleDailyCacheUpdate(orgStatistics)
if _, err := tx.Put(key, orgStatistics); err != nil {
log.Printf("[WARNING] Failed setting stats: %s", err)
tx.Rollback()
return
}
if _, err = tx.Commit(); err != nil {
log.Printf("[ERROR] Failed commiting stats: %s", err)
}
}
// Could use cache for everything, really
if project.CacheDb {
cacheKey := fmt.Sprintf("%s_%s", nameKey, orgId)
data, err := json.Marshal(orgStatistics)
if err != nil {
log.Printf("[WARNING] Failed marshalling in set org stats: %s", err)
return
}
err = SetCache(ctx, cacheKey, data, 30)
if err != nil {
log.Printf("[WARNING] Failed setting cache for org stats '%s': %s", cacheKey, err)
}
}
}
// Rudementary caching system. WILL go wrong at times without sharding.
// It's only good for the user in cloud, hence wont bother for a while
func IncrementCache(ctx context.Context, orgId, dataType string) {
// Check if environment is worker and skip
if project.Environment == "worker" {
//log.Printf("[DEBUG] Skipping cache increment for worker with datatype %s", dataType)
return
}
//log.Printf("[DEBUG] Incrementing cache '%s' for org '%s'", dataType, orgId)
// Dump to disk every 0x19
// 1. Get the existing value
// 2. Update it
dbDumpInterval := uint8(dumpInterval)
key := fmt.Sprintf("cache_%s_%s", orgId, dataType)
if len(memcached) > 0 {
item, err := mc.Get(key)
if err == gomemcache.ErrCacheMiss {
//log.Printf("[DEBUG] Increment memcache miss for %s: %s", key, err)
item := &gomemcache.Item{
Key: key,
Value: []byte(string(1)),
Expiration: 86400,
}
if err := mc.Set(item); err != nil {
log.Printf("[ERROR] Failed setting increment cache for key %s: %s", orgId, err)
}
} else if err != nil {
log.Printf("[ERROR] Failed increment memcache err: %s", err)
} else {
if item == nil || item.Value == nil {
item = &gomemcache.Item{
Key: key,
Value: []byte(string(1)),
Expiration: 86400,
}
log.Printf("[ERROR] Value in DB is nil for cache %s.", dataType)
}
if len(item.Value) == 1 {
num := item.Value[0]
num += 1
if num >= dbDumpInterval {
// Memcache dump first to keep the counter going for other executions
num = 0
item := &gomemcache.Item{
Key: key,
Value: []byte(string(num)),
Expiration: 86400,
}
if err := mc.Set(item); err != nil {
log.Printf("[ERROR] Failed setting inner memcache for key %s: %s", orgId, err)
}
IncrementCacheDump(ctx, orgId, dataType)
} else {
//log.Printf("NOT Dumping!")
item := &gomemcache.Item{
Key: key,
Value: []byte(string(num)),
Expiration: 86400,
}
if err := mc.Set(item); err != nil {
log.Printf("[ERROR] Failed setting inner memcache for key %s: %s", orgId, err)
}
}
} else {
log.Printf("[ERROR] Length of value is longer than 1")
}
}
} else {
// Get the cache, but use requestCache instead of memcache
item, err := GetCache(ctx, key)
if err != nil {
err = SetCache(ctx, key, []byte("1"), 86400)
if err != nil {
log.Printf("[ERROR] Failed setting increment cache for key %s: %s", orgId, err)
}
//log.Printf("[DEBUG] Increment cache miss for %s", key)
} else {
// make item into a number
foundItem := 1
if item == nil {
log.Printf("[ERROR] Value in DB is nil for cache %s. Setting to 1", dataType)
} else {
// Parse out int from []uint8 with marshal
foundData := []byte(item.([]uint8))
foundItem, err = strconv.Atoi(string(foundData))
if err != nil {
log.Printf("[ERROR] Failed converting item to int: %s", err)
foundItem = 1
} else {
foundItem += 1
}
}
if foundItem >= int(dbDumpInterval) {
// Memcache dump first to keep the counter going for other executions
go SetCache(ctx, key, []byte("0"), 86400)
go IncrementCacheDump(ctx, orgId, dataType)
} else {
// Set cacheo
err = SetCache(ctx, key, []byte(strconv.Itoa(foundItem)), 86400)
if err != nil {
log.Printf("[ERROR] Failed setting increment cache for key %s: %s", orgId, err)
}
}
}
return
}
}
// Cache handlers
func DeleteCache(ctx context.Context, name string) error {
if len(memcached) > 0 {
return mc.Delete(name)
}
//if project.Environment == "cloud" {
if false {
return memcache.Delete(ctx, name)
} else if project.Environment == "onprem" {
requestCache.Delete(name)
return nil
} else {
requestCache.Delete(name)
return nil
}
return errors.New(fmt.Sprintf("No cache found for %s when DELETING cache", name))
}
// Cache handlers
func GetCache(ctx context.Context, name string) (interface{}, error) {
if len(name) == 0 {
log.Printf("[ERROR] No name provided for cache")
return "", nil
}
name = strings.Replace(name, " ", "_", -1)
if len(memcached) > 0 {
item, err := mc.Get(name)
if err == gomemcache.ErrCacheMiss {
//log.Printf("[DEBUG] Cache miss for %s: %s", name, err)
} else if err != nil {
//log.Printf("[DEBUG] Failed to find cache for key %s: %s", name, err)
} else {
//log.Printf("[INFO] Got new cache: %s", item)
if len(item.Value) == maxCacheSize {
totalData := item.Value
keyCount := 1
keyname := fmt.Sprintf("%s_%d", name, keyCount)
for {
if item, err := mc.Get(keyname); err != nil {
break
} else {
if totalData != nil && item != nil && item.Value != nil {
totalData = append(totalData, item.Value...)
}
//log.Printf("%d - %d = ", len(item.Value), maxCacheSize)
if len(item.Value) != maxCacheSize {
break
}
}
keyCount += 1
keyname = fmt.Sprintf("%s_%d", name, keyCount)
}
// Random~ high number
if len(totalData) > 10062147 {
//log.Printf("[WARNING] CACHE: TOTAL SIZE FOR %s: %d", name, len(totalData))
}
return totalData, nil
} else {
return item.Value, nil
}
}
return "", errors.New(fmt.Sprintf("No cache found in SHUFFLE_MEMCACHED for %s", name))
}
if false {
if item, err := memcache.Get(ctx, name); err != nil {
} else if err != nil {
return "", errors.New(fmt.Sprintf("Failed getting CLOUD cache for %s: %s", name, err))
} else {
// Loops if cachesize is more than max allowed in memcache (multikey)
if len(item.Value) == maxCacheSize {
totalData := item.Value
keyCount := 1
keyname := fmt.Sprintf("%s_%d", name, keyCount)
for {
if item, err := memcache.Get(ctx, keyname); err != nil {
break
} else {
totalData = append(totalData, item.Value...)
//log.Printf("%d - %d = ", len(item.Value), maxCacheSize)
if len(item.Value) != maxCacheSize {
break
}
}
keyCount += 1
keyname = fmt.Sprintf("%s_%d", name, keyCount)
}
// Random~ high number
if len(totalData) > 10062147 {
//log.Printf("[WARNING] CACHE: TOTAL SIZE FOR %s: %d", name, len(totalData))
}
return totalData, nil
} else {
return item.Value, nil
}
}
} else if project.Environment == "onprem" {
//log.Printf("[INFO] GETTING CACHE FOR %s ONPREM", name)
if value, found := requestCache.Get(name); found {
return value, nil
} else {
return "", errors.New(fmt.Sprintf("Failed getting ONPREM cache for %s", name))
}
} else {
if value, found := requestCache.Get(name); found {
return value, nil
} else {
return "", errors.New(fmt.Sprintf("Failed getting ONPREM cache for %s", name))
}
//return "", errors.New(fmt.Sprintf("No cache handler for environment %s yet", project.Environment))
}
return "", errors.New(fmt.Sprintf("No cache found for %s", name))
}
// Sets a key in cache. Expiration is in minutes.
func SetCache(ctx context.Context, name string, data []byte, expiration int32) error {
// Set cache verbose
//if strings.Contains(name, "execution") || strings.Contains(name, "action") && len(data) > 1 {
//}
if len(name) == 0 {
log.Printf("[WARNING] Key '%s' is empty with value length %d and expiration %d. Skipping cache.", name, len(data), expiration)
return nil
}
// Maxsize ish~
name = strings.Replace(name, " ", "_", -1)
// Splitting into multiple cache items
//if project.Environment == "cloud" || len(memcached) > 0 {
if len(memcached) > 0 {
comparisonNumber := 50
if len(data) > maxCacheSize*comparisonNumber {
return errors.New(fmt.Sprintf("Couldn't set cache for %s - too large: %d > %d", name, len(data), maxCacheSize*comparisonNumber))
}
loop := false
if len(data) > maxCacheSize {
loop = true
//log.Printf("Should make multiple cache items for %s", name)
}
// Custom for larger sizes. Max is maxSize*10 when being set
if loop {
currentChunk := 0
keyAmount := 0
totalAdded := 0
chunkSize := maxCacheSize
nextStep := chunkSize
keyname := name
for {
if len(data) < nextStep {
nextStep = len(data)
}
parsedData := data[currentChunk:nextStep]
item := &memcache.Item{
Key: keyname,
Value: parsedData,
Expiration: time.Minute * time.Duration(expiration),
}
var err error
if len(memcached) > 0 {
newitem := &gomemcache.Item{
Key: keyname,
Value: parsedData,
Expiration: expiration * 60,
}
err = mc.Set(newitem)
} else {
err = memcache.Set(ctx, item)
}
if err != nil {
if !strings.Contains(fmt.Sprintf("%s", err), "App Engine context") {
log.Printf("[ERROR] Failed setting cache for '%s' (1): %s", keyname, err)
}
break
} else {
totalAdded += chunkSize
currentChunk = nextStep
nextStep += chunkSize
keyAmount += 1
//log.Printf("%s: %d: %d", keyname, totalAdded, len(data))
keyname = fmt.Sprintf("%s_%d", name, keyAmount)
if totalAdded > len(data) {
break
}
}
}
//log.Printf("[INFO] Set app cache with length %d and %d keys", len(data), keyAmount)
} else {
item := &memcache.Item{
Key: name,
Value: data,
Expiration: time.Minute * time.Duration(expiration),
}
var err error
if len(memcached) > 0 {
newitem := &gomemcache.Item{
Key: name,
Value: data,
Expiration: expiration * 60,
}
err = mc.Set(newitem)
} else {
err = memcache.Set(ctx, item)
}
if err != nil {
if !strings.Contains(fmt.Sprintf("%s", err), "App Engine context") {
log.Printf("[WARNING] Failed setting cache for key '%s' with data size %d (2): %s", name, len(data), err)
} else {
log.Printf("[ERROR] Something bad with App Engine context for memcache (key: %s): %s", name, err)
}
}
}
return nil
} else if project.Environment == "onprem" {
requestCache.Set(name, data, time.Minute*time.Duration(expiration))
} else {
requestCache.Set(name, data, time.Minute*time.Duration(expiration))
}
return nil
}
func GetDatastoreClient(ctx context.Context, projectID string) (datastore.Client, error) {
//client, err := datastore.NewClient(ctx, projectID, option.WithCredentialsFile(test"))
client, err := datastore.NewClient(ctx, projectID)
//client, err := datastore.NewClient(ctx, projectID, option.WithCredentialsFile("test"))
if err != nil {
return datastore.Client{}, err
}
return *client, nil
}
func SetWorkflowAppDatastore(ctx context.Context, workflowapp WorkflowApp, id string) error {
nameKey := "workflowapp"
cacheKey := fmt.Sprintf("%s_%s", nameKey, id)
timeNow := int64(time.Now().Unix())
workflowapp.Edited = timeNow
if workflowapp.Created == 0 {
workflowapp.Created = timeNow
}
// New struct, to not add body, author etc
data, err := json.Marshal(workflowapp)
if err != nil {
log.Printf("[WARNING] Failed marshalling in setapp: %s", err)
return nil
}
if project.DbType == "opensearch" {
err = indexEs(ctx, nameKey, workflowapp.ID, data)
if err != nil {
return err
}
} else {
key := datastore.NameKey(nameKey, id, nil)
if _, err := project.Dbclient.Put(ctx, key, &workflowapp); err != nil {
if strings.Contains(fmt.Sprintf("%s", err), "entity is too big") || strings.Contains(fmt.Sprintf("%s", err), "is longer than") {
workflowapp, err = UploadAppSpecFiles(ctx, &project.StorageClient, workflowapp, ParsedOpenApi{})
if err != nil {
log.Printf("[WARNING] Failed uploading app spec file in set workflow app: %s", err)
} else {
if _, err = project.Dbclient.Put(ctx, key, &workflowapp); err != nil {
log.Printf("[ERROR] Failed second upload of app %s (%s): %s", workflowapp.Name, workflowapp.ID, err)
} else {
log.Printf("[DEBUG] Successfully updated app %s (%s)!", workflowapp.Name, workflowapp.ID)
}
}
} else {
log.Printf("[WARNING] Error adding workflow app: %s", err)
}
if err != nil {
return err
}
}
}
if project.CacheDb {
// Don't want to overwrite this part.
//data, err := json.Marshal(workflowapp)
//if err != nil {
// log.Printf("[WARNING] Failed marshalling in setapp: %s", err)
// return nil
//}
err = SetCache(ctx, cacheKey, data, 30)
if err != nil {
log.Printf("[ERROR] Failed setting cache for 'setapp' key %s: %s", cacheKey, err)
}
DeleteCache(ctx, fmt.Sprintf("openapi3_%s", id))
}
return nil
}
func SetWorkflowExecution(ctx context.Context, workflowExecution WorkflowExecution, dbSave bool) error {
nameKey := "workflowexecution"
if len(workflowExecution.ExecutionId) == 0 {
log.Printf("[ERROR] Workflowexecution executionId can't be empty.")
// Generate it on the fly?
//workflowExecution.ExecutionId = uuid.NewV4().String()
return errors.New("ExecutionId can't be empty.")
}
if len(workflowExecution.WorkflowId) == 0 {
log.Printf("[WARNING][%s] Workflowexecution workflowId can't be empty.", workflowExecution.ExecutionId)
workflowExecution.WorkflowId = workflowExecution.Workflow.ID
}
if len(workflowExecution.Authorization) == 0 {
log.Printf("[WARNING][%s] Workflowexecution authorization can't be empty.", workflowExecution.ExecutionId)
//workflowExecution.Authorization = uuid.NewV4().String()
return errors.New("Authorization can't be empty.")
}
// Fixes missing pieces
workflowExecution, newDbSave := Fixexecution(ctx, workflowExecution)
if newDbSave {
dbSave = true
}
cacheKey := fmt.Sprintf("%s_%s", nameKey, workflowExecution.ExecutionId)
executionData, err := json.Marshal(workflowExecution)
if err == nil {
err = SetCache(ctx, cacheKey, executionData, 31)
if err != nil {
//log.Printf("[WARNING] Failed updating execution cache. Setting DB! %s", err)
dbSave = true
} else {
}
} else {
//log.Printf("[ERROR] Failed marshalling execution for cache: %s", err)
//log.Printf("[INFO] Set execution cache for workflowexecution %s", cacheKey)
}
// Weird workaround that only applies during local development
hostname, err := os.Hostname()
if err != nil || hostname == "debian" {
hostname = "shuffle-backend"
}
// FIXME: This right here has caused more problems during dev than anything
if (os.Getenv("SHUFFLE_SWARM_CONFIG") == "run" || project.Environment == "worker") && !strings.Contains(strings.ToLower(hostname), "backend") {
//log.Printf("[INFO] Not saving execution to DB (just cache), since we are running in swarm mode.")
return nil
}
// This may get data from cache, hence we need to continuously set things in the database. Mainly as a precaution.
newexec, err := GetWorkflowExecution(ctx, workflowExecution.ExecutionId)
if !dbSave && err == nil && (newexec.Status == "FINISHED" || newexec.Status == "ABORTED") {
log.Printf("[INFO][%s] Already finished (set workflow) with status %s! Stopping the rest of the request for execution.", workflowExecution.ExecutionId, newexec.Status)
return nil
}
// Deleting cache so that listing can work well
DeleteCache(ctx, fmt.Sprintf("%s_%s", nameKey, workflowExecution.WorkflowId))
DeleteCache(ctx, fmt.Sprintf("%s_%s_50", nameKey, workflowExecution.WorkflowId))
DeleteCache(ctx, fmt.Sprintf("%s_%s_100", nameKey, workflowExecution.WorkflowId))
if !dbSave && workflowExecution.Status == "EXECUTING" && len(workflowExecution.Results) > 1 {
//log.Printf("[WARNING][%s] SHOULD skip DB saving for execution. Status: %s", workflowExecution.ExecutionId, workflowExecution.Status)
if project.Environment != "cloud" {
return nil
}
// Randomly saving once every 5 times
// Just making sure results are saved
if rand.Intn(5) != 1 {
return nil
}
}
// New struct, to not add body, author etc
//log.Printf("[DEBUG][%s] Adding execution to database, not just cache. Workflow: %s (%s)", workflowExecution.ExecutionId, workflowExecution.Workflow.Name, workflowExecution.Workflow.ID)
if project.DbType == "opensearch" {
// Need to fix an indexing problem?
// "mapper [workflow.actions.position.x] cannot be changed from type [float] to [long]"
// Position doesn't matter in execution. Maybe just set all to 0?
for actionIndex, _ := range workflowExecution.Workflow.Actions {
workflowExecution.Workflow.Actions[actionIndex].Position.X = float64(0)
workflowExecution.Workflow.Actions[actionIndex].Position.Y = float64(0)
}
for actionIndex, _ := range workflowExecution.Workflow.Triggers {
workflowExecution.Workflow.Triggers[actionIndex].Position.X = float64(0)
workflowExecution.Workflow.Triggers[actionIndex].Position.Y = float64(0)
}
for actionIndex, _ := range workflowExecution.Workflow.Comments {
workflowExecution.Workflow.Comments[actionIndex].Position.X = float64(0)
workflowExecution.Workflow.Comments[actionIndex].Position.Y = float64(0)
}
err = indexEs(ctx, nameKey, workflowExecution.ExecutionId, executionData)
if err != nil {
log.Printf("[ERROR] Failed saving new execution %s: %s", workflowExecution.ExecutionId, err)
return err
}
//log.Printf("[INFO] Successfully saved new execution %s. Timestamp: %d!", workflowExecution.ExecutionId, workflowExecution.StartedAt)
} else {
// Compresses and removes unecessary things
workflowExecution, _ := compressExecution(ctx, workflowExecution, "db-connector save")
// Setting to nothing as this is realtime calculated anyway
workflowExecution.Result = ""
// Print 1 out of X times as a debug mode
if rand.Intn(20) == 1 {
log.Printf("[INFO][%s] Saving execution with status %s and %d/%d results (not including subflows) - 2", workflowExecution.ExecutionId, workflowExecution.Status, len(workflowExecution.Results), len(workflowExecution.Workflow.Actions))
}