-
Notifications
You must be signed in to change notification settings - Fork 4
/
dsjira.go
1485 lines (1437 loc) · 42.3 KB
/
dsjira.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 (
"encoding/base64"
"fmt"
neturl "net/url"
"os"
"strconv"
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
)
const (
// JiraAPIRoot - main API path
JiraAPIRoot = "/rest/api/2"
// JiraAPISearch - search API subpath
JiraAPISearch = "/search"
// JiraAPIField - field API subpath
JiraAPIField = "/field"
// JiraAPIIssue - issue API subpath
JiraAPIIssue = "/issue"
// JiraAPIComment - comments API subpath
JiraAPIComment = "/comment"
// JiraBackendVersion - backend version
JiraBackendVersion = "0.1.1"
// JiraDefaultSearchField - default search field
JiraDefaultSearchField = "item_id"
// JiraFilterByProjectInComments - filter by project when searching for comments
JiraFilterByProjectInComments = false
// JiraDropCustomFields - drop custom fields from raw index
JiraDropCustomFields = true
// JiraMapCustomFields - run custom fields mapping
JiraMapCustomFields = true
// ClosedStatusCategoryKey - issue closed status key
ClosedStatusCategoryKey = "done"
// JiraRichAuthorField - rich index author field
JiraRichAuthorField = "reporter"
)
var (
// JiraSearchFields - extra search fields
JiraSearchFields = map[string][]string{
"project_id": {"fields", "project", "id"},
"project_key": {"fields", "project", "key"},
"project_name": {"fields", "project", "name"},
"issue_key": {"key"},
}
// JiraRawMapping - Jira raw index mapping
// JiraRawMapping = []byte(`{"dynamic":true,"properties":{"metadata__updated_on":{"type":"date"},"data":{"properties":{"renderedFields":{"dynamic":false,"properties":{}},"operations":{"dynamic":false,"properties":{}},"fields":{"dynamic":true,"properties":{"description":{"type":"text","index":true},"workratio":{"type":"double"},"environment":{"type":"text","index":true}}},"changelog":{"properties":{"histories":{"dynamic":false,"properties":{}}}},"comments_data":{"properties":{"body":{"type":"text","index":true}}}}}}}`)
JiraRawMapping = []byte(`{"properties":{"metadata__updated_on":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"main_description_analyzed":{"type":"text","index":true},"releases":{"type":"keyword"},"body":{"type":"text","index":true}},"dynamic_templates":[{"notanalyzed":{"match":"*","unmatch":"body","match_mapping_type":"string","mapping":{"type":"keyword"}}},{"formatdate":{"match":"*","match_mapping_type":"date","mapping":{"format":"strict_date_optional_time||epoch_millis","type":"date"}}}]}`)
// JiraRichMapping - Jira rich index mapping
// JiraRichMapping = []byte(`{"properties":{"metadata__updated_on":{"type":"date"},"main_description_analyzed":{"type":"text","index":true},"releases":{"type":"keyword"},"body":{"type":"text","index":true}}}`)
JiraRichMapping = []byte(`{"dynamic":true,"properties":{"metadata__updated_on":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"data":{"properties":{"renderedFields":{"dynamic":false,"properties":{}},"operations":{"dynamic":false,"properties":{}},"fields":{"dynamic":true,"properties":{"description":{"type":"text","index":true},"environment":{"type":"text","index":true}}},"changelog":{"properties":{"histories":{"dynamic":false,"properties":{}}}},"comments_data":{"properties":{"body":{"type":"text","index":true}}}}}},"dynamic_templates":[{"notanalyzed":{"match":"*","unmatch":"body","match_mapping_type":"string","mapping":{"type":"keyword"}}},{"workratio":{"match":"workratio","match_mapping_type":"long","mapping":{"type":"double"}}},{"formatdate":{"match":"*","match_mapping_type":"date","mapping":{"format":"strict_date_optional_time||epoch_millis","type":"date"}}}]}`)
// JiraRoles - roles defined for Jira backend
JiraRoles = []string{"assignee", "reporter", "creator", Author, "updateAuthor"}
// JiraCategories - categories defined for Jira
JiraCategories = map[string]struct{}{Issue: {}}
// JiraKeepCustomFiled - we're dropping all but those custom fields
JiraKeepCustomFiled = map[string]struct{}{"Story Points": {}, "Sprint": {}}
)
// DSJira - DS implementation for Jira
type DSJira struct {
DS string
URL string // From DA_JIRA_URL - Jira URL
NoSSLVerify bool // From DA_JIRA_NO_SSL_VERIFY
User string // From DA_JIRA_USER - if user is provided then we assume that we don't have base64 encoded user:token yet
Token string // From DA_JIRA_TOKEN - if user is not specified we assume that token already contains "<username>:<your-api-token>"
PageSize int // From DA_JIRA_PAGE_SIZE
MultiOrigin bool // From DA_JIRA_MULTI_ORIGIN
}
// JiraField - informatin about fields present in issues
type JiraField struct {
ID string `json:"id"`
Name string `json:"name"`
Custom bool `json:"custom"`
}
// ParseArgs - parse jira specific environment variables
func (j *DSJira) ParseArgs(ctx *Ctx) (err error) {
j.DS = Jira
// Jira specific env variables
prefix := "DA_JIRA_"
j.URL = os.Getenv(prefix + "URL")
j.NoSSLVerify = StringToBool(os.Getenv(prefix + "NO_SSL_VERIFY"))
j.Token = os.Getenv(prefix + "TOKEN")
AddRedacted(j.Token, false)
j.User = os.Getenv(prefix + "USER")
AddRedacted(j.User, false)
if j.User != "" {
// If user is specified, then we must calculate base64(user:token) to get a real token
j.Token = base64.StdEncoding.EncodeToString([]byte(j.User + ":" + j.Token))
AddRedacted(j.Token, false)
}
if os.Getenv(prefix+"PAGE_SIZE") == "" {
j.PageSize = 500
} else {
pageSize, err := strconv.Atoi(os.Getenv(prefix + "PAGE_SIZE"))
FatalOnError(err)
if pageSize > 0 {
j.PageSize = pageSize
}
}
j.MultiOrigin = StringToBool(os.Getenv(prefix + "MULTI_ORIGIN"))
if j.NoSSLVerify {
NoSSLVerify()
}
return
}
// Validate - is current DS configuration OK?
func (j *DSJira) Validate(ctx *Ctx) (err error) {
if strings.HasSuffix(j.URL, "/") {
j.URL = j.URL[:len(j.URL)-1]
}
if j.URL == "" {
err = fmt.Errorf("Jira URL must be set")
}
return
}
// Name - return data source name
func (j *DSJira) Name() string {
return j.DS
}
// Info - return DS configuration in a human readable form
func (j DSJira) Info() string {
return fmt.Sprintf("%+v", j)
}
// CustomFetchRaw - is this datasource using custom fetch raw implementation?
func (j *DSJira) CustomFetchRaw() bool {
return false
}
// FetchRaw - implement fetch raw data for Jira
func (j *DSJira) 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 *DSJira) CustomEnrich() bool {
return false
}
// Enrich - implement enrich data for Jira
func (j *DSJira) Enrich(ctx *Ctx) (err error) {
Printf("%s should use generic Enrich()\n", j.DS)
return
}
// GetFields - implement get fields for jira datasource
func (j *DSJira) GetFields(ctx *Ctx) (customFields map[string]JiraField, err error) {
url := j.URL + JiraAPIRoot + JiraAPIField
method := Get
var headers map[string]string
if j.Token != "" {
headers = map[string]string{"Authorization": "Basic " + j.Token}
}
var resp interface{}
// Week for caching fields, they don't change that often
cacheFor := time.Duration(168) * time.Hour
resp, _, _, _, err = Request(ctx, url, method, headers, []byte{}, []string{}, nil, nil, map[[2]int]struct{}{{200, 200}: {}}, map[[2]int]struct{}{{200, 200}: {}}, true, &cacheFor, false)
if err != nil {
return
}
var fields []JiraField
err = jsoniter.Unmarshal(resp.([]byte), &fields)
if err != nil {
return
}
customFields = make(map[string]JiraField)
for _, field := range fields {
if !field.Custom {
continue
}
customFields[field.ID] = field
}
return
}
// GenSearchFields - generate extra search fields
func (j *DSJira) GenSearchFields(ctx *Ctx, issue interface{}, uuid string) (fields map[string]interface{}) {
searchFields := j.SearchFields()
fields = make(map[string]interface{})
fields[JiraDefaultSearchField] = uuid
for field, keyAry := range searchFields {
value, ok := Dig(issue, keyAry, false, true)
if ok {
fields[field] = value
}
}
if ctx.Debug > 1 {
Printf("returning search fields %+v\n", fields)
}
return
}
// AddMetadata - add metadata to the item
func (j *DSJira) AddMetadata(ctx *Ctx, issue interface{}) (mItem map[string]interface{}) {
mItem = make(map[string]interface{})
origin := j.URL
tag := ctx.Tag
if tag == "" {
tag = origin
if ctx.Project != "" {
tag += ":::" + ctx.Project
}
}
issueID := j.ItemID(issue)
updatedOn := j.ItemUpdatedOn(issue)
uuid := UUIDNonEmpty(ctx, origin, issueID)
timestamp := time.Now()
mItem["backend_name"] = j.DS
mItem["backend_version"] = JiraBackendVersion
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(issue)
mItem["search_fields"] = j.GenSearchFields(ctx, issue, uuid)
mItem[DefaultDateField] = ToESDate(updatedOn)
mItem[DefaultTimestampField] = ToESDate(timestamp)
mItem[ProjectSlug] = ctx.ProjectSlug
if ctx.Debug > 1 {
Printf("%s: %s: %v %v\n", origin, uuid, issueID, updatedOn)
}
return
}
// ProcessIssue - process a single issue
func (j *DSJira) ProcessIssue(ctx *Ctx, allIssues *[]interface{}, allIssuesMtx *sync.Mutex, issue interface{}, customFields map[string]JiraField, from time.Time, to *time.Time, thrN int) (wch chan error, err error) {
var mtx *sync.RWMutex
if thrN > 1 {
mtx = &sync.RWMutex{}
}
issueID := j.ItemID(issue)
var headers map[string]string
if j.Token != "" {
headers = map[string]string{"Content-Type": "application/json", "Authorization": "Basic " + j.Token}
} else {
headers = map[string]string{"Content-Type": "application/json"}
}
// Encode search params in query for GET requests
encodeInQuery := true
cacheFor := time.Duration(3) * time.Hour
processIssue := func(c chan error) (e error) {
defer func() {
if c != nil {
c <- e
}
}()
urlRoot := j.URL + JiraAPIRoot + JiraAPIIssue + "/" + issueID + JiraAPIComment
startAt := int64(0)
maxResults := int64(j.PageSize)
epochMS := from.UnixNano() / 1e6
// Seems like original Jira was using project filter there which is not needed IMHO.
var jql string
if JiraFilterByProjectInComments {
if to != nil {
epochToMS := (*to).UnixNano() / 1e6
if ctx.ProjectFilter && ctx.Project != "" {
jql = fmt.Sprintf(`project = %s AND updated > %d AND updated < %d order by updated asc`, ctx.Project, epochMS, epochToMS)
} else {
jql = fmt.Sprintf(`updated > %d AND updated < %d order by updated asc`, epochMS, epochToMS)
}
} else {
if ctx.ProjectFilter && ctx.Project != "" {
jql = fmt.Sprintf(`project = %s AND updated > %d order by updated asc`, ctx.Project, epochMS)
} else {
jql = fmt.Sprintf(`updated > %d order by updated asc`, epochMS)
}
}
} else {
if to != nil {
epochToMS := (*to).UnixNano() / 1e6
jql = fmt.Sprintf(`updated > %d AND updated < %d order by updated asc`, epochMS, epochToMS)
} else {
jql = fmt.Sprintf(`updated > %d order by updated asc`, epochMS)
}
}
method := Get
for {
var payloadBytes []byte
url := urlRoot
if encodeInQuery {
// ?startAt=0&maxResults=100&jql=updated+%3E+0+order+by+updated+asc
url += fmt.Sprintf(`?startAt=%d&maxResults=%d&jql=`, startAt, maxResults) + neturl.QueryEscape(jql)
} else {
payloadBytes = []byte(fmt.Sprintf(`{"startAt":%d,"maxResults":%d,"jql":"%s"}`, startAt, maxResults, jql))
}
var res interface{}
res, _, _, _, e = Request(
ctx,
url,
method,
headers,
payloadBytes,
[]string{},
map[[2]int]struct{}{{200, 200}: {}}, // JSON statuses
nil, // Error statuses
map[[2]int]struct{}{{200, 200}: {}}, // OK statuses: 200
map[[2]int]struct{}{{200, 200}: {}}, // Cache statuses: 200
true, // retry
&cacheFor, // cache duration
false, // skip in dry-run mode
)
if e != nil {
return
}
comments, ok := res.(map[string]interface{})["comments"].([]interface{})
if !ok {
e = fmt.Errorf("unable to unmarshal comments from %+v", DumpKeys(res))
return
}
if ctx.Debug > 1 {
nComments := len(comments)
if nComments > 0 {
Printf("processing %d comments\n", len(comments))
}
}
if thrN > 1 {
mtx.Lock()
}
issueComments, ok := issue.(map[string]interface{})["comments_data"].([]interface{})
if !ok {
issue.(map[string]interface{})["comments_data"] = []interface{}{}
}
issueComments, _ = issue.(map[string]interface{})["comments_data"].([]interface{})
if !ok {
issueComments = comments
} else {
issueComments = append(issueComments, comments...)
}
issue.(map[string]interface{})["comments_data"] = issueComments
if thrN > 1 {
mtx.Unlock()
}
totalF, ok := res.(map[string]interface{})["total"].(float64)
if !ok {
e = fmt.Errorf("unable to unmarshal total from %+v", DumpKeys(res))
return
}
maxResultsF, ok := res.(map[string]interface{})["maxResults"].(float64)
if !ok {
e = fmt.Errorf("unable to maxResults total from %+v", DumpKeys(res))
return
}
total := int64(totalF)
maxResults = int64(maxResultsF)
inc := int64(totalF)
if maxResultsF < totalF {
inc = int64(maxResultsF)
}
startAt += inc
if startAt >= total {
startAt = total
break
}
if ctx.Debug > 0 {
Printf("processing next comments page from %d/%d\n", startAt, total)
}
}
if ctx.Debug > 1 {
Printf("processed %d comments\n", startAt)
}
return
}
var ch chan error
if thrN > 1 {
ch = make(chan error)
go func() {
_ = processIssue(ch)
}()
} else {
err = processIssue(nil)
if err != nil {
return
}
}
if thrN > 1 {
mtx.RLock()
}
issueFields, ok := issue.(map[string]interface{})["fields"].(map[string]interface{})
if thrN > 1 {
mtx.RUnlock()
}
if !ok {
err = fmt.Errorf("unable to unmarshal fields from issue %+v", DumpKeys(issue))
return
}
if ctx.Debug > 1 {
Printf("before map custom: %+v\n", DumpPreview(issueFields, 100))
}
type mapping struct {
ID string
Name string
Value interface{}
}
if JiraMapCustomFields {
m := make(map[string]mapping)
for k, v := range issueFields {
customField, ok := customFields[k]
if !ok {
continue
}
m[k] = mapping{ID: customField.ID, Name: customField.Name, Value: v}
}
for k, v := range m {
if ctx.Debug > 1 {
prev := issueFields[k]
Printf("mapping custom fields %s: %+v -> %+v\n", k, prev, v)
}
issueFields[k] = v
}
}
if ctx.Debug > 1 {
Printf("after map custom: %+v\n", DumpPreview(issueFields, 100))
}
// Extra fields
if thrN > 1 {
mtx.Lock()
}
esItem := j.AddMetadata(ctx, issue)
// Seems like it doesn't make sense, because we just added those custom fields
if JiraDropCustomFields {
for k, v := range issueFields {
if strings.HasPrefix(strings.ToLower(k), "customfield_") {
mp, _ := v.(mapping)
_, keep := JiraKeepCustomFiled[mp.Name]
if !keep {
delete(issueFields, k)
}
}
}
}
if ctx.Debug > 1 {
Printf("after drop: %+v\n", DumpPreview(issueFields, 100))
}
if ctx.Project != "" {
issue.(map[string]interface{})["project"] = ctx.Project
}
esItem["data"] = issue
if thrN > 1 {
mtx.Unlock()
err = <-ch
}
if allIssuesMtx != nil {
allIssuesMtx.Lock()
}
*allIssues = append(*allIssues, esItem)
nIssues := len(*allIssues)
if nIssues >= ctx.ESBulkSize {
sendToElastic := func(c chan error) (e error) {
defer func() {
if c != nil {
c <- e
}
}()
e = SendToElastic(ctx, j, true, UUID, *allIssues)
if e != nil {
Printf("error %v sending %d issues to ElasticSearch\n", e, len(*allIssues))
}
*allIssues = []interface{}{}
if allIssuesMtx != nil {
allIssuesMtx.Unlock()
}
return
}
if thrN > 1 {
wch = make(chan error)
go func() {
_ = sendToElastic(wch)
}()
} else {
err = sendToElastic(nil)
if err != nil {
return
}
}
} else {
if allIssuesMtx != nil {
allIssuesMtx.Unlock()
}
}
return
}
// FetchItems - implement fetch items for jira datasource
func (j *DSJira) FetchItems(ctx *Ctx) (err error) {
thrN := GetThreadsNum(ctx)
var customFields map[string]JiraField
fieldsFetched := false
var chF chan error
getFields := func(c chan error) (e error) {
defer func() {
if c != nil {
c <- e
}
if ctx.Debug > 0 {
Printf("got %d custom fields\n", len(customFields))
}
}()
customFields, e = j.GetFields(ctx)
return
}
if thrN > 1 {
chF = make(chan error)
go func() {
_ = getFields(chF)
}()
} else {
err = getFields(nil)
if err != nil {
Printf("GetFields error: %+v\n", err)
return
}
fieldsFetched = true
}
// '{"jql":"updated > 1601281314000 order by updated asc","startAt":0,"maxResults":400,"expand":["renderedFields","transitions","operations","changelog"]}'
var (
from time.Time
to *time.Time
)
if ctx.DateFrom != nil {
from = *ctx.DateFrom
} else {
from = DefaultDateFrom
}
to = ctx.DateTo
url := j.URL + JiraAPIRoot + JiraAPISearch
startAt := int64(0)
maxResults := int64(j.PageSize)
jql := ""
epochMS := from.UnixNano() / 1e6
if to != nil {
epochToMS := (*to).UnixNano() / 1e6
if ctx.ProjectFilter && ctx.Project != "" {
jql = fmt.Sprintf(`"jql":"project = %s AND updated > %d AND updated < %d order by updated asc"`, ctx.Project, epochMS, epochToMS)
} else {
jql = fmt.Sprintf(`"jql":"updated > %d AND updated < %d order by updated asc"`, epochMS, epochToMS)
}
} else {
if ctx.ProjectFilter && ctx.Project != "" {
jql = fmt.Sprintf(`"jql":"project = %s AND updated > %d order by updated asc"`, ctx.Project, epochMS)
} else {
jql = fmt.Sprintf(`"jql":"updated > %d order by updated asc"`, epochMS)
}
}
expand := `"expand":["renderedFields","transitions","operations","changelog"]`
allIssues := []interface{}{}
var allIssuesMtx *sync.Mutex
var escha []chan error
var eschaMtx *sync.Mutex
var chE chan error
if thrN > 1 {
chE = make(chan error)
allIssuesMtx = &sync.Mutex{}
eschaMtx = &sync.Mutex{}
}
nThreads := 0
method := Post
var headers map[string]string
if j.Token != "" {
// Token should be BASE64("useremail:api_token"), see: https://developer.atlassian.com/cloud/jira/platform/basic-auth-for-rest-apis
headers = map[string]string{"Content-Type": "application/json", "Authorization": "Basic " + j.Token}
} else {
headers = map[string]string{"Content-Type": "application/json"}
}
if ctx.Debug > 0 {
Printf("requesting issues from: %s\n", from)
}
cacheFor := time.Duration(3) * time.Hour
for {
payloadBytes := []byte(fmt.Sprintf(`{"startAt":%d,"maxResults":%d,%s,%s}`, startAt, maxResults, jql, expand))
var res interface{}
res, _, _, _, err = Request(
ctx,
url,
method,
headers,
payloadBytes,
[]string{},
map[[2]int]struct{}{{200, 200}: {}}, // JSON statuses
nil, // Error statuses
map[[2]int]struct{}{{200, 200}: {}}, // OK statuses: 200
map[[2]int]struct{}{{200, 200}: {}}, // Cache statuses: 200
true, // retry
&cacheFor, // cache duration
false, // skip in dry-run mode
)
if err != nil {
return
}
if !fieldsFetched {
err = <-chF
if err != nil {
Printf("GetFields error: %+v\n", err)
return
}
fieldsFetched = true
}
processIssues := func(c chan error) (e error) {
defer func() {
if c != nil {
c <- e
}
}()
issues, ok := res.(map[string]interface{})["issues"].([]interface{})
if !ok {
e = fmt.Errorf("unable to unmarshal issues from %+v", DumpKeys(res))
return
}
if ctx.Debug > 0 {
Printf("processing %d issues\n", len(issues))
}
for _, issue := range issues {
var esch chan error
esch, e = j.ProcessIssue(ctx, &allIssues, allIssuesMtx, issue, customFields, from, to, thrN)
if e != nil {
Printf("Error %v processing issue: %+v\n", e, issue)
return
}
if esch != nil {
if eschaMtx != nil {
eschaMtx.Lock()
}
escha = append(escha, esch)
if eschaMtx != nil {
eschaMtx.Unlock()
}
}
}
return
}
if thrN > 1 {
go func() {
_ = processIssues(chE)
}()
nThreads++
if nThreads == thrN {
err = <-chE
if err != nil {
return
}
nThreads--
}
} else {
err = processIssues(nil)
if err != nil {
return
}
}
totalF, ok := res.(map[string]interface{})["total"].(float64)
if !ok {
err = fmt.Errorf("unable to unmarshal total from %+v", DumpKeys(res))
return
}
maxResultsF, ok := res.(map[string]interface{})["maxResults"].(float64)
if !ok {
err = fmt.Errorf("unable to maxResults total from %+v", DumpKeys(res))
return
}
total := int64(totalF)
maxResults = int64(maxResultsF)
inc := int64(totalF)
if maxResultsF < totalF {
inc = int64(maxResultsF)
}
startAt += inc
if startAt >= total {
startAt = total
break
}
if ctx.Debug > 0 {
Printf("processing next issues page from %d/%d\n", startAt, total)
}
}
for thrN > 1 && nThreads > 0 {
err = <-chE
nThreads--
if err != nil {
return
}
}
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()
}
nIssues := len(allIssues)
if ctx.Debug > 0 {
Printf("%d remaining issues to send to ES\n", nIssues)
}
if nIssues > 0 {
err = SendToElastic(ctx, j, true, UUID, allIssues)
if err != nil {
Printf("Error %v sending %d issues to ES\n", err, len(allIssues))
}
}
Printf("processed %d issues\n", startAt)
return
}
// SupportDateFrom - does DS support resuming from date?
func (j *DSJira) SupportDateFrom() bool {
return true
}
// SupportOffsetFrom - does DS support resuming from offset?
func (j *DSJira) SupportOffsetFrom() bool {
return false
}
// DateField - return date field used to detect where to restart from
func (j *DSJira) DateField(*Ctx) string {
return DefaultDateField
}
// RichIDField - return rich ID field name
func (j *DSJira) RichIDField(*Ctx) string {
return DefaultIDField
}
// RichAuthorField - return rich author field name
func (j *DSJira) RichAuthorField(*Ctx) string {
return JiraRichAuthorField
}
// OffsetField - return offset field used to detect where to restart from
func (j *DSJira) OffsetField(*Ctx) string {
return DefaultOffsetField
}
//Categories - return a set of configured categories
func (j *DSJira) Categories() map[string]struct{} {
return JiraCategories
}
// OriginField - return origin field used to detect where to restart from
func (j *DSJira) OriginField(ctx *Ctx) string {
return DefaultTagField
}
// ResumeNeedsOrigin - is origin field needed when resuming
// Origin should be needed when multiple configurations save to the same index
// Jira usually stores only one instance per index, so we don't need to enable filtering by origin to resume
func (j *DSJira) ResumeNeedsOrigin(ctx *Ctx, raw bool) bool {
return j.MultiOrigin
}
// 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 *DSJira) ResumeNeedsCategory(ctx *Ctx, raw bool) bool {
return false
}
// Origin - return current origin
// Tag gets precendence if set
func (j *DSJira) Origin(ctx *Ctx) string {
if ctx.Tag != "" {
return ctx.Tag
}
if ctx.Project == "" {
return j.URL
}
return j.URL + ":::" + ctx.Project
}
// ItemID - return unique identifier for an item
func (j *DSJira) ItemID(item interface{}) string {
id, ok := item.(map[string]interface{})["id"].(string)
if !ok {
Fatalf("%s: ItemID() - cannot extract id from %+v", j.DS, item)
}
return id
}
// ItemUpdatedOn - return updated on date for an item
func (j *DSJira) ItemUpdatedOn(item interface{}) time.Time {
fields, ok := item.(map[string]interface{})["fields"].(map[string]interface{})
if !ok {
Fatalf("%s: ItemUpdatedOn() - cannot extract fields from %+v", j.DS, DumpKeys(item))
}
sUpdated, ok := fields["updated"].(string)
if !ok {
Fatalf("%s: ItemUpdatedOn() - cannot extract updated from %+v", j.DS, DumpKeys(fields))
}
updated, err := TimeParseES(sUpdated)
FatalOnError(err)
return updated
}
// ItemCategory - return unique identifier for an item
func (j *DSJira) ItemCategory(item interface{}) string {
return Issue
}
// SearchFields - define (optional) search fields to be returned
func (j *DSJira) SearchFields() map[string][]string {
return JiraSearchFields
}
// ElasticRawMapping - Raw index mapping definition
func (j *DSJira) ElasticRawMapping() []byte {
return JiraRawMapping
}
// ElasticRichMapping - Rich index mapping definition
func (j *DSJira) ElasticRichMapping() []byte {
return JiraRichMapping
}
// 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 *DSJira) GetItemIdentities(ctx *Ctx, doc interface{}) (identities map[[3]string]struct{}, err error) {
fields, ok := doc.(map[string]interface{})["data"].(map[string]interface{})["fields"].(map[string]interface{})
if !ok {
err = fmt.Errorf("cannot read data.fields from doc %+v", DumpKeys(doc))
return
}
init := false
for _, field := range []string{"assignee", "reporter", "creator"} {
f, ok := fields[field].(map[string]interface{})
if !ok {
// Printf("Field %s not found\n", field)
continue
}
any := false
identity := [3]string{}
for i, k := range []string{"displayName", "name", "emailAddress"} {
v, ok := f[k].(string)
if ok {
identity[i] = v
any = true
} else {
identity[i] = Nil
}
}
if any {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[identity] = struct{}{}
}
}
comments, ok := doc.(map[string]interface{})["data"].(map[string]interface{})["comments_data"].([]interface{})
if !ok {
err = fmt.Errorf("cannot read data.comments_data from doc %+v", DumpKeys(doc))
return
}
for _, rawComment := range comments {
comment, ok := rawComment.(map[string]interface{})
if !ok {
err = fmt.Errorf("Cannot parse %+v", rawComment)
return
}
for _, field := range []string{Author, "updateAuthor"} {
f, ok := comment[field].(map[string]interface{})
if !ok {
// Printf("Field %s not found\n", field)
continue
}
any := false
identity := [3]string{}
for i, k := range []string{"displayName", "name", "emailAddress"} {
v, ok := f[k].(string)
if ok {
identity[i] = v
any = true
} else {
identity[i] = Nil
}
}
if any {
if !init {
identities = make(map[[3]string]struct{})
init = true
}
identities[identity] = struct{}{}
}
}
}
return
}
// EnrichComments - return rich item from raw item for a given author type
func EnrichComments(ctx *Ctx, ds DS, comments []interface{}, item map[string]interface{}, affs bool) (richComments []interface{}, err error) {
for _, comment := range comments {
richComment := make(map[string]interface{})
for _, field := range RawFields {
v, _ := item[field]
richComment[field] = v
}
fields := []string{"project_id", "project_key", "project_name", "issue_type", "issue_description"}
for _, field := range fields {
richComment[field] = item[field]
}
// This overwrites project passed from outside, but this was requested, we can comment this out if needed
if ctx.Project == "" {
richComment["project"] = item["project_key"]
} else {
richComment["project"] = ctx.Project
}
richComment["issue_key"] = item["key"]
richComment["issue_url"] = item["url"]
authors := []string{Author, "updateAuthor"}
for _, a := range authors {
author, ok := Dig(comment, []string{a}, false, true)
if ok {
richComment[a], _ = Dig(author, []string{"displayName"}, true, false)
tz, ok := Dig(author, []string{"timeZone"}, false, true)
if ok {
richComment[a+"_tz"] = tz
}
} else {
richComment[a] = nil
}
}
var dt time.Time
var created interface{}
for _, field := range []string{"created", "updated"} {
idt, _ := Dig(comment, []string{field}, true, false)
dt, err = TimeParseInterfaceString(idt)
if err != nil {
richComment[field] = nil
} else {
richComment[field] = dt
}
if field == "created" {
created = idt
}
}
cid, _ := Dig(comment, []string{"id"}, true, false)
richComment["body"], _ = Dig(comment, []string{"body"}, true, false)
richComment["comment_id"] = cid
iid, ok := item["id"].(string)
if !ok {
err = fmt.Errorf("missing string id field in issue %+v", DumpKeys(item))
return
}
comid, ok := cid.(string)
if !ok {
err = fmt.Errorf("missing string id field in comment %+v", DumpKeys(comment))
return
}
richComment["id"] = fmt.Sprintf("%s_comment_%s", iid, comid)
richComment["type"] = Comment
if affs {
var affsItems map[string]interface{}
itemComment := map[string]interface{}{"data": map[string]interface{}{"fields": comment}}
affsItems, err = ds.AffsItems(ctx, itemComment, []string{Author, "updateAuthor"}, created)
if err != nil {
return
}
for prop, value := range affsItems {
richComment[prop] = value
}
}
for prop, value := range CommonFields(ds, created, Comment) {
richComment[prop] = value
}
err = EnrichItem(ctx, ds, richComment)
if err != nil {
return
}
richComments = append(richComments, richComment)
}
return
}
// JiraEnrichItemsFunc - 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 JiraEnrichItemsFunc(ctx *Ctx, ds DS, thrN int, items []interface{}, docs *[]interface{}) (err error) {
if ctx.Debug > 0 {
Printf("jira enrich items %d/%d func\n", len(items), len(*docs))
}
var (