-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreport.go
3501 lines (3437 loc) · 95.5 KB
/
report.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 main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/jmoiron/sqlx"
jsoniter "github.com/json-iterator/go"
_ "github.com/go-sql-driver/mysql"
)
const (
// cCreatedAtColumn = "metadata__enriched_on"
// cCreatedAtColumn = "metadata__timestamp"
cCreatedAtColumn = "metadata__updated_on"
cOffsetMinutes = -60
)
var (
gReport string
gESURL string
gDB *sqlx.DB
gOrg string
gFrom string
gTo string
gIndexFilter string
gDbg bool
gDatasource map[string]struct{}
gSubReport map[string]struct{}
gAll map[string]int
gDt time.Time
gNamePrefix string
gMaxThreads int
gProgress bool
gFiltered bool
gIncremental bool
gESLogURL string
gSyncDates map[string]time.Time
gSyncDatesMtx *sync.Mutex
)
var gDtMtx = &sync.Mutex{}
// contributor name, email address, project slug and affiliation date range
type contribReportItem struct {
uuid string
name string
email string
project string
subProject string
n int
from time.Time
to time.Time
root string
commits int
locAdded int
locDeleted int
prAct int
issueAct int
}
// contribReport - full report structure
type contribReport struct {
items []contribReportItem
summary map[string]contribReportItem
}
// LOC stats report item (only git)
// subrep
type datalakeLOCReportItem struct {
docID string
identityID string
dataSource string
projectSlug string
sfSlug string
createdAt time.Time
locAdded int
locDeleted int
title string
url string
filtered bool
}
// Docs stats report item (only confluence)
// subrep
type datalakeDocReportItem struct {
docID string
identityID string
dataSource string
projectSlug string
sfSlug string
createdAt time.Time
actionType string // page, new_page, comment, attachment
title string
url string
filtered bool
}
// PRs stats report item (github pull_request & gerrit)
// subrep
type datalakePRReportItem struct {
docID string
identityID string
dataSource string
projectSlug string
sfSlug string
createdAt time.Time
actionType string // all possible doc types from github-issue (PRs only) and gerrit, also detecting approvals/rejections/merges
title string
url string
filtered bool
}
// Issues stats report item (github issue, Jira issue, Bugzilla(rest) issue)
// subrep
type datalakeIssueReportItem struct {
docID string
identityID string
dataSource string
projectSlug string
sfSlug string
createdAt time.Time
actionType string // all possible doc types from github-issue (Issue only), Jira & Bugzilla(rest)
title string
url string
filtered bool
}
// datalakeReport - full report structure
// subrep
type datalakeReport struct {
locItems []datalakeLOCReportItem
docItems []datalakeDocReportItem
prItems []datalakePRReportItem
issueItems []datalakeIssueReportItem
}
type resultTypeError struct {
Type string `json:"type"`
Reason string `json:"reason"`
}
type resultType struct {
Cursor string `json:"cursor"`
Rows [][]interface{} `json:"rows"`
Error resultTypeError `json:"error"`
}
func fatalError(err error) {
if err == nil {
return
}
fmt.Printf("error: %v\n", err)
panic("")
}
func fatal(str string) {
fmt.Printf("error: %s\n", str)
panic("")
}
func fatalf(f string, a ...interface{}) {
fatalError(fmt.Errorf(f, a...))
}
// return values
// 1 - report this error
// 0 - this error is allowed
// -1 - don't report this error, but retry due to missing 'project_slug' column
func reportThisError(err resultTypeError) int {
errMsg := fmt.Sprintf("%+v", err)
// We attempt to get all possible data types using project root, if some data type is not present then this is just fine.
if strings.Contains(errMsg, "Unknown index ") {
return 0
}
// We attempt to get PRs data on github-issue indices, some projects have only issues enabled and not PRs - so this is fine too.
if strings.Contains(errMsg, "Unknown column ") && strings.Contains(errMsg, "merged_by_data_id") {
return 0
}
// don't report this error, but retry due to missing 'project_slug' column
if strings.Contains(errMsg, "Unknown column ") && strings.Contains(errMsg, "project_slug") {
return -1
}
return 1
}
func reportThisErrorOrg(err resultTypeError) bool {
errMsg := fmt.Sprintf("%+v", err)
// We attempt to get all possible data types using project root, if some data type is not present then this is just fine.
if strings.Contains(errMsg, "Unknown index ") {
return false
}
return true
}
func getIndices(res map[string]interface{}, aliases bool) (indices []string) {
ary, _ := res["x"].([]interface{})
for _, i := range ary {
item, _ := i.(map[string]interface{})
idx, _ := item["index"].(string)
if !strings.HasPrefix(idx, "sds-") {
continue
}
// if strings.HasSuffix(idx, "-raw") || strings.HasSuffix(idx, "-for-merge") || strings.HasSuffix(idx, "-cache") || strings.HasSuffix(idx, "-converted") || strings.HasSuffix(idx, "-temp") || strings.HasSuffix(idx, "-last-action-date-cache") {
if strings.HasSuffix(idx, "-raw") || strings.HasSuffix(idx, "-cache") || strings.HasSuffix(idx, "-converted") || strings.HasSuffix(idx, "-temp") || strings.HasSuffix(idx, "-last-action-date-cache") {
continue
}
if gIndexFilter != "" && !strings.Contains(idx, gIndexFilter) {
continue
}
// to limit data processing while implementing
// yyy
/*
if !strings.Contains(idx, "o-ran") {
continue
}
*/
if !aliases {
sCnt, _ := item["docs.count"].(string)
cnt, _ := strconv.Atoi(sCnt)
if gDbg {
fmt.Printf("%s-> %d\n", idx, cnt)
}
if cnt == 0 {
gAll[idx] = 0
if gDbg {
fmt.Printf("skipping an empty index %s\n", idx)
}
continue
}
indices = append(indices, idx)
gAll[idx] = cnt
continue
}
cnt, ok := gAll[idx]
if ok && cnt == 0 {
if gDbg {
fmt.Printf("skipping an empty index from alias %s\n", idx)
}
continue
}
if !ok {
gAll[idx] = -1
}
indices = append(indices, idx)
}
sort.Strings(indices)
if gDbg {
if aliases {
fmt.Printf("indices from aliases: %v\n", indices)
} else {
fmt.Printf("indices: %v\n", indices)
}
}
return
}
func getRoots(indices, aliases []string) (roots, dsa []string) {
fmt.Printf("%d indices, %d aliases\n", len(indices), len(aliases))
dss := make(map[string]struct{})
all := make(map[string]struct{})
var reported map[string]struct{}
if gDbg {
reported = make(map[string]struct{})
}
for _, idx := range indices {
if strings.HasSuffix(idx, "-for-merge") {
idx = idx[:len(idx)-10]
}
ary := strings.Split(idx, "-")
lAry := len(ary)
ds := ary[lAry-1]
root := strings.Join(ary[1:lAry-1], "-")
if strings.HasSuffix(root, "-github") {
root = root[:len(root)-7]
ds = "github-" + ds
}
if root == "" {
continue
}
if gDatasource != nil {
_, ok := gDatasource[ds]
if !ok {
if gDbg {
_, rep := reported[ds]
if !rep {
fmt.Printf("data source '%s' not on the data source list, skipping\n", ds)
reported[ds] = struct{}{}
}
}
continue
}
if gDbg {
_, rep := reported[ds]
if !rep {
fmt.Printf("data source '%s' included\n", ds)
reported[ds] = struct{}{}
}
}
}
dss[ds] = struct{}{}
all[root] = struct{}{}
}
for _, idx := range aliases {
if strings.HasSuffix(idx, "-for-merge") {
idx = idx[:len(idx)-10]
}
ary := strings.Split(idx, "-")
lAry := len(ary)
ds := ary[lAry-1]
root := strings.Join(ary[1:lAry-1], "-")
if strings.HasSuffix(root, "-github") {
root = root[:len(root)-7]
ds = "github-" + ds
}
if root == "" {
continue
}
if gDatasource != nil {
_, ok := gDatasource[ds]
if !ok {
if gDbg {
_, rep := reported[ds]
if !rep {
fmt.Printf("data source '%s' not on the data source list, skipping\n", ds)
reported[ds] = struct{}{}
}
}
continue
}
if gDbg {
_, rep := reported[ds]
if !rep {
fmt.Printf("data source '%s' included\n", ds)
reported[ds] = struct{}{}
}
}
}
dss[ds] = struct{}{}
all[root] = struct{}{}
}
fmt.Printf("%d data source types\n", len(dss))
for root := range all {
roots = append(roots, root)
}
for ds := range dss {
dsa = append(dsa, ds)
}
sort.Strings(dsa)
if gDbg {
fmt.Printf("data source types: %v\n", dsa)
}
sort.Strings(roots)
fmt.Printf("%d projects detected\n", len(roots))
if gDbg {
fmt.Printf("projects: %v\n", roots)
}
return
}
func getSlugRoots() (slugRoots, dataSourceTypes []string) {
method := "GET"
url := gESURL + "/_cat/indices?format=json"
req, err := http.NewRequest(method, url, nil)
fatalError(err)
resp, err := http.DefaultClient.Do(req)
fatalError(err)
body, err := ioutil.ReadAll(resp.Body)
fatalError(err)
_ = resp.Body.Close()
body = append([]byte(`{"x":`), body...)
body = append(body, []byte(`}`)...)
var result map[string]interface{}
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
indices := getIndices(result, false)
url = gESURL + "/_cat/aliases?format=json"
req, err = http.NewRequest(method, url, nil)
fatalError(err)
resp, err = http.DefaultClient.Do(req)
fatalError(err)
body, err = ioutil.ReadAll(resp.Body)
fatalError(err)
_ = resp.Body.Close()
body = append([]byte(`{"x":`), body...)
body = append(body, []byte(`}`)...)
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
aliases := getIndices(result, true)
slugRoots, dataSourceTypes = getRoots(indices, aliases)
return
}
func jsonEscape(str string) string {
b, _ := jsoniter.Marshal(str)
return string(b[1 : len(b)-1])
}
func timeParseES(dtStr string) (time.Time, error) {
dtStr = strings.TrimSpace(strings.Replace(dtStr, "Z", "", -1))
ary := strings.Split(dtStr, "+")
ary2 := strings.Split(ary[0], ".")
var s string
if len(ary2) == 1 {
s = ary2[0] + ".000"
} else {
if len(ary2[1]) > 3 {
ary2[1] = ary2[1][:3]
}
s = strings.Join(ary2, ".")
}
return time.Parse("2006-01-02T15:04:05.000", s)
}
func toMDYDate(dt time.Time) string {
return fmt.Sprintf("%d/%d/%d", dt.Month(), dt.Day(), dt.Year())
}
func toYMDHMSDate(dt time.Time) string {
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", dt.Year(), dt.Month(), dt.Day(), dt.Hour(), dt.Minute(), dt.Second())
}
func applySlugMapping(slug string, useDAWhenNotFound bool) (daName, sfName string, found bool) {
slugs := []string{slug}
defer func() {
if gDbg {
fmt.Printf("slug mapping: %s -> %+v -> %s,%s,%v\n", slug, slugs, daName, sfName, found)
return
}
if !found {
fmt.Printf("slug mapping not found: %s -> %+v -> %s,%s\n", slug, slugs, daName, sfName)
}
}()
ary := strings.Split(slug, "-")
n := len(ary)
for i := 1; i < n; i++ {
slugs = append(slugs, strings.Join(ary[:i], "-")+"/"+strings.Join(ary[i:], "-"))
}
if strings.HasSuffix(slug, "-shared") {
newSlug := slug[:len(slug)-7]
if gDbg {
fmt.Printf("shared slug detected: '%s' -> '%s'\n", slug, newSlug)
}
slugs = append(slugs, newSlug)
ary := strings.Split(newSlug, "-")
n := len(ary)
for i := 1; i < n; i++ {
slugs = append(slugs, strings.Join(ary[:i], "-")+"/"+strings.Join(ary[i:], "-"))
}
}
for _, kw := range []string{"common", "all"} {
if strings.HasSuffix(slug, "-"+kw) {
newSlug := slug[:len(slug)-(len(kw)+1)]
if gDbg {
fmt.Printf("%s slug detected: '%s' -> '%s'\n", kw, slug, newSlug)
}
slugs = append(slugs, newSlug)
ary := strings.Split(newSlug, "-")
n := len(ary)
for i := 1; i < n; i++ {
slugs = append(slugs, strings.Join(ary[:i], "-")+"/"+strings.Join(ary[i:], "-"))
}
if n > 1 {
ary = ary[:n-1]
n--
newSlug := strings.Join(ary, "-")
slugs = append(slugs, newSlug)
if gDbg {
fmt.Printf("%s slug detected (2nd attempt): '%s' -> '%s'\n", kw, slug, newSlug)
}
for i := 1; i < n; i++ {
slugs = append(slugs, strings.Join(ary[:i], "-")+"/"+strings.Join(ary[i:], "-"))
}
}
}
}
if strings.HasSuffix(slug, "-f") {
newSlug := slug[:len(slug)-2]
if gDbg {
fmt.Printf("dash-f slug detected: '%s' -> '%s'\n", slug, newSlug)
}
slugs = append(slugs, newSlug)
ary := strings.Split(newSlug, "-")
n := len(ary)
for i := 1; i < n; i++ {
slugs = append(slugs, strings.Join(ary[:i], "-")+"/"+strings.Join(ary[i:], "-"))
}
}
for _, slg := range slugs {
rows, err := gDB.Query("select sf_name from slug_mapping where da_name = ?", slg)
fatalError(err)
for rows.Next() {
err = rows.Scan(&sfName)
fatalError(err)
break
}
fatalError(rows.Err())
fatalError(rows.Close())
if sfName != "" {
daName = slg
found = true
return
}
}
if useDAWhenNotFound {
sfName = slug
}
daName = slug
return
}
func getPatternIncrementalDate(key string) string {
method := "POST"
data := `{"query":"select max(dt) from \"datalake-status\" where key = '` + key + `'"}`
payloadBytes := []byte(data)
payloadBody := bytes.NewReader(payloadBytes)
url := gESLogURL + "/_sql?format=json"
req, err := http.NewRequest(method, url, payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
fatalError(err)
body, err := ioutil.ReadAll(resp.Body)
fatalError(err)
_ = resp.Body.Close()
var result resultType
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
if result.Error.Type != "" || result.Error.Reason != "" {
if gDbg {
// fmt.Printf("getPatternIncrementalDate(%s): %s/%s: %v\n", key, url, data, result)
fmt.Printf("getPatternIncrementalDate: error for %s: %v\n", key, result.Error)
}
return ""
}
if len(result.Rows) < 1 || len(result.Rows[0]) < 1 {
return ""
}
sDt, ok := result.Rows[0][0].(string)
if !ok {
return ""
}
cond := " and " + cCreatedAtColumn + " >= '" + sDt + "'"
if gDbg {
fmt.Printf("%s condition: %s >= %s\n", key, cCreatedAtColumn, sDt)
}
return cond
}
func savePatternIncrementalDate(key string, when time.Time) {
gSyncDatesMtx.Lock()
gSyncDates[key] = when
gSyncDatesMtx.Unlock()
}
func saveIncrementalDates(thrN int) {
fmt.Printf("saving %d sync dates status using %d threads...\n", len(gSyncDates), thrN)
type docType struct {
Dt time.Time `json:"dt"`
Key string `json:"key"`
}
save := func(ch chan struct{}, key string, when time.Time) {
defer func() {
ch <- struct{}{}
}()
data := docType{Key: key, Dt: when}
payloadBytes, err := jsoniter.Marshal(data)
fatalError(err)
payloadBody := bytes.NewReader(payloadBytes)
method := "POST"
url := gESLogURL + "/datalake-status/_doc?refresh=wait_for"
req, err := http.NewRequest(method, os.ExpandEnv(url), payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
fatalError(err)
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != 201 {
body, err := ioutil.ReadAll(resp.Body)
fatalError(err)
fatalf("Method:%s url:%s status:%d data:%+v\n%s", method, url, resp.StatusCode, data, body)
}
if gDbg {
fmt.Printf("saved sync date '%s' -> '%v'\n", key, when)
}
}
ch := make(chan struct{})
nThreads := 0
for key, when := range gSyncDates {
go save(ch, key, when)
nThreads++
if nThreads == thrN {
<-ch
nThreads--
}
}
for nThreads > 0 {
<-ch
nThreads--
}
fmt.Printf("saved %d sync dates status\n", len(gSyncDates))
}
// subrep
func datalakeLOCReportForRoot(root, projectSlug, sfSlug string, overrideProjectSlug, missingCol bool) (locItems []datalakeLOCReportItem, retry bool) {
if gDbg {
defer func() {
fmt.Printf("got LOC %s: %d\n", root, len(locItems))
}()
}
var fromCond string
if gIncremental {
key := root + ":git"
fromCond = getPatternIncrementalDate(key)
defer func() {
if !retry && len(locItems) > 0 {
savePatternIncrementalDate(key, time.Now().Add(time.Duration(cOffsetMinutes)*time.Minute))
}
}()
}
pattern := jsonEscape("sds-" + root + "-git*,-*-github,-*-github-issue,-*-github-repository,-*-github-pull_request,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache")
fields := getAllFields(pattern)
_, isGit := fields["git_uuid"]
if !isGit {
if gDbg {
fmt.Printf("%s: has no git data\n", root)
}
return
}
appendCols := ""
extraCols := []string{"title", "commit_url"}
for _, extraCol := range extraCols {
_, present := fields[extraCol]
if present {
appendCols += `, \"` + extraCol + `\"`
} else {
appendCols += `, ''`
}
}
method := "POST"
var data string
if missingCol {
data = fmt.Sprintf(
`{"query":"select git_uuid, author_id, '%s', %s, lines_added, lines_removed%s from \"%s\" `+
`where author_id is not null and type = 'commit' and (lines_added > 0 or lines_removed > 0)%s","fetch_size":%d}`,
projectSlug,
cCreatedAtColumn,
appendCols,
pattern,
fromCond,
10000,
)
} else {
data = fmt.Sprintf(
`{"query":"select git_uuid, author_id, project_slug, %s, lines_added, lines_removed%s from \"%s\" `+
`where author_id is not null and type = 'commit' and (lines_added > 0 or lines_removed > 0)%s","fetch_size":%d}`,
cCreatedAtColumn,
appendCols,
pattern,
fromCond,
10000,
)
}
if gDbg {
fmt.Printf("%s:%s\n", pattern, data)
}
payloadBytes := []byte(data)
payloadBody := bytes.NewReader(payloadBytes)
url := gESURL + "/_sql?format=json"
req, err := http.NewRequest(method, url, payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
fatalError(err)
body, err := ioutil.ReadAll(resp.Body)
fatalError(err)
_ = resp.Body.Close()
var result resultType
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
if result.Error.Type != "" || result.Error.Reason != "" {
// Missing index error in this case is allowed
status := reportThisError(result.Error)
if gDbg || status > 0 {
fmt.Printf("datalakeLOCReportForRoot: error for %s: %v\n", pattern, result.Error)
}
if status < 0 {
retry = true
}
return
}
if len(result.Rows) == 0 {
return
}
var pSlug string
if overrideProjectSlug {
pSlug = projectSlug
}
processResults := func() {
skipped := 0
for _, row := range result.Rows {
// [f16103509162d3044c5882a2b0d4c4cf70c16cb0 7f6daae75c73b05795d1cffb2f6642d51ad94ab5 accord/accord-concerto 2021-08-11T12:16:55.000Z 1 1]
documentID, _ := row[0].(string)
identityID, _ := row[1].(string)
if !overrideProjectSlug {
pSlug, _ = row[2].(string)
}
// Skip rows having no enriched date
if row[3] == nil {
skipped++
continue
}
createdAt, _ := timeParseES(row[3].(string))
fLOCAdded, _ := row[4].(float64)
locAdded := int(fLOCAdded)
fLOCDeleted, _ := row[5].(float64)
locDeleted := int(fLOCDeleted)
title, _ := row[6].(string)
url, _ := row[7].(string)
item := datalakeLOCReportItem{
docID: documentID,
identityID: identityID,
dataSource: "git",
projectSlug: pSlug,
sfSlug: sfSlug,
createdAt: createdAt,
locAdded: locAdded,
locDeleted: locDeleted,
title: title,
url: url,
filtered: false,
}
locItems = append(locItems, item)
}
if skipped > 0 {
fmt.Printf("%s: skipped %d/%d rows due to missing %s\n", pattern, skipped, len(result.Rows), cCreatedAtColumn)
}
}
processResults()
page := 1
for {
if result.Cursor == "" {
break
}
data = `{"cursor":"` + result.Cursor + `"}`
//fmt.Printf("data=%s\n", data)
payloadBytes = []byte(data)
payloadBody = bytes.NewReader(payloadBytes)
req, err = http.NewRequest(method, url, payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err = http.DefaultClient.Do(req)
fatalError(err)
body, err = ioutil.ReadAll(resp.Body)
fatalError(err)
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
if result.Error.Type != "" || result.Error.Reason != "" {
fmt.Printf("datalakeLOCReportForRoot: error for %s: %v\n", pattern, result.Error)
break
}
if len(result.Rows) == 0 {
break
}
page++
if gDbg || gProgress {
fmt.Printf("%s: processing #%d page...\n", pattern, page)
}
processResults()
}
if result.Cursor == "" {
return
}
url = gESURL + "/_sql/close"
data = `{"cursor":"` + result.Cursor + `"}`
payloadBytes = []byte(data)
payloadBody = bytes.NewReader(payloadBytes)
req, err = http.NewRequest(method, url, payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err = http.DefaultClient.Do(req)
fatalError(err)
body, err = ioutil.ReadAll(resp.Body)
fatalError(err)
_ = resp.Body.Close()
return
}
// subrep
func datalakeGithubPRReportForRoot(root, projectSlug, sfName string, overrideProjectSlug, missingCol bool) (prItems []datalakePRReportItem, retry bool) {
if gDbg {
defer func() {
fmt.Printf("got github-pr %s: %d\n", root, len(prItems))
}()
}
var fromCond string
if gIncremental {
key := root + ":github-pulls"
fromCond = getPatternIncrementalDate(key)
defer func() {
if !retry && len(prItems) > 0 {
savePatternIncrementalDate(key, time.Now().Add(time.Duration(cOffsetMinutes)*time.Minute))
}
}()
}
pattern := jsonEscape("sds-" + root + "-github-issue*,-*-raw,-*-for-merge,-*-cache,-*-converted,-*-temp,-*-last-action-date-cache")
fields := getAllFields(pattern)
_, isPR := fields["is_github_pull_request"]
if !isPR {
if gDbg {
fmt.Printf("%s: has no github PRs data (probably only issues?)\n", root)
}
return
}
appendCols := ""
extraCols := []string{"title", "url", "html_url"}
for _, extraCol := range extraCols {
_, present := fields[extraCol]
if present {
appendCols += `, \"` + extraCol + `\"`
} else {
appendCols += `, ''`
}
}
method := "POST"
var data string
if missingCol {
data = fmt.Sprintf(
`{"query":"select id, author_id, '%s', %s, type, state, merged_by_data_id%s from \"%s\" `+
`where author_id is not null and is_github_pull_request = 1%s","fetch_size":%d}`,
projectSlug,
cCreatedAtColumn,
appendCols,
pattern,
fromCond,
10000,
)
} else {
data = fmt.Sprintf(
`{"query":"select id, author_id, project_slug, %s, type, state, merged_by_data_id%s from \"%s\" `+
`where author_id is not null and is_github_pull_request = 1%s","fetch_size":%d}`,
cCreatedAtColumn,
appendCols,
pattern,
fromCond,
10000,
)
}
if gDbg {
fmt.Printf("%s:%s\n", pattern, data)
}
payloadBytes := []byte(data)
payloadBody := bytes.NewReader(payloadBytes)
url := gESURL + "/_sql?format=json"
req, err := http.NewRequest(method, url, payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
fatalError(err)
body, err := ioutil.ReadAll(resp.Body)
fatalError(err)
_ = resp.Body.Close()
var result resultType
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
if result.Error.Type != "" || result.Error.Reason != "" {
// Missing index error in this case is allowed
status := reportThisError(result.Error)
if gDbg || status > 0 {
fmt.Printf("datalakeGitHubPRReportForRoot: error for %s: %v\n", pattern, result.Error)
}
if status < 0 {
retry = true
}
return
}
if len(result.Rows) == 0 {
return
}
var pSlug string
if overrideProjectSlug {
pSlug = projectSlug
}
processResults := func() {
skipped := 0
for _, row := range result.Rows {
// [ffd3f84758dbdd21df9a66b09a96df1ae47db0f3 2ca78b1cc8c9bb81152d3495a5aa8058fba5801c academy-software-foundation/opencolorio 2021-09-16T06:33:13.461Z pull_request closed 5675ad72e0958195400713bc2430e77315cbedf9]
// [ffd3f84758dbdd21df9a66b09a96df1ae47db0f3 5675ad72e0958195400713bc2430e77315cbedf9 academy-software-foundation/opencolorio 2021-09-16T06:33:13.461Z pull_request_review APPROVED <nil>]
// [293c9ccfe121c0b895c9b7cf0ce20aa11f142aca 2ab3287aa9894fbb6b395e544fc579ba3126c8c7 academy-software-foundation/opencolorio 2021-10-04T23:32:45.981Z issue_comment <nil> <nil>]
documentID, _ := row[0].(string)
identityID, _ := row[1].(string)
if !overrideProjectSlug {
pSlug, _ = row[2].(string)
}
// Skip rows having no enriched date
if row[3] == nil {
skipped++
continue
}
createdAt, _ := timeParseES(row[3].(string))
actionType, _ := row[4].(string)
state, _ := row[5].(string)
mergeIdentityID, _ := row[6].(string)
// fmt.Printf("(%s,%s,%s)\n", actionType, state, mergeIdentityID)
if actionType == "pull_request_review" {
switch state {
case "APPROVED":
actionType = "GitHub PR approved"
case "CHANGES_REQUESTED":
actionType = "GitHub PR changes requested"
case "COMMENTED":
actionType = "GitHub PR review comment"
case "DISMISSED":
actionType = "GitHub PR dismissed"
}
}
title, _ := row[7].(string)
var url string
if actionType == "pull_request" {
url, _ = row[8].(string)
} else {
url, _ = row[9].(string)
}
if identityID == mergeIdentityID {
actionType = "GitHub PR merged"
}
item := datalakePRReportItem{
docID: documentID,
identityID: identityID,
dataSource: "github",
projectSlug: pSlug,
sfSlug: sfName,
createdAt: createdAt,
actionType: actionType,
title: title,
url: url,
filtered: false,
}
prItems = append(prItems, item)
}
if skipped > 0 {
fmt.Printf("%s: skipped %d/%d rows due to missing %s\n", pattern, skipped, len(result.Rows), cCreatedAtColumn)
}
}
processResults()
page := 1
for {
if result.Cursor == "" {
break
}
data = `{"cursor":"` + result.Cursor + `"}`
//fmt.Printf("data=%s\n", data)
payloadBytes = []byte(data)
payloadBody = bytes.NewReader(payloadBytes)
req, err = http.NewRequest(method, url, payloadBody)
fatalError(err)
req.Header.Set("Content-Type", "application/json")
resp, err = http.DefaultClient.Do(req)
fatalError(err)
body, err = ioutil.ReadAll(resp.Body)
fatalError(err)
err = jsoniter.Unmarshal(body, &result)
fatalError(err)
if result.Error.Type != "" || result.Error.Reason != "" {
fmt.Printf("datalakeGitHubPRReportForRoot: error for %s: %v\n", pattern, result.Error)
break
}
if len(result.Rows) == 0 {
break
}
page++
if gDbg || gProgress {
fmt.Printf("%s: processing #%d page...\n", pattern, page)
}
processResults()
}
if result.Cursor == "" {
return
}
url = gESURL + "/_sql/close"
data = `{"cursor":"` + result.Cursor + `"}`
payloadBytes = []byte(data)
payloadBody = bytes.NewReader(payloadBytes)
req, err = http.NewRequest(method, url, payloadBody)
fatalError(err)