-
Notifications
You must be signed in to change notification settings - Fork 4
/
dsgerrit.go
2182 lines (2128 loc) · 68.6 KB
/
dsgerrit.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 (
"fmt"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
)
const (
// GerritBackendVersion - backend version
GerritBackendVersion = "0.1.1"
// GerritDefaultSSHKeyPath - default path to look for gerrit ssh private key
GerritDefaultSSHKeyPath = "$HOME/.ssh/id_rsa"
// GerritDefaultSSHPort - default gerrit ssh port
GerritDefaultSSHPort = 29418
// GerritDefaultMaxReviews = default max reviews when processing gerrit
GerritDefaultMaxReviews = 1000
// GerritCodeReviewApprovalType - code review approval type
GerritCodeReviewApprovalType = "Code-Review"
)
var (
// GerritRawMapping - Gerrit raw index mapping
GerritRawMapping = []byte(`{"dynamic":true,"properties":{"metadata__updated_on":{"type":"date"},"data":{"properties":{"commitMessage":{"type":"text","index":true},"comments":{"properties":{"message":{"type":"text","index":true}}},"subject":{"type":"text","index":true},"patchSets":{"properties":{"approvals":{"properties":{"description":{"type":"text","index":true}}},"comments":{"properties":{"message":{"type":"text","index":true}}}}}}}}}`)
// GerritRichMapping - Gerrit rich index mapping
GerritRichMapping = []byte(`{"properties":{"metadata__updated_on":{"type":"date"},"approval_description_analyzed":{"type":"text","index":true},"comment_message_analyzed":{"type":"text","index":true},"status":{"type":"keyword"},"summary_analyzed":{"type":"text","index":true},"timeopen":{"type":"double"}}}`)
// GerritCategories - categories defined for gerrit
GerritCategories = map[string]struct{}{Review: {}}
// GerritVersionRegexp - gerrit verion pattern
GerritVersionRegexp = regexp.MustCompile(`gerrit version (\d+)\.(\d+).*`)
// GerritDefaultSearchField - default search field
GerritDefaultSearchField = "item_id"
// GerritReviewRoles - roles to fetch affiliation data for review
GerritReviewRoles = []string{"owner"}
// GerritCommentRoles - roles to fetch affiliation data for comment
GerritCommentRoles = []string{"reviewer"}
// GerritPatchsetRoles - roles to fetch affiliation data for patchset
GerritPatchsetRoles = []string{"author", "uploader"}
// GerritApprovalRoles - roles to fetch affiliation data for approval
GerritApprovalRoles = []string{"by"}
)
// DSGerrit - DS implementation for stub - does nothing at all, just presents a skeleton code
type DSGerrit struct {
DS string
URL string // From DA_GERRIT_URL - gerrit repo path
SingleOrigin bool // From DA_GERRIT_SINGLE_ORIGIN - if you want to store only one gerrit endpoint in the index
User string // From DA_GERRIT_USER - gerrit user name
SSHKey string // From DA_GERRIT_SSH_KEY - must contain full SSH private key - has higher priority than key path
SSHKeyPath string // From DA_GERRIT_SSH_KEY_PATH - path to SSH private key, default GerritDefaultSSHKeyPath '~/.ssh/id_rsa'
SSHPort int // From DA_GERRIT_SSH_PORT, defaults to GerritDefaultSSHPort (29418)
MaxReviews int // From DA_GERRIT_MAX_REVIEWS, defaults to GerritDefaultMaxReviews (1000)
NoSSLVerify bool // From DA_GERRIT_NO_SSL_VERIFY
DisableHostKeyCheck bool // From DA_GERRIT_DISABLE_HOST_KEY_CHECK
// Non-config variables
SSHOpts string // SSH Options
SSHKeyTempPath string // if used SSHKey - temp file with this name was used to store key contents
GerritCmd []string // gerrit remote command used to fetch data
VersionMajor int // gerrit major version
VersionMinor int // gerrit minor version
}
// ParseArgs - parse gerrit specific environment variables
func (j *DSGerrit) ParseArgs(ctx *Ctx) (err error) {
j.DS = Gerrit
prefix := "DA_GERRIT_"
j.URL = os.Getenv(prefix + "URL")
j.User = os.Getenv(prefix + "USER")
j.SingleOrigin = StringToBool(os.Getenv(prefix + "SINGLE_ORIGIN"))
if os.Getenv(prefix+"SSH_KEY_PATH") != "" {
j.SSHKeyPath = os.Getenv(prefix + "SSH_KEY_PATH")
} else {
j.SSHKeyPath = GerritDefaultSSHKeyPath
}
j.SSHKey = os.Getenv(prefix + "SSH_KEY")
j.NoSSLVerify = StringToBool(os.Getenv(prefix + "NO_SSL_VERIFY"))
if j.NoSSLVerify {
NoSSLVerify()
}
j.DisableHostKeyCheck = StringToBool(os.Getenv(prefix + "DISABLE_HOST_KEY_CHECK"))
if ctx.Env("SSH_PORT") != "" {
sshPort, err := strconv.Atoi(ctx.Env("SSH_PORT"))
FatalOnError(err)
if sshPort > 0 {
j.SSHPort = sshPort
}
} else {
j.SSHPort = GerritDefaultSSHPort
}
if ctx.Env("MAX_REVIEWS") != "" {
maxReviews, err := strconv.Atoi(ctx.Env("MAX_REVIEWS"))
FatalOnError(err)
if maxReviews > 0 {
j.MaxReviews = maxReviews
}
} else {
j.MaxReviews = GerritDefaultMaxReviews
}
return
}
// Validate - is current DS configuration OK?
func (j *DSGerrit) Validate(ctx *Ctx) (err error) {
j.URL = strings.TrimSpace(j.URL)
if strings.HasSuffix(j.URL, "/") {
j.URL = j.URL[:len(j.URL)-1]
}
ary := strings.Split(j.URL, "://")
if len(ary) > 1 {
j.URL = ary[1]
}
j.SSHKeyPath = os.ExpandEnv(j.SSHKeyPath)
if j.SSHKeyPath == "" && j.SSHKey == "" {
err = fmt.Errorf("Either SSH key or SSH key path must be set")
return
}
if j.URL == "" || j.User == "" {
err = fmt.Errorf("URL and user must be set")
}
return
}
// Name - return data source name
func (j *DSGerrit) Name() string {
return j.DS
}
// Info - return DS configuration in a human readable form
func (j DSGerrit) Info() string {
return fmt.Sprintf("%+v", j)
}
// CustomFetchRaw - is this datasource using custom fetch raw implementation?
func (j *DSGerrit) CustomFetchRaw() bool {
return false
}
// FetchRaw - implement fetch raw data for stub datasource
func (j *DSGerrit) FetchRaw(ctx *Ctx) (err error) {
Printf("%s should use generic FetchRaw()\n", j.DS)
return
}
// CustomEnrich - is this datasource using custom enrich implementation?
func (j *DSGerrit) CustomEnrich() bool {
return false
}
// Enrich - implement enrich data for stub datasource
func (j *DSGerrit) Enrich(ctx *Ctx) (err error) {
Printf("%s should use generic Enrich()\n", j.DS)
return
}
// InitGerrit - initializes gerrit client
func (j *DSGerrit) InitGerrit(ctx *Ctx) (err error) {
if j.DisableHostKeyCheck {
j.SSHOpts += "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "
}
if j.SSHKey != "" {
var f *os.File
f, err = ioutil.TempFile("", "id_rsa")
if err != nil {
return
}
j.SSHKeyTempPath = f.Name()
_, err = f.Write([]byte(j.SSHKey))
if err != nil {
return
}
err = f.Close()
if err != nil {
return
}
err = os.Chmod(j.SSHKeyTempPath, 0600)
if err != nil {
return
}
j.SSHOpts += "-i " + j.SSHKeyTempPath + " "
} else {
if j.SSHKeyPath != "" {
j.SSHOpts += "-i " + j.SSHKeyPath + " "
}
}
if strings.HasSuffix(j.SSHOpts, " ") {
j.SSHOpts = j.SSHOpts[:len(j.SSHOpts)-1]
}
gerritCmd := fmt.Sprintf("ssh %s -p %d %s@%s gerrit", j.SSHOpts, j.SSHPort, j.User, j.URL)
ary := strings.Split(gerritCmd, " ")
for _, item := range ary {
if item == "" {
continue
}
j.GerritCmd = append(j.GerritCmd, item)
}
return
}
// GetGerritVersion - get gerrit version
func (j *DSGerrit) GetGerritVersion(ctx *Ctx) (err error) {
cmdLine := j.GerritCmd
cmdLine = append(cmdLine, "version")
var (
sout string
serr string
)
sout, serr, err = ExecCommand(ctx, cmdLine, "", nil)
if err != nil {
Printf("error executing %v: %v\n%s\n%s\n", cmdLine, err, sout, serr)
return
}
match := GerritVersionRegexp.FindAllStringSubmatch(sout, -1)
if len(match) < 1 {
err = fmt.Errorf("cannot parse gerrit version '%s'", sout)
return
}
j.VersionMajor, _ = strconv.Atoi(match[0][1])
j.VersionMinor, _ = strconv.Atoi(match[0][2])
if ctx.Debug > 0 {
Printf("Detected gerrit %d.%d\n", j.VersionMajor, j.VersionMinor)
}
return
}
// GetGerritReviews - get gerrit reviews
func (j *DSGerrit) GetGerritReviews(ctx *Ctx, after string, afterEpoch float64, startFrom int) (reviews []map[string]interface{}, newStartFrom int, err error) {
cmdLine := j.GerritCmd
// https://gerrit-review.googlesource.com/Documentation/user-search.html:
// ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i ./ssh-key.secret -p XYZ usr@gerrit-url gerrit query after:'1970-01-01 00:00:00' limit: 2 (status:open OR status:closed) --all-approvals --all-reviewers --comments --format=JSON
// For unknown reasons , gerrit is not returning data if number of seconds is not equal to 00 - so I'm updating query string to set seconds to ":00"
after = after[:len(after)-3] + ":00"
cmdLine = append(cmdLine, "query")
if ctx.ProjectFilter && ctx.Project != "" {
cmdLine = append(cmdLine, "project:", ctx.Project)
}
cmdLine = append(cmdLine, `after:"`+after+`"`, "limit:", strconv.Itoa(j.MaxReviews), "(status:open OR status:closed)", "--all-approvals", "--all-reviewers", "--comments", "--format=JSON")
// 2006-01-02[ 15:04:05[.890][ -0700]]
if startFrom > 0 {
cmdLine = append(cmdLine, "--start="+strconv.Itoa(startFrom))
}
var (
sout string
serr string
)
if ctx.Debug > 0 {
Printf("getting reviews via: %v\n", cmdLine)
}
sout, serr, err = ExecCommand(ctx, cmdLine, "", nil)
// sout, serr, err = `{"project":"sdc/sdc-be-common","branch":"master","id":"Ieacedaa9c5204c2eab6ee96870f9b7726e06fc43","number":121462,"subject":"Fix tests not running after junit5 upgrade","owner":{"name":"Andr� Schmid","email":"[email protected]","username":"andre.schmid"},"url":"https://gerrit.onap.org/r/c/sdc/sdc-be-common/+/121462","commitMessage":"Fix tests not running after junit5 upgrade\n\nThere was a conflict with the junit version in spring boot and\nthe one in the project. With that, maven surefire plugin was not\nfinding the tests.\nThe org.onap.sdc.security.logging.wrappers.LoggerTest was also broken\nwith a conflict with mockito and an undesirable powermock library from\norg.onap.portal.sdk:epsdk-fw artifact. There was also an incorrect\nassertion in the test.\n\nIssue-ID: SDC-3604\nSigned-off-by: André Schmid \[email protected]\u003e\nChange-Id: Ieacedaa9c5204c2eab6ee96870f9b7726e06fc43\n","createdOn":1621524278,"lastUpdated":1621527597,"open":false,"status":"MERGED","comments":[{"timestamp":1621524278,"reviewer":{"name":"Andr� Schmid","email":"[email protected]","username":"andre.schmid"},"message":"Uploaded patch set 1."},{"timestamp":1621524535,"reviewer":{"name":"ONAP Jobbuilder","email":"[email protected]","username":"onap-jobbuilder"},"message":"Patch Set 1:\n\nBuild Started https://jenkins.onap.org/job/sdc-sdc-be-common-master-verify-java/120/"},{"timestamp":1621524687,"reviewer":{"name":"ONAP Jobbuilder","email":"[email protected]","username":"onap-jobbuilder"},"message":"Patch Set 1: Verified+1\n\nBuild Successful \n\nhttps://jenkins.onap.org/job/sdc-sdc-be-common-master-verify-java/120/ : SUCCESS\n\nLogs: https://logs.onap.org/production/vex-yul-ecomp-jenkins-1/sdc-sdc-be-common-master-verify-java/120"},{"timestamp":1621526917,"reviewer":{"name":"Vasyl Razinkov","email":"[email protected]","username":"vasraz"},"message":"Patch Set 1: Code-Review+2"},{"timestamp":1621526921,"reviewer":{"name":"Vasyl Razinkov","email":"[email protected]","username":"vasraz"},"message":"Change has been successfully merged by Vasyl Razinkov"},{"timestamp":1621526932,"reviewer":{"name":"Vasyl Razinkov","email":"[email protected]","username":"vasraz"},"message":"Patch Set 1:\n\nrun-sonar"},{"timestamp":1621527435,"reviewer":{"name":"ONAP Jobbuilder","email":"[email protected]","username":"onap-jobbuilder"},"message":"Patch Set 1:\n\nBuild Successful \n\nhttps://jenkins.onap.org/job/sdc-sdc-be-common-master-merge-java/59/ : SUCCESS\n\nLogs: https://logs.onap.org/production/vex-yul-ecomp-jenkins-1/sdc-sdc-be-common-master-merge-java/59"},{"timestamp":1621527597,"reviewer":{"name":"ONAP Jobbuilder","email":"[email protected]","username":"onap-jobbuilder"},"message":"Patch Set 1:\n\nBuild Successful \n\nhttps://jenkins.onap.org/job/sdc-sdc-be-common-sonar/724/ : SUCCESS (skipped)\n\nLogs: https://logs.onap.org/production/vex-yul-ecomp-jenkins-1/sdc-sdc-be-common-sonar/724"}],"patchSets":[{"number":1,"revision":"7f2e3520839a322f2c659bbf2501720a84bf0635","parents":["d9390c23f8568c4df7797eb321161cef725221b0"],"ref":"refs/changes/62/121462/1","uploader":{"name":"Andr� Schmid","email":"[email protected]","username":"andre.schmid"},"createdOn":1621524278,"author":{"name":"Andr� Schmid","email":"[email protected]","username":"andre.schmid"},"kind":"REWORK","approvals":[{"type":"Verified","description":"Verified","value":"1","grantedOn":1621524687,"by":{"name":"ONAP Jobbuilder","email":"[email protected]","username":"onap-jobbuilder"}},{"type":"Code-Review","description":"Code-Review","value":"2","grantedOn":1621526917,"by":{"name":"Vasyl Razinkov","email":"[email protected]","username":"vasraz"}},{"type":"SUBM","value":"1","grantedOn":1621526921,"by":{"name":"Vasyl Razinkov","email":"[email protected]","username":"vasraz"}}],"sizeInsertions":45,"sizeDeletions":22}],"allReviewers":[{"name":"Vasyl Razinkov","email":"[email protected]","username":"vasraz"},{"name":"ONAP Jobbuilder","email":"[email protected]","username":"onap-jobbuilder"},{"name":"Anderson Ribeiro","email":"[email protected]","username":"aribeiro"},{"name":"Julien Bertozzi","email":"[email protected]","username":"JulienBe"},{"name":"Ojas Dubey","email":"[email protected]","username":"ojasdubey"},{"name":"Xue Gao","email":"[email protected]","username":"xuegao"},{"name":"tali orenbach","email":"[email protected]","username":"talio"},{"name":"Christophe Closset","email":"[email protected]","username":"ChrisC"},{"name":"Ilana Paktor","email":"[email protected]","username":"ilanap"},{"name":"Michael Morris","email":"[email protected]","username":"MichaelMorris"},{"name":"S�bastien Determe","email":"[email protected]","username":"sebdet"}]}`, "", nil
if err != nil {
Printf("error executing %v: %v\n%s\n%s\n", cmdLine, err, sout, serr)
return
}
data := strings.Replace("["+strings.Replace(sout, "\n", ",", -1)+"]", ",]", "]", -1)
var items []interface{}
err = jsoniter.Unmarshal([]byte(data), &items)
if err != nil {
return
}
for i, iItem := range items {
item, _ := iItem.(map[string]interface{})
//Printf("#%d) %v\n", i, DumpKeys(item))
iMoreChanges, ok := item["moreChanges"]
if ok {
moreChanges, ok := iMoreChanges.(bool)
if ok {
if moreChanges {
newStartFrom = startFrom + i
if ctx.Debug > 0 {
Printf("#%d) moreChanges: %v, newStartFrom: %d\n", i, moreChanges, newStartFrom)
}
}
} else {
Printf("cannot read boolean value from %v\n", iMoreChanges)
}
return
}
_, ok = item["project"]
if !ok {
if ctx.Debug > 0 {
Printf("#%d) project not found: %+v", i, item)
}
continue
}
iLastUpdated, ok := item["lastUpdated"]
if ok {
lastUpdated, ok := iLastUpdated.(float64)
if ok {
if lastUpdated < afterEpoch {
if ctx.Debug > 1 {
Printf("#%d) lastUpdated: %v < afterEpoch: %v, skipping\n", i, lastUpdated, afterEpoch)
}
continue
}
} else {
Printf("cannot read float value from %v\n", iLastUpdated)
}
} else {
Printf("cannot read lastUpdated from %v\n", item)
}
reviews = append(reviews, item)
}
return
}
// FetchItems - implement enrich data for stub datasource
func (j *DSGerrit) FetchItems(ctx *Ctx) (err error) {
err = j.InitGerrit(ctx)
if err != nil {
return
}
if j.SSHKeyTempPath != "" {
defer func() {
Printf("removing temporary SSH key %s\n", j.SSHKeyTempPath)
_ = os.Remove(j.SSHKeyTempPath)
}()
}
// We don't have ancient gerrit versions like < 2.9 - this check is only for debugging
if ctx.Debug > 1 {
err = j.GetGerritVersion(ctx)
if err != nil {
return
}
}
var (
startFrom int
after string
afterEpoch float64
)
if ctx.DateFrom != nil {
after = ToYMDHMSDate(*ctx.DateFrom)
afterEpoch = float64(ctx.DateFrom.Unix())
} else {
after = "1970-01-01 00:00:00"
afterEpoch = 0.0
}
var (
ch chan error
allReviews []interface{}
allReviewsMtx *sync.Mutex
escha []chan error
eschaMtx *sync.Mutex
)
thrN := GetThreadsNum(ctx)
if thrN > 1 {
ch = make(chan error)
allReviewsMtx = &sync.Mutex{}
eschaMtx = &sync.Mutex{}
}
nThreads := 0
processReview := func(c chan error, review map[string]interface{}) (wch chan error, e error) {
defer func() {
if c != nil {
c <- e
}
}()
esItem := j.AddMetadata(ctx, review)
if ctx.Project != "" {
review["project"] = ctx.Project
}
esItem["data"] = review
if allReviewsMtx != nil {
allReviewsMtx.Lock()
}
allReviews = append(allReviews, esItem)
nReviews := len(allReviews)
if nReviews >= ctx.ESBulkSize {
sendToElastic := func(c chan error) (ee error) {
defer func() {
if c != nil {
c <- ee
}
}()
ee = SendToElastic(ctx, j, true, UUID, allReviews)
if ee != nil {
Printf("error %v sending %d reviews to ElasticSearch\n", ee, len(allReviews))
}
allReviews = []interface{}{}
if allReviewsMtx != nil {
allReviewsMtx.Unlock()
}
return
}
if thrN > 1 {
wch = make(chan error)
go func() {
_ = sendToElastic(wch)
}()
} else {
e = sendToElastic(nil)
if e != nil {
return
}
}
} else {
if allReviewsMtx != nil {
allReviewsMtx.Unlock()
}
}
return
}
if thrN > 1 {
for {
var reviews []map[string]interface{}
reviews, startFrom, err = j.GetGerritReviews(ctx, after, afterEpoch, startFrom)
if err != nil {
return
}
for _, review := range reviews {
go func(review map[string]interface{}) {
var (
e error
esch chan error
)
esch, e = processReview(ch, review)
if e != nil {
Printf("process error: %v\n", e)
return
}
if esch != nil {
if eschaMtx != nil {
eschaMtx.Lock()
}
escha = append(escha, esch)
if eschaMtx != nil {
eschaMtx.Unlock()
}
}
}(review)
nThreads++
if nThreads == thrN {
err = <-ch
if err != nil {
return
}
nThreads--
}
}
if startFrom == 0 {
break
}
}
for nThreads > 0 {
err = <-ch
nThreads--
if err != nil {
return
}
}
} else {
for {
var reviews []map[string]interface{}
reviews, startFrom, err = j.GetGerritReviews(ctx, after, afterEpoch, startFrom)
if err != nil {
return
}
for _, review := range reviews {
_, err = processReview(nil, review)
if err != nil {
return
}
}
if startFrom == 0 {
break
}
}
}
if eschaMtx != nil {
eschaMtx.Lock()
}
for _, esch := range escha {
err = <-esch
if err != nil {
if eschaMtx != nil {
eschaMtx.Unlock()
}
return
}
}
if eschaMtx != nil {
eschaMtx.Unlock()
}
nReviews := len(allReviews)
if ctx.Debug > 0 {
Printf("%d remaining reviews to send to ES\n", nReviews)
}
if nReviews > 0 {
err = SendToElastic(ctx, j, true, UUID, allReviews)
if err != nil {
Printf("Error %v sending %d reviews to ES\n", err, len(allReviews))
}
}
return
}
// SupportDateFrom - does DS support resuming from date?
func (j *DSGerrit) SupportDateFrom() bool {
// A bit dangerous, because if any run failed then one review can set max update to some recent date
// while other reviews can be left at a lower date
return true
}
// SupportOffsetFrom - does DS support resuming from offset?
func (j *DSGerrit) SupportOffsetFrom() bool {
return false
}
// DateField - return date field used to detect where to restart from
func (j *DSGerrit) DateField(*Ctx) string {
return DefaultDateField
}
// RichIDField - return rich ID field name
func (j *DSGerrit) RichIDField(*Ctx) string {
return DefaultIDField
}
// RichAuthorField - return rich ID field name
func (j *DSGerrit) RichAuthorField(*Ctx) string {
return DefaultAuthorField
}
// OffsetField - return offset field used to detect where to restart from
func (j *DSGerrit) OffsetField(*Ctx) string {
return DefaultOffsetField
}
// OriginField - return origin field used to detect where to restart from
func (j *DSGerrit) OriginField(ctx *Ctx) string {
if ctx.Tag != "" {
return DefaultTagField
}
return DefaultOriginField
}
// Categories - return a set of configured categories
func (j *DSGerrit) Categories() map[string]struct{} {
return GerritCategories
}
// ResumeNeedsOrigin - is origin field needed when resuming
// Origin should be needed when multiple configurations save to the same index
func (j *DSGerrit) ResumeNeedsOrigin(ctx *Ctx, raw bool) bool {
return !j.SingleOrigin
}
// ResumeNeedsCategory - is category field needed when resuming
// Category should be needed when multiple types of categories save to the same index
// or there are multiple types of documents within the same category
func (j *DSGerrit) ResumeNeedsCategory(ctx *Ctx, raw bool) bool {
return false
}
// Origin - return current origin
func (j *DSGerrit) Origin(ctx *Ctx) string {
return j.URL
}
// ItemID - return unique identifier for an item
func (j *DSGerrit) ItemID(item interface{}) string {
id, ok := item.(map[string]interface{})["number"].(float64)
if !ok {
Fatalf("%s: ItemID() - cannot extract number from %+v", j.DS, DumpKeys(item))
}
return fmt.Sprintf("%.0f", id)
}
// AddMetadata - add metadata to the item
func (j *DSGerrit) AddMetadata(ctx *Ctx, item interface{}) (mItem map[string]interface{}) {
mItem = make(map[string]interface{})
origin := j.URL
tag := ctx.Tag
if tag == "" {
tag = origin
}
itemID := j.ItemID(item)
updatedOn := j.ItemUpdatedOn(item)
uuid := UUIDNonEmpty(ctx, origin, itemID)
timestamp := time.Now()
mItem["backend_name"] = j.DS
mItem["backend_version"] = GerritBackendVersion
mItem["timestamp"] = fmt.Sprintf("%.06f", float64(timestamp.UnixNano())/1.0e9)
mItem[UUID] = uuid
mItem[DefaultOriginField] = origin
mItem[DefaultTagField] = tag
mItem[DefaultOffsetField] = float64(updatedOn.Unix())
mItem["category"] = j.ItemCategory(item)
mItem["search_fields"] = make(map[string]interface{})
project, _ := Dig(item, []string{"project"}, true, false)
hash, _ := Dig(item, []string{"id"}, true, false)
FatalOnError(DeepSet(mItem, []string{"search_fields", GerritDefaultSearchField}, itemID, false))
FatalOnError(DeepSet(mItem, []string{"search_fields", "project_name"}, project, false))
FatalOnError(DeepSet(mItem, []string{"search_fields", "review_hash"}, hash, false))
mItem[DefaultDateField] = ToESDate(updatedOn)
mItem[DefaultTimestampField] = ToESDate(timestamp)
mItem[ProjectSlug] = ctx.ProjectSlug
return
}
// ItemUpdatedOn - return updated on date for an item
func (j *DSGerrit) ItemUpdatedOn(item interface{}) time.Time {
epoch, ok := item.(map[string]interface{})["lastUpdated"].(float64)
if !ok {
Fatalf("%s: ItemUpdatedOn() - cannot extract lastUpdated from %+v", j.DS, DumpKeys(item))
}
return time.Unix(int64(epoch), 0)
}
// ItemCategory - return unique identifier for an item
func (j *DSGerrit) ItemCategory(item interface{}) string {
return Review
}
// ElasticRawMapping - Raw index mapping definition
func (j *DSGerrit) ElasticRawMapping() []byte {
return GerritRawMapping
}
// ElasticRichMapping - Rich index mapping definition
func (j *DSGerrit) ElasticRichMapping() []byte {
return GerritRichMapping
}
// IdentityForObject - construct identity from a given object
func (j *DSGerrit) IdentityForObject(ctx *Ctx, obj map[string]interface{}) (identity [3]string) {
if ctx.Debug > 2 {
defer func() {
Printf("%+v -> %+v\n", obj, identity)
}()
}
item := obj
data, ok := Dig(item, []string{"data"}, false, true)
if ok {
mp, ok := data.(map[string]interface{})
if ok {
if ctx.Debug > 2 {
Printf("digged in data: %+v\n", obj)
}
item = mp
}
}
for i, prop := range []string{"name", "username", "email"} {
iVal, ok := Dig(item, []string{prop}, false, true)
if ok {
val, ok := iVal.(string)
if ok {
identity[i] = val
}
} else {
identity[i] = Nil
}
}
return
}
// GetItemIdentities return list of item's identities, each one is [3]string
// (name, username, email) tripples, special value Nil "none" means null
// we use string and not *string which allows nil to allow usage as a map key
func (j *DSGerrit) GetItemIdentities(ctx *Ctx, doc interface{}) (identities map[[3]string]struct{}, err error) {
if ctx.Debug > 2 {
defer func() {
Printf("%+v -> %+v\n", DumpPreview(doc, 100), identities)
}()
}
init := false
item, _ := Dig(doc, []string{"data"}, true, false)
iUser, ok := Dig(item, []string{"owner"}, false, true)
if ok {
user, ok := iUser.(map[string]interface{})
if ok {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[j.IdentityForObject(ctx, user)] = struct{}{}
}
}
iPatchSets, ok := Dig(item, []string{"patchSets"}, false, true)
if ok {
patchSets, ok := iPatchSets.([]interface{})
if ok {
for _, iPatch := range patchSets {
patch, ok := iPatch.(map[string]interface{})
if !ok {
continue
}
iUploader, ok := Dig(patch, []string{"uploader"}, false, true)
if ok {
uploader, ok := iUploader.(map[string]interface{})
if ok {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[j.IdentityForObject(ctx, uploader)] = struct{}{}
}
}
iAuthor, ok := Dig(patch, []string{"author"}, false, true)
if ok {
author, ok := iAuthor.(map[string]interface{})
if ok {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[j.IdentityForObject(ctx, author)] = struct{}{}
}
}
iApprovals, ok := Dig(patch, []string{"approvals"}, false, true)
if ok {
approvals, ok := iApprovals.([]interface{})
if ok {
for _, iApproval := range approvals {
approval, ok := iApproval.(map[string]interface{})
if !ok {
continue
}
iBy, ok := Dig(approval, []string{"by"}, false, true)
if ok {
by, ok := iBy.(map[string]interface{})
if ok {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[j.IdentityForObject(ctx, by)] = struct{}{}
}
}
}
}
}
}
}
}
iComments, ok := Dig(item, []string{"comments"}, false, true)
if ok {
comments, ok := iComments.([]interface{})
if ok {
for _, iComment := range comments {
comment, ok := iComment.(map[string]interface{})
if !ok {
continue
}
iReviewer, ok := Dig(comment, []string{"reviewer"}, false, true)
if ok {
reviewer, ok := iReviewer.(map[string]interface{})
if ok {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[j.IdentityForObject(ctx, reviewer)] = struct{}{}
}
}
}
}
}
return
}
// GerritEnrichItemsFunc - iterate items and enrich them
// items is a current pack of input items
// docs is a pointer to where extracted identities will be stored
func GerritEnrichItemsFunc(ctx *Ctx, ds DS, thrN int, items []interface{}, docs *[]interface{}) (err error) {
if ctx.Debug > 0 {
Printf("gerrit enrich items %d/%d func\n", len(items), len(*docs))
}
var (
mtx *sync.RWMutex
ch chan error
)
if thrN > 1 {
mtx = &sync.RWMutex{}
ch = make(chan error)
}
dbConfigured := ctx.AffsDBConfigured()
gerrit, _ := ds.(*DSGerrit)
getRichItems := func(doc map[string]interface{}) (richItems []interface{}, e error) {
/*
defer func() {
m := make(map[string]struct{})
if len(richItems) < 10 {
return
}
for _, iRich := range richItems {
rich, ok := iRich.(map[string]interface{})
if !ok {
continue
}
it, ok := rich["type"]
if !ok {
continue
}
t, ok := it.(string)
if !ok {
continue
}
m[t] = struct{}{}
}
if len(m) < 4 {
return
}
s := "\n"
for i, rich := range richItems {
s += fmt.Sprintf("%d) %+v\n", i+1, PreviewOnly(rich, 128))
}
Printf("%s\n", s)
}()
*/
var rich map[string]interface{}
rich, e = ds.EnrichItem(ctx, doc, "", dbConfigured, nil)
if e != nil {
return
}
_, authorIDOK := Dig(rich, []string{"author_id"}, false, true)
if authorIDOK || !ctx.CheckAuthorID {
richItems = append(richItems, rich)
}
data, _ := Dig(doc, []string{"data"}, true, false)
iPatchSets, ok := Dig(data, []string{"patchSets"}, false, true)
if ok {
patchSets, ok := iPatchSets.([]interface{})
if ok {
var patches []map[string]interface{}
for _, iPatch := range patchSets {
patch, ok := iPatch.(map[string]interface{})
if !ok {
continue
}
patches = append(patches, patch)
}
if len(patches) > 0 {
var riches []interface{}
riches, e = gerrit.EnrichPatchsets(ctx, rich, patches, dbConfigured)
if e != nil {
return
}
for _, rich := range riches {
_, authorIDOK := Dig(rich, []string{"author_id"}, false, true)
if !authorIDOK && ctx.CheckAuthorID {
continue
}
richItems = append(richItems, rich)
}
//richItems = append(richItems, riches...)
}
}
}
iComments, ok := Dig(data, []string{"comments"}, false, true)
if ok {
comments, ok := iComments.([]interface{})
if ok {
var comms []map[string]interface{}
for _, iComment := range comments {
comment, ok := iComment.(map[string]interface{})
if !ok {
continue
}
comms = append(comms, comment)
}
if len(comms) > 0 {
var riches []interface{}
riches, e = gerrit.EnrichComments(ctx, rich, comms, dbConfigured)
if e != nil {
return
}
for _, rich := range riches {
_, authorIDOK := Dig(rich, []string{"author_id"}, false, true)
if !authorIDOK && ctx.CheckAuthorID {
continue
}
richItems = append(richItems, rich)
}
//richItems = append(richItems, riches...)
}
}
}
return
}
nThreads := 0
procItem := func(c chan error, idx int) (e error) {
if thrN > 1 {
mtx.RLock()
}
item := items[idx]
if thrN > 1 {
mtx.RUnlock()
}
defer func() {
if c != nil {
c <- e
}
}()
src, ok := item.(map[string]interface{})["_source"]
if !ok {
e = fmt.Errorf("Missing _source in item %+v", DumpKeys(item))
return
}
doc, ok := src.(map[string]interface{})
if !ok {
e = fmt.Errorf("Failed to parse document %+v", doc)
return
}
richItems, e := getRichItems(doc)
if e != nil {
return
}
for _, rich := range richItems {
e = EnrichItem(ctx, ds, rich.(map[string]interface{}))
if e != nil {
return
}
}
if thrN > 1 {
mtx.Lock()
}
*docs = append(*docs, richItems...)
if thrN > 1 {
mtx.Unlock()
}
return
}
if thrN > 1 {
for i := range items {
go func(i int) {
_ = procItem(ch, i)
}(i)
nThreads++
if nThreads == thrN {
err = <-ch
if err != nil {
return
}
nThreads--
}
}
for nThreads > 0 {
err = <-ch
nThreads--
if err != nil {
return
}
}
return
}
for i := range items {
err = procItem(nil, i)
if err != nil {
return
}
}
return
}
// EnrichItems - perform the enrichment
func (j *DSGerrit) EnrichItems(ctx *Ctx) (err error) {
Printf("enriching items\n")
err = ForEachESItem(ctx, j, true, ESBulkUploadFunc, GerritEnrichItemsFunc, nil, true)
return
}
// ConvertDates - convert floating point dates to datetimes
func (j *DSGerrit) ConvertDates(ctx *Ctx, review map[string]interface{}) {
for _, field := range []string{"timestamp", "createdOn", "lastUpdated"} {
idt, ok := Dig(review, []string{field}, false, true)
if !ok {
continue
}
fdt, ok := idt.(float64)
if !ok {
continue
}
review[field] = time.Unix(int64(fdt), 0)
// Printf("converted %s: %v -> %v\n", field, idt, review[field])
}
iPatchSets, ok := Dig(review, []string{"patchSets"}, false, true)
if ok {
patchSets, ok := iPatchSets.([]interface{})
if ok {
for _, iPatch := range patchSets {
patch, ok := iPatch.(map[string]interface{})
if !ok {
continue
}
field := "createdOn"
idt, ok := Dig(patch, []string{field}, false, true)
if ok {
fdt, ok := idt.(float64)
if ok {
patch[field] = time.Unix(int64(fdt), 0)
// Printf("converted patch %s: %v -> %v\n", field, idt, patch[field])
}
}