-
Notifications
You must be signed in to change notification settings - Fork 4
/
ds.go
1632 lines (1611 loc) · 46 KB
/
ds.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 dads
import (
"database/sql"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
)
// Typical run:
// DA_DS=jira DA_JIRA_ENRICH=1 DA_JIRA_ES_URL=... DA_JIRA_RAW_INDEX=proj-raw DA_JIRA_RICH_INDEX=proj DA_JIRA_URL=https://jira.xyz.org DA_JIRA_DEBUG=1 DA_JIRA_PROJECT=proj DA_JIRA_DB_NAME=db DA_JIRA_DB_USER=u DA_JIRA_DB_PASS=p DA_JIRA_MULTI_ORIGIN=1 ./dads
const (
// BulkRefreshMode - bulk upload refresh mode, can be: false, true, wait_for (ES defaults to false)
BulkRefreshMode = "true"
// BulkWaitForActiveShardsMode - bulk upload wait_for_active_shards mode, can be: 1, 2, ..., all (ES defaults to 1)
BulkWaitForActiveShardsMode = "all"
// KeywordMaxlength - max description length
KeywordMaxlength = 1000
// DefaultRateLimitHeader - default value for rate limit header
DefaultRateLimitHeader = "X-RateLimit-Remaining"
// DefaultRateLimitResetHeader - default value for rate limit reset header
DefaultRateLimitResetHeader = "X-RateLimit-Reset"
)
var (
// SettingsFieldsNumberLimit - make maximum number of index fields bigger (some raw indices have a lot of fields and we don't control this)
SettingsFieldsNumberLimit = []byte(`{"index.mapping.total_fields.limit":50000}`)
// MappingNotAnalyzeString - make all string keywords by default (not analyze them)
MappingNotAnalyzeString = []byte(`{"dynamic_templates":[{"notanalyzed":{"match":"*","match_mapping_type":"string","mapping":{"type":"keyword"}}},{"formatdate":{"match":"*","match_mapping_type":"date","mapping":{"type":"date","format":"strict_date_optional_time||epoch_millis"}}}]}`)
// RawFields - standard raw fields
RawFields = []string{DefaultDateField, DefaultTimestampField, DefaultOriginField, DefaultTagField, UUID, Offset}
// DefaultDateFrom - default date from
DefaultDateFrom = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
)
// DS - interface for all data source types
type DS interface {
ParseArgs(*Ctx) error
Name() string
Info() string
Validate(*Ctx) error
FetchRaw(*Ctx) error
FetchItems(*Ctx) error
Enrich(*Ctx) error
DateField(*Ctx) string
OffsetField(*Ctx) string
OriginField(*Ctx) string
Categories() map[string]struct{}
CustomFetchRaw() bool
CustomEnrich() bool
SupportDateFrom() bool
SupportOffsetFrom() bool
ResumeNeedsOrigin(*Ctx, bool) bool
ResumeNeedsCategory(*Ctx, bool) bool
Origin(*Ctx) string
ItemID(interface{}) string
RichIDField(*Ctx) string
RichAuthorField(*Ctx) string
ItemUpdatedOn(interface{}) time.Time
ItemCategory(interface{}) string
ElasticRawMapping() []byte
ElasticRichMapping() []byte
AddMetadata(*Ctx, interface{}) map[string]interface{}
GetItemIdentities(*Ctx, interface{}) (map[[3]string]struct{}, error)
EnrichItems(*Ctx) error
EnrichItem(*Ctx, map[string]interface{}, string, bool, interface{}) (map[string]interface{}, error)
AffsItems(*Ctx, map[string]interface{}, []string, interface{}) (map[string]interface{}, error)
GetRoleIdentity(*Ctx, map[string]interface{}, string) map[string]interface{}
AllRoles(*Ctx, map[string]interface{}) ([]string, bool)
CalculateTimeToReset(*Ctx, int, int) int
HasIdentities() bool
UseDefaultMapping(*Ctx, bool) bool
}
// CommonFields - common rich item fields
// { "is_dsname_category": 1, "grimoire_creation_date": dt}
func CommonFields(ds DS, date interface{}, category string) (fields map[string]interface{}) {
dt, err := TimeParseInterfaceString(date)
if err != nil {
switch vdt := date.(type) {
case string:
// 1st date is in UTC, 2nd is in TZ, 3rd is TZ offset innhours
var ok bool
dt, _, _, ok = ParseDateWithTz(vdt)
if !ok {
Fatalf("CommonFields: cannot parse date %s\n", vdt)
return
}
case time.Time:
dt = vdt
default:
Fatalf("cannot parse date %T %v\n", vdt, vdt)
return
}
}
name := "is_" + ds.Name() + "_" + category
fields = map[string]interface{}{"grimoire_creation_date": dt, name: 1}
return
}
// ESBulkUploadFunc - function to bulk upload items to ES
// We assume here that docs maintained my iterator func contains a list of rich items
// outDocs is maintained with ES bulk size
// last flag signalling that this is the last (so it must flush output then)
// there can be no items in input pack in the last flush call
func ESBulkUploadFunc(ctx *Ctx, ds DS, thrN int, docs, outDocs *[]interface{}, last bool) (e error) {
if ctx.Debug > 0 {
Printf("ES bulk uploading %d/%d func\n", len(*docs), len(*outDocs))
}
bulkSize := ctx.ESBulkSize
itemID := ds.RichIDField(ctx)
run := func() (err error) {
nItems := len(*outDocs)
if ctx.Debug > 0 {
Printf("ES bulk uploading %d items to ES\n", nItems)
}
nPacks := nItems / bulkSize
if nItems%bulkSize != 0 {
nPacks++
}
for i := 0; i < nPacks; i++ {
from := i * bulkSize
to := from + bulkSize
if to > nItems {
to = nItems
}
if ctx.Debug > 0 {
Printf("ES bulk upload: bulk uploading pack #%d %d-%d (%d/%d) to ES\n", i+1, from, to, to-from, nPacks)
}
err = SendToElastic(ctx, ds, false, itemID, (*outDocs)[from:to])
if err != nil {
return
}
}
return
}
nDocs := len(*docs)
nOutDocs := len(*outDocs)
if ctx.Debug > 0 {
Printf("ES bulk upload pack size %d/%d last %v\n", nDocs, nOutDocs, last)
}
for _, doc := range *docs {
*outDocs = append(*outDocs, doc)
nOutDocs = len(*outDocs)
if nOutDocs >= bulkSize {
if ctx.Debug > 0 {
Printf("ES bulk pack size %d/%d reached, flushing\n", nOutDocs, bulkSize)
}
e = run()
if e != nil {
return
}
*outDocs = []interface{}{}
}
}
if last {
nOutDocs := len(*outDocs)
if nOutDocs > 0 {
e = run()
if e != nil {
return
}
*outDocs = []interface{}{}
}
}
*docs = []interface{}{}
if ctx.Debug > 0 {
nOutDocs = len(*outDocs)
if nOutDocs > 0 {
Printf("ES bulk upload %d items left (last %v)\n", nOutDocs, last)
}
}
return
}
// DBUploadIdentitiesFunc - function to upload identities to affiliation DB
// We assume here that docs maintained my iterator func contains a list of [3]string
// Each identity is [3]string [name, username, email]
// outDocs is maintained with DB bulk size
// last flag signalling that this is the last (so it must flush output then)
// there can be no items in input pack in the last flush call
func DBUploadIdentitiesFunc(ctx *Ctx, ds DS, thrN int, docs, outDocs *[]interface{}, last bool) (e error) {
if ctx.Debug > 0 {
Printf("DB bulk uploading %d/%d identities func\n", len(*docs), len(*outDocs))
}
//bulkSize := ctx.DBBulkSize / 6
// We don't insert 1000 parameters into one () but 100 times (?,?,?,?,?,?)
bulkSize := ctx.DBBulkSize
run := func() (err error) {
var tx *sql.Tx
err = SetDBSessionOrigin(ctx)
if err != nil {
return
}
tx, err = ctx.DB.Begin()
if err != nil {
return
}
// Dedup (data comes from possibly multiple input packs
// Each one is already deduped but the combination may have duplicates
nNonUni := len(*outDocs)
idents := make(map[[3]string]struct{})
for _, doc := range *outDocs {
idents[doc.([3]string)] = struct{}{}
}
identsAry := [][3]string{}
for ident := range idents {
identsAry = append(identsAry, ident)
}
nIdents := len(identsAry)
source := ds.Name()
runOneByOne := func() (err error) {
Printf("DB bulk upload: falling back to one-by-one mode for %d items\n", nIdents)
var (
er error
errs []error
itx *sql.Tx
)
defer func() {
nErrs := len(errs)
if nErrs == 0 {
Printf("DB bulk upload: one-by-one mode for %d items - all succeeded\n", nIdents)
return
}
s := fmt.Sprintf("%d errors: ", nErrs)
for _, er := range errs {
s += er.Error() + ", "
}
s = s[:len(s)-2]
err = fmt.Errorf("%s", s)
Printf("DB bulk upload: one-by-one mode for %d items: %d errors\n", nIdents, nErrs)
}()
for i := 0; i < nIdents; i++ {
ident := identsAry[i]
if ctx.DebugSQL > 0 {
Printf("DB bulk upload: one-by-one: ident %d/%d: %+v\n", i, nIdents, ident)
}
queryU := "insert ignore into uidentities(uuid,last_modified) values"
queryI := "insert ignore into identities(id,source,name,email,username,uuid,last_modified) values"
queryP := "insert ignore into profiles(uuid,name,email) values"
argsU := []interface{}{}
argsI := []interface{}{}
argsI2 := []interface{}{}
argsP := []interface{}{}
name := ident[0]
username := ident[1]
email := ident[2]
// DA-4391 - future
// returns (valid, newEmail), if email is invalid "" is returned this is why we can skip testing for valid
// params: (email, validateDomain, guess), guess means that we do some replaces like " at " -> "@" etc.
origemail := email
_, email = IsValidEmail(email, true, true)
// DA-4366: starts
origname := name
origusername := username
// DA-4366: ends
name, username = PostprocessNameUsername(name, username, email)
var (
pname *string
pemail *string
pusername *string
profname *string
porigname *string
porigusername *string
porigemail *string
)
if name != Nil {
pname = &name
profname = &name
}
if email != Nil {
pemail = &email
}
if username != Nil {
pusername = &username
}
if origname != Nil {
porigname = &origname
}
if origusername != Nil {
porigusername = &origusername
}
if origemail != Nil {
porigemail = &origemail
}
if ctx.DebugSQL > 0 {
Printf("DB bulk upload: one-by-one: %d/%d: ('%s','%s','%s','%s','%s','%s')\n", i, nIdents, name, username, email, origname, origusername, origemail)
}
if pname == nil && pemail == nil && pusername == nil {
continue
}
// if username matches a real email and there is no email set, assume email=username
if pemail == nil && pusername != nil {
valid, em := IsValidEmail(username, true, true)
if valid {
username = em
pemail = &username
email = username
}
}
// if name matches a real email and there is no email set, assume email=name
if pemail == nil && pname != nil {
valid, em := IsValidEmail(name, true, true)
if valid {
name = em
pemail = &name
email = name
}
}
// uuid(source, email, name, username)
// DA-4366: starts
origuuid := UUIDAffs(ctx, source, origemail, origname, origusername)
if origuuid == "" {
er := fmt.Errorf("error: uploadToDB: failed to generate orig uuid for (%s,%s,%s,%s)", source, origemail, origname, origusername)
Printf("DB bulk upload: one-by-one(%d/%d): %v\n", i+1, nIdents, er)
errs = append(errs, er)
continue
}
// DA-4366: ends
uuid := UUIDAffs(ctx, source, email, name, username)
if ctx.DebugSQL > 0 {
Printf("DB bulk upload: one-by-one: %d/%d: ('%s','%s','%s','%s','%s','%s','%s','%s')\n", i, nIdents, name, username, email, origname, origusername, origemail, uuid, origuuid)
}
if uuid == "" {
er := fmt.Errorf("error: uploadToDB: failed to generate uuid for (%s,%s,%s,%s)", source, email, name, username)
Printf("DB bulk upload: one-by-one(%d/%d): %v\n", i+1, nIdents, er)
errs = append(errs, er)
continue
}
var rows *sql.Rows
rows, er = QuerySQL(ctx, nil, "select uuid from identities where id in (?, ?)", uuid, origuuid)
if er != nil {
errs = append(errs, er)
continue
}
mergedUUID := uuid
// DA-4366: starts
foundUUID := 0
// DA-4366: ends
for rows.Next() {
er = rows.Scan(&mergedUUID)
if er == nil {
foundUUID = 1
}
break
}
if er != nil {
errs = append(errs, er)
continue
}
er = rows.Err()
if er != nil {
errs = append(errs, er)
continue
}
er = rows.Close()
if er != nil {
errs = append(errs, er)
continue
}
if foundUUID == 0 {
// Try to find matching identity even it it was generated with an old UUID library
rows, er = QuerySQL(ctx, nil, "select id, uuid from identities where source = ? and name = ? and username = ? and email = ?", source, porigname, porigusername, porigemail)
if er != nil {
errs = append(errs, er)
continue
}
iid := ""
for rows.Next() {
er = rows.Scan(&iid, &mergedUUID)
if er == nil {
foundUUID = 2
}
break
}
if er != nil {
errs = append(errs, er)
continue
}
er = rows.Err()
if er != nil {
errs = append(errs, er)
continue
}
er = rows.Close()
if er != nil {
errs = append(errs, er)
continue
}
// Fix that identity's id
if foundUUID == 2 {
_, er = ExecSQL(ctx, itx, "update identities set id = ? where id = ?", origuuid, iid)
if er != nil {
Printf("DB bulk upload: one-by-one(%d/%d): failed to update identity id %s->%s: %+v\n", i+1, nIdents, origuuid, iid, er)
// _ = itx.Rollback()
// errs = append(errs, er)
// continue
}
}
}
if ctx.Debug > 0 && (uuid != mergedUUID || origuuid != mergedUUID) {
Printf("one-by-one: merged profile detected: %s/%s -> %s,%d\n", uuid, origuuid, mergedUUID, foundUUID)
}
// DA-4366: starts
// skip adding identity/profile/uidentity if identity already exists
/*
if isMerged {
continue
}
rows, er = QuerySQL(ctx, nil, "select 1 from profiles where uuid in (?, ?)", uuid, origuuid)
if er != nil {
errs = append(errs, er)
continue
}
dummy := 0
for rows.Next() {
er = rows.Scan(&dummy)
break
}
if er != nil {
errs = append(errs, er)
continue
}
er = rows.Err()
if er != nil {
errs = append(errs, er)
continue
}
er = rows.Close()
if er != nil {
errs = append(errs, er)
continue
}
// skip adding identity/profile/uidentity if identity already exists
if dummy != 0 {
continue
}
*/
// DA-4366: ends
queryU += fmt.Sprintf("(?,now())")
queryI += fmt.Sprintf("(?,?,?,?,?,?,now())")
queryP += fmt.Sprintf("(?,?,?)")
argsU = append(argsU, mergedUUID)
// DA-4366: starts
// argsI = append(argsI, uuid, source, pname, pemail, pusername, mergedUUID)
argsI = append(argsI, origuuid, source, porigname, porigemail, porigusername, mergedUUID)
// DA-4366: ends
argsP = append(argsP, mergedUUID, profname, pemail)
itx, err = ctx.DB.Begin()
if err != nil {
return
}
_, er = ExecSQL(ctx, itx, queryU, argsU...)
if er != nil {
Printf("DB bulk upload: one-by-one(%d/%d): %s[%+v]: %v\n", i+1, nIdents, queryU, argsU, er)
_ = itx.Rollback()
errs = append(errs, er)
continue
}
_, er = ExecSQL(ctx, itx, queryP, argsP...)
if er != nil {
Printf("DB bulk upload: one-by-one(%d/%d): %s[%+v]: %v\n", i+1, nIdents, queryP, argsP, er)
_ = itx.Rollback()
errs = append(errs, er)
continue
}
_, er = ExecSQL(ctx, itx, queryI, argsI...)
if er != nil {
Printf("DB bulk upload: one-by-one(%d/%d): %s[%+v]: %v\n", i+1, nIdents, queryI, argsI, er)
_ = itx.Rollback()
errs = append(errs, er)
continue
}
if uuid != origuuid {
argsI2 = append(argsI2, uuid, source, pname, pemail, pusername, mergedUUID)
_, er = ExecSQL(ctx, itx, queryI, argsI2...)
if er != nil {
Printf("DB bulk upload: one-by-one(%d/%d): %s[%+v]: %v\n", i+1, nIdents, queryI, argsI2, er)
_ = itx.Rollback()
errs = append(errs, er)
continue
}
}
err = itx.Commit()
if err != nil {
return
}
itx = nil
}
return
}
if ctx.Debug > 0 {
Printf("DB bulk upload: bulk adding %d (%d unique) idents\n", nNonUni, nIdents)
}
// NOTE: For normal bulk mode operation, uncomment the deferred function
/*
defer func() {
if tx != nil {
if ctx.DryRun {
Printf("DB bulk upload: dry-run: rolling back %d identities insert (possibly due to dry-run mode)\n", nIdents)
} else {
Printf("DB bulk upload: rolling back %d identities insert\n", nIdents)
}
_ = tx.Rollback()
err = runOneByOne()
}
}()
*/
// NOTE: now because new specs were added - and they prevent bulk mode, because we need to check the DB state first, before any insert
// Comment out manually called runOneByOne() and uncomment deferred
err = runOneByOne()
if 1 == 1 {
return
}
// End note.
nPacks := nIdents / bulkSize
if nIdents%bulkSize != 0 {
nPacks++
}
for i := 0; i < nPacks; i++ {
from := i * bulkSize
to := from + bulkSize
if to > nIdents {
to = nIdents
}
queryU := "insert ignore into uidentities(uuid,last_modified) values"
queryI := "insert ignore into identities(id,source,name,email,username,uuid,last_modified) values"
queryP := "insert ignore into profiles(uuid,name,email) values"
argsU := []interface{}{}
argsI := []interface{}{}
argsP := []interface{}{}
if ctx.Debug > 0 {
Printf("DB bulk upload: bulk adding idents pack #%d %d-%d (%d/%d)\n", i+1, from, to, to-from, nIdents)
}
uuids := map[int][]interface{}{}
for j := from; j < to; j++ {
ident := identsAry[j]
name := ident[0]
username := ident[1]
email := ident[2]
name, username = PostprocessNameUsername(name, username, email)
var (
pname *string
pemail *string
pusername *string
profname *string
)
if name != Nil {
pname = &name
profname = &name
}
if email != Nil {
pemail = &email
}
if username != Nil {
pusername = &username
}
if pname == nil && pemail == nil && pusername == nil {
continue
}
// if username matches a real email and there is no email set, assume email=username
if pemail == nil && pusername != nil {
valid, em := IsValidEmail(username, true, true)
if valid {
username = em
pemail = &username
email = username
}
}
// if name matches a real email and there is no email set, assume email=name
if pemail == nil && pname != nil {
valid, em := IsValidEmail(name, true, true)
if valid {
name = em
pemail = &name
email = name
}
}
// uuid(source, email, name, username)
uuid := UUIDAffs(ctx, source, email, name, username)
if uuid == "" {
Printf("error: uploadToDb(bulk): failed to generate uuid for (%s,%s,%s,%s), skipping this one\n", source, email, name, username)
continue
}
uuids[j] = []interface{}{uuid, source, pname, pemail, pusername, profname}
}
queryS := "select id, uuid from identities where id in("
argsS := []interface{}{}
for _, data := range uuids {
queryS += "?,"
argsS = append(argsS, data[0])
}
queryS = queryS[:len(queryS)-1] + ")"
var rows *sql.Rows
rows, err = QuerySQL(ctx, nil, queryS, argsS...)
if err != nil {
return
}
var (
id string
uuid string
)
id2uuid := map[string]string{}
for rows.Next() {
err = rows.Scan(&id, &uuid)
if err != nil {
return
}
id2uuid[id] = uuid
}
err = rows.Err()
if err != nil {
return
}
err = rows.Close()
if err != nil {
return
}
for j := from; j < to; j++ {
data, ok := uuids[j]
if !ok {
continue
}
uuid, _ := data[0].(string)
mergedUUID, ok := id2uuid[uuid]
if !ok {
mergedUUID = uuid
}
if ctx.Debug > 0 && uuid != mergedUUID {
Printf("mass: merged profile detected: %s -> %s\n", uuid, mergedUUID)
}
source := data[1]
pname := data[2]
pemail := data[3]
pusername := data[4]
profname := data[5]
queryU += fmt.Sprintf("(?,now()),")
queryI += fmt.Sprintf("(?,?,?,?,?,?,now()),")
queryP += fmt.Sprintf("(?,?,?),")
argsU = append(argsU, mergedUUID)
argsI = append(argsI, uuid, source, pname, pemail, pusername, mergedUUID)
argsP = append(argsP, mergedUUID, profname, pemail)
}
queryU = queryU[:len(queryU)-1]
queryI = queryI[:len(queryI)-1]
queryP = queryP[:len(queryP)-1] // + " on duplicate key update name=values(name),email=values(email),last_modified=now()"
_, err = ExecSQL(ctx, tx, queryU, argsU...)
if err != nil {
return
}
_, err = ExecSQL(ctx, tx, queryP, argsP...)
if err != nil {
return
}
_, err = ExecSQL(ctx, tx, queryI, argsI...)
if err != nil {
return
}
}
// Will not commit in dry-run mode, deferred function will rollback - so we can still test any errors
// but the final commit is replaced with rollback
if !ctx.DryRun {
err = tx.Commit()
if err != nil {
return
}
tx = nil
}
return
}
nDocs := len(*docs)
nOutDocs := len(*outDocs)
if ctx.Debug > 0 {
Printf("DB bulk upload: upload idents pack size %d/%d last %v\n", nDocs, nOutDocs, last)
}
for _, doc := range *docs {
*outDocs = append(*outDocs, doc)
nOutDocs = len(*outDocs)
if nOutDocs >= bulkSize {
if ctx.Debug > 0 {
Printf("DB bulk upload: upload idents pack size %d/%d reached, flushing\n", nOutDocs, bulkSize)
}
e = run()
if e != nil {
return
}
*outDocs = []interface{}{}
}
}
if last {
nOutDocs := len(*outDocs)
if nOutDocs > 0 {
e = run()
if e != nil {
return
}
*outDocs = []interface{}{}
}
}
*docs = []interface{}{}
if ctx.Debug > 0 {
nOutDocs = len(*outDocs)
Printf("DB bulk upload: upload idents %d items left (last %v)\n", nOutDocs, last)
}
return
}
// StandardItemsFunc - just get each doument's _source and append to output docs
// items is a current pack of input items
// docs is a pointer to where extracted items will be stored
func StandardItemsFunc(ctx *Ctx, ds DS, items []interface{}, docs *[]interface{}) (err error) {
if ctx.Debug > 0 {
Printf("standard items %d/%d func\n", len(items), len(*docs))
}
for _, item := range items {
doc, ok := item.(map[string]interface{})["_source"]
if !ok {
err = fmt.Errorf("Missing _source in item %+v", DumpKeys(item))
return
}
*docs = append(*docs, doc)
}
return
}
// ItemsIdentitiesFunc - extract identities from items
// items is a current pack of ES input items
// docs is a pointer to where extracted identities will be stored
// each identity is [3]string [name, username, email]
func ItemsIdentitiesFunc(ctx *Ctx, ds DS, thrN int, items []interface{}, docs *[]interface{}) (err error) {
if ctx.Debug > 0 {
Printf("items identities %d/%d func\n", len(items), len(*docs))
}
var (
mtx *sync.Mutex
ch chan error
)
if thrN > 1 {
mtx = &sync.Mutex{}
ch = make(chan error)
}
idents := make(map[[3]string]struct{})
for _, doc := range *docs {
idents[doc.([3]string)] = struct{}{}
}
procItem := func(c chan error, it interface{}) (e error) {
defer func() {
if c != nil {
c <- e
}
}()
doc, ok := it.(map[string]interface{})["_source"]
if !ok {
e = fmt.Errorf("Missing _source in item %+v", DumpKeys(it))
return
}
var identities map[[3]string]struct{}
identities, e = ds.GetItemIdentities(ctx, doc)
if e != nil {
e = fmt.Errorf("Cannot get identities from doc %+v", DumpKeys(doc))
return
}
if identities == nil {
return
}
if thrN > 1 {
mtx.Lock()
}
for identity := range identities {
idents[identity] = struct{}{}
}
if thrN > 1 {
mtx.Unlock()
}
return
}
updateDocs := func() {
*docs = []interface{}{}
for ident := range idents {
*docs = append(*docs, ident)
}
}
if thrN > 1 {
nThreads := 0
for _, item := range items {
go func(it interface{}) {
_ = procItem(ch, it)
}(item)
nThreads++
if nThreads == thrN {
err = <-ch
if err != nil {
return
}
nThreads--
}
}
for nThreads > 0 {
err = <-ch
nThreads--
if err != nil {
return
}
}
updateDocs()
return
}
for _, item := range items {
err = procItem(nil, item)
if err != nil {
return
}
}
updateDocs()
return
}
// ItemsRefreshIdentitiesFunc - refresh input items/re-enrich
// items is a current pack of ES rich items
// docs is a pointer to where updated rich items will be stored
func ItemsRefreshIdentitiesFunc(ctx *Ctx, ds DS, thrN int, richItems []interface{}, docs *[]interface{}) (err error) {
if ctx.Debug > 0 {
Printf("refresh identities %d/%d func\n", len(richItems), len(*docs))
}
var (
mtx *sync.Mutex
ch chan error
)
if thrN > 1 {
mtx = &sync.Mutex{}
ch = make(chan error)
}
roles, staticRoles := ds.AllRoles(ctx, nil)
procRich := func(c chan error, rItem interface{}) (e error) {
defer func() {
if c != nil {
c <- e
}
}()
var values map[string]interface{}
doc, ok := rItem.(map[string]interface{})["_source"]
if !ok {
e = fmt.Errorf("Missing _source in item %+v", DumpKeys(rItem))
return
}
rich, _ := doc.(map[string]interface{})
var rols []string
if staticRoles {
rols = roles
} else {
rols, _ = ds.AllRoles(ctx, rich)
}
var er error
values, er = AffsDataForRoles(ctx, ds, rich, rols)
if er != nil {
Printf("ItemsRefreshIdentitiesFunc/AffsDataForRoles: error: %v for %v %v\n", er, DumpKeys(rich), rols)
}
for prop, val := range values {
rich[prop] = val
}
rich["groups"] = ctx.Groups
if thrN > 1 {
mtx.Lock()
}
*docs = append(*docs, rich)
if thrN > 1 {
mtx.Unlock()
}
return
}
if thrN > 1 {
nThreads := 0
for _, richItem := range richItems {
go func(rItem interface{}) {
_ = procRich(ch, rItem)
}(richItem)
nThreads++
if nThreads == thrN {
err = <-ch
if err != nil {
return
}
nThreads--
}
}
for nThreads > 0 {
err = <-ch
nThreads--
if err != nil {
return
}
}
return
}
for _, richItem := range richItems {
err = procRich(nil, richItem)
if err != nil {
return
}
}
return
}
// UploadIdentities - upload identities to SH DB
// We assume here that docs maintained my iterator func contains a list of [3]string
// Each identity is [3]string [name, username, email]
func UploadIdentities(ctx *Ctx, ds DS) (err error) {
Printf("%s: uploading identities\n", ds.Name())
if ds.HasIdentities() {
err = ForEachESItem(ctx, ds, true, DBUploadIdentitiesFunc, ItemsIdentitiesFunc, nil, true)
Printf("%s: identities uploaded\n", ds.Name())
} else {
Printf("%s: identities not defined for the current datasource (no upload needed)\n", ds.Name())
}
return
}
// RefreshIdentities - refresh identities
// We iterate over rich index to refresh its affiliation data
func RefreshIdentities(ctx *Ctx, ds DS) (err error) {
Printf("%s: refreshing identities\n", ds.Name())
if ds.HasIdentities() {
err = ForEachESItem(ctx, ds, false, ESBulkUploadFunc, ItemsRefreshIdentitiesFunc, nil, true)
Printf("%s: identities refreshed\n", ds.Name())
} else {
Printf("%s: identities not defined for the current datasource (no refresh needed)\n", ds.Name())
}
return
}
// ForEachESItem - perform specific function for all raw/rich items
// ufunct: function to perform on input pack, receives input pack, pointer to an output pack
// and a flag signalling that this is the last (so it must flush output then)
// there can be no items in input pack in the last flush call
// uitems: function to extract items from input data: can just add documents, but can also maintain a pack of documents identities
// receives items and pointer to output items (which then become input for ufunct)
func ForEachESItem(
ctx *Ctx,
ds DS,
raw bool,
ufunct func(*Ctx, DS, int, *[]interface{}, *[]interface{}, bool) error,
uitems func(*Ctx, DS, int, []interface{}, *[]interface{}) error,
cacheFor *time.Duration,
mt bool,
) (err error) {
dateField := JSONEscape(ds.DateField(ctx))
originField := JSONEscape(ds.OriginField(ctx))
origin := JSONEscape(ds.Origin(ctx))
packSize := ctx.ESScrollSize
var (
scroll *string
dateFrom string
res interface{}
status int
)
headers := map[string]string{"Content-Type": "application/json"}
if ctx.DateFrom != nil {
dateFrom = ToESDate(*ctx.DateFrom)
}
attemptAt := time.Now()
total := 0
// Defer free scroll
defer func() {
if scroll == nil {
return
}
url := ctx.ESURL + "/_search/scroll"
payload := []byte(`{"scroll_id":"` + *scroll + `"}`)
_, _, _, _, err := Request(
ctx,
url,
Delete,
headers,
payload,
[]string{},
nil,
nil, // Error statuses
map[[2]int]struct{}{{200, 200}: {}}, // OK statuses
nil, // Cache statuses
false, // retry request
nil, // cacheExpire duration
false, // skip in dry-run mode
)
if err != nil {
Printf("Error releasing scroll %s: %+v, ignored\n", *scroll, err)
err = nil
}
}()
thrN := GetThreadsNum(ctx)
fThrN := thrN
if !mt {
fThrN = 1
}
Printf("Multithreaded: %v, using %d threads\n", MT, thrN)
nThreads := 0
var (