-
Notifications
You must be signed in to change notification settings - Fork 54
/
http.go
2359 lines (2121 loc) · 78.6 KB
/
http.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"
"embed"
"encoding/json"
"errors"
"fmt"
"io/fs"
"math"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
releasecontroller "github.com/openshift/release-controller/pkg/release-controller"
"github.com/openshift/release-controller/pkg/rhcos"
"github.com/blang/semver"
imagev1 "github.com/openshift/api/image/v1"
humanize "github.com/dustin/go-humanize"
"github.com/gorilla/mux"
"github.com/russross/blackfriday"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog"
"k8s.io/test-infra/prow/jira"
)
//go:embed static
var static embed.FS
var resources, _ = fs.Sub(static, "static")
var htmlPageStart = loadStaticHTML("htmlPageStart.html")
var htmlPageEnd = loadStaticHTML("htmlPageEnd.html")
const (
sectionTypeNoEpicWithFeature = "noEpicWithFeature"
sectionTypeNoFeatureWithEpic = "noFeatureWithEpic"
sectionTypeNoEpicNoFeature = "noEpicNoFeature"
sectionTypeUnknowns = "unknowns"
sectionTypeUnsortedUnknowns = "unsorted_unknowns"
)
var unlinkedIssuesSections = sets.NewString(sectionTypeNoEpicWithFeature, sectionTypeNoFeatureWithEpic, sectionTypeNoEpicNoFeature, sectionTypeUnknowns, sectionTypeUnsortedUnknowns)
var statusComplete = sets.NewString(strings.ToLower(jira.StatusOnQA), strings.ToLower(jira.StatusVerified), strings.ToLower(jira.StatusModified), strings.ToLower(jira.StatusClosed))
// Find the stream from releaseTag.
// Eg if we have release.openshift.io/releaseTag, we find the corresponding stream metadata
func (c *Controller) getStreamFromTag(tag string) (*imagev1.ImageStream, error) {
// Go through each image stream
for _, stream := range c.imageStreams {
// Get the field release.openshift.io/releaseTag from Annotations
releaseTag, ok := stream.Annotations[releasecontroller.ReleaseAnnotationReleaseTag]
if !ok {
// Image stream might not have that annotation, but that's okay. We move on.
continue
}
// We found the correct stream
if releaseTag == tag {
return stream, nil
}
}
return nil, fmt.Errorf("could not find an image stream with the tag %s", tag)
}
func (c *Controller) findReleaseStreamTags(includeStableTags bool, tags ...string) (map[string]*ReleaseStreamTag, bool) {
needed := make(map[string]*ReleaseStreamTag)
for _, tag := range tags {
if len(tag) == 0 {
continue
}
needed[tag] = nil
}
remaining := len(needed)
imageStreams, err := c.releaseLister.List(labels.Everything())
if err != nil {
return nil, false
}
var stable *releasecontroller.StableReferences
if includeStableTags {
stable = &releasecontroller.StableReferences{}
}
for _, stream := range imageStreams {
r, ok, err := releasecontroller.ReleaseDefinition(stream, c.parsedReleaseConfigCache, c.eventRecorder, *c.releaseLister)
if err != nil || !ok {
continue
}
// TODO: should be refactored to be unsortedSemanticReleaseTags
releaseTags := releasecontroller.SortedReleaseTags(r)
if includeStableTags {
if version, err := releasecontroller.SemverParseTolerant(r.Config.Name); err == nil || r.Config.As == releasecontroller.ReleaseConfigModeStable {
stable.Releases = append(stable.Releases, releasecontroller.StableRelease{
Release: r,
Version: version,
Versions: releasecontroller.NewSemanticVersions(releaseTags),
})
}
}
if includeStableTags && remaining == 0 {
continue
}
for i, tag := range releaseTags {
if needs, ok := needed[tag.Name]; ok && needs == nil {
needed[tag.Name] = &ReleaseStreamTag{
Release: r,
Tag: tag,
Previous: findPreviousRelease(tag, releaseTags[i+1:], r),
PreviousRelease: r,
Older: releaseTags[i+1:],
Stable: stable,
}
remaining--
if !includeStableTags && remaining == 0 {
return needed, true
}
}
}
}
if includeStableTags {
sort.Sort(stable.Releases)
}
return needed, remaining == 0
}
func (c *Controller) endOfLifePrefixes() sets.String {
imageStreams, err := c.releaseLister.List(labels.Everything())
if err != nil {
return nil
}
endOfLifePrefixes := sets.NewString()
for _, stream := range imageStreams {
r, ok, err := releasecontroller.ReleaseDefinition(stream, c.parsedReleaseConfigCache, c.eventRecorder, *c.releaseLister)
if err != nil || !ok {
continue
}
if r.Config.EndOfLife {
if version, err := releasecontroller.SemverParseTolerant(r.Config.Name); err == nil {
endOfLifePrefixes.Insert(fmt.Sprintf("%d.%d", version.Major, version.Minor))
}
continue
}
}
return endOfLifePrefixes
}
func (c *Controller) userInterfaceHandler() http.Handler {
mux := mux.NewRouter()
mux.HandleFunc("/", c.httpReleases)
mux.HandleFunc("/graph", c.graphHandler)
mux.HandleFunc("/changelog", c.httpReleaseChangelog)
mux.HandleFunc("/archive/graph", c.httpGraphSave)
mux.HandleFunc("/releasetag/{tag}/json", c.httpReleaseInfoJson)
mux.HandleFunc("/releasetag/{tag}", c.httpReleaseInfo)
mux.HandleFunc("/releasestream/{release}", c.httpReleaseStreamTable)
mux.HandleFunc("/releasestream/{release}/release/{tag}", c.httpReleaseInfo)
mux.HandleFunc("/releasestream/{release}/release/{tag}/download", c.httpReleaseInfoDownload)
mux.HandleFunc("/releasestream/{release}/inconsistency/{tag}", c.httpInconsistencyInfo)
mux.HandleFunc("/releasestream/{release}/latest", c.httpReleaseLatest)
mux.HandleFunc("/releasestream/{release}/latest/download", c.httpReleaseLatestDownload)
mux.HandleFunc("/releasestream/{release}/candidates", c.httpReleaseCandidateList)
mux.HandleFunc("/dashboards/overview", c.httpDashboardOverview)
mux.HandleFunc("/dashboards/compare", c.httpDashboardCompare)
// APIs
mux.HandleFunc("/api/v1/releasestream/{release}/tags", c.apiReleaseTags)
mux.HandleFunc("/api/v1/releasestream/{release}/latest", c.apiReleaseLatest)
mux.HandleFunc("/api/v1/releasestream/{release}/candidate", c.apiReleaseCandidate)
mux.HandleFunc("/api/v1/releasestream/{release}/release/{tag}", c.apiReleaseInfo)
mux.HandleFunc("/api/v1/releasestream/{release}/config", c.apiReleaseConfig)
mux.HandleFunc("/api/v1/releasestreams/accepted", c.apiAcceptedStreams)
mux.HandleFunc("/api/v1/releasestreams/rejected", c.apiRejectedStreams)
mux.HandleFunc("/api/v1/releasestreams/all", c.apiAllStreams)
mux.HandleFunc("/api/v1/features/{tag}", c.apiFeatureInfo)
mux.HandleFunc("/features/{tag}", c.httpFeatureInfo)
// static files
mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.FS(resources))))
return mux
}
func (c *Controller) releaseFeatureInfo(tagInfo *releaseTagInfo) ([]*FeatureTree, error) {
// Get change log
changeLogJSON := renderResult{}
c.changeLogWorker(&changeLogJSON, tagInfo, "json")
if changeLogJSON.err != nil {
return nil, changeLogJSON.err
}
var changeLog releasecontroller.ChangeLog
if err := json.Unmarshal([]byte(changeLogJSON.out), &changeLog); err != nil {
return nil, err
}
// Get issue details
info, err := c.releaseInfo.IssuesInfo(changeLogJSON.out)
if err != nil {
return nil, err
}
var mapIssueDetails map[string]releasecontroller.IssueDetails
if err := json.Unmarshal([]byte(info), &mapIssueDetails); err != nil {
return nil, err
}
// Create feature trees
var featureTrees []*FeatureTree
for key, details := range mapIssueDetails {
if details.IssueType != releasecontroller.JiraTypeFeature {
continue
}
featureTree := addChild(key, details, &changeLog.To.Created)
featureTrees = append(featureTrees, featureTree)
}
linkedIssues := sets.Set[string]{}
visited := make(map[string]bool)
if !GetFeatureInfo(featureTrees, mapIssueDetails, &changeLog.To.Created, &linkedIssues, 10000, visited) {
return nil, errors.New("failed getting the features information, cycle limit reached! ")
}
var noFeatureWithEpic []*FeatureTree
var unknowns []*FeatureTree
for issue, details := range mapIssueDetails {
if linkedIssues.Has(issue) || details.IssueType == releasecontroller.JiraTypeEpic || details.IssueType == releasecontroller.JiraTypeFeature || details.IssueType == releasecontroller.JiraTypeMarketProblem {
continue
}
feature := addChild(issue, details, &changeLog.To.Created)
if details.Feature == "" && details.Epic == "" && details.Parent == "" {
feature.NotLinkedType = sectionTypeNoEpicNoFeature
featureTrees = append(featureTrees, feature)
} else if details.Epic != "" {
noFeatureWithEpic = append(noFeatureWithEpic, feature)
} else {
feature.NotLinkedType = sectionTypeUnknowns
unknowns = append(unknowns, feature)
}
}
epicWithoutFeatureMap := make(map[string][]*FeatureTree, 0)
for _, child := range noFeatureWithEpic {
epicWithoutFeatureMap[child.Epic] = append(epicWithoutFeatureMap[child.Epic], child)
}
for epic, children := range epicWithoutFeatureMap {
f := &FeatureTree{
IssueKey: epic,
Summary: mapIssueDetails[epic].Summary,
Description: mapIssueDetails[epic].Description,
ReleaseNotes: mapIssueDetails[epic].ReleaseNotes,
Type: mapIssueDetails[epic].IssueType,
Epic: mapIssueDetails[epic].Epic,
Feature: mapIssueDetails[epic].Feature,
Parent: mapIssueDetails[epic].Parent,
NotLinkedType: sectionTypeNoFeatureWithEpic,
PRs: mapIssueDetails[epic].PRs,
IncludedInBuild: statusOnBuild(&changeLog.To.Created, mapIssueDetails[epic].ResolutionDate, mapIssueDetails[epic].Transitions),
Children: children,
Demos: mapIssueDetails[epic].Demos,
}
featureTrees = append(featureTrees, f)
}
// TODO - find a better way to do this, this it is to expensive
redistributedUnknowns := sets.Set[string]{}
for _, unknown := range unknowns {
if unknown.Parent != "" {
redistributeUnknowns(featureTrees, unknown.Parent, unknown, &redistributedUnknowns, 10000)
}
if unknown.Epic != "" {
redistributeUnknowns(featureTrees, unknown.Epic, unknown, &redistributedUnknowns, 10000)
}
if unknown.Feature != "" {
redistributeUnknowns(featureTrees, unknown.Feature, unknown, &redistributedUnknowns, 10000)
}
}
for _, ticket := range unknowns {
if !redistributedUnknowns.Has(ticket.IssueKey) {
ticket.NotLinkedType = sectionTypeUnsortedUnknowns
featureTrees = append(featureTrees, ticket)
}
}
// Remove every tree from sectionTypeNoEpicNoFeature that has no PRs, since it implies that it is not part of the
// change log. Specifically, cards within the parent/epics/features group are gathered for the featureTree but are
// not linked properly (e.g., an Epic that links directly to a "Market Problem" instead of a Feature, and Feature
// is the root).
toRemove := sets.Set[string]{}
for _, ticket := range featureTrees {
if ticket.NotLinkedType == sectionTypeNoEpicNoFeature {
if isPRsEmpty(ticket) {
toRemove.Insert(ticket.IssueKey)
}
}
}
return removeUnnecessaryTrees(featureTrees, toRemove), nil
}
func removeUnnecessaryTrees(slice []*FeatureTree, toRemove sets.Set[string]) []*FeatureTree {
newFeatureTree := make([]*FeatureTree, 0)
for _, feature := range slice {
if !toRemove.Has(feature.IssueKey) {
newFeatureTree = append(newFeatureTree, feature)
}
}
return newFeatureTree
}
func isPRsEmpty(ft *FeatureTree) bool {
if len(ft.PRs) > 0 {
return false
}
for _, child := range ft.Children {
if !isPRsEmpty(child) {
return false
}
}
return true
}
func redistributeUnknowns(slice []*FeatureTree, key string, feature *FeatureTree, s *sets.Set[string], limit int) bool {
if limit <= 0 {
klog.Errorf("breaking the recursion: limit reached for the redistributeUnknowns func! This might indicate a cyclic tree!")
return false
}
for _, node := range slice {
if node.IssueKey == key {
node.Children = append(node.Children, feature)
s.Insert(feature.IssueKey)
return true
}
redistributeUnknowns(node.Children, key, feature, s, limit-1)
}
return false
}
func GetFeatureInfo(ft []*FeatureTree, issues map[string]releasecontroller.IssueDetails, buildTimeStamp *time.Time, linkedIssues *sets.Set[string], limit int, visited map[string]bool) bool {
// add a fail-safe to protect against stack-overflows caused by a cyclic link. If the limit has been reached, the
//function will return immediately without making any further recursive calls.
if limit <= 0 {
klog.Errorf("breaking the recursion: limit reached for the GetFeatureInfo func! This might indicate a cyclic tree!")
return false
}
for _, child := range ft {
// Check if the child has already been visited. This will protect against cyclic links and redundant work
if visited[child.IssueKey] {
klog.Infof("Skipping child %v as it has already been visited", child.IssueKey)
continue
}
visited[child.IssueKey] = true // mark the child as visited
var children []*FeatureTree
for issueKey, issueDetails := range issues {
var featureTree *FeatureTree
if child.Type == releasecontroller.JiraTypeFeature && issueDetails.Feature == child.IssueKey {
featureTree = addChild(issueKey, issueDetails, buildTimeStamp)
} else if child.Type == releasecontroller.JiraTypeEpic && issueDetails.Epic == child.IssueKey {
featureTree = addChild(issueKey, issueDetails, buildTimeStamp)
linkedIssues.Insert(issueKey)
} else {
if issueDetails.Parent == child.IssueKey {
featureTree = addChild(issueKey, issueDetails, buildTimeStamp)
linkedIssues.Insert(issueKey)
}
}
if featureTree != nil {
children = append(children, featureTree)
}
}
child.Children = children
GetFeatureInfo(child.Children, issues, buildTimeStamp, linkedIssues, limit-1, visited)
}
return true
}
func addChild(issueKey string, issueDetails releasecontroller.IssueDetails, buildTimeStamp *time.Time) *FeatureTree {
return &FeatureTree{
IssueKey: issueKey,
Summary: issueDetails.Summary,
Description: issueDetails.Description,
ReleaseNotes: issueDetails.ReleaseNotes,
Type: issueDetails.IssueType,
Epic: issueDetails.Epic,
Feature: issueDetails.Feature,
Parent: issueDetails.Parent,
IncludedInBuild: statusOnBuild(buildTimeStamp, issueDetails.ResolutionDate, issueDetails.Transitions),
PRs: issueDetails.PRs,
Children: nil,
Demos: issueDetails.Demos,
}
}
func (c *Controller) apiFeatureInfo(w http.ResponseWriter, req *http.Request) {
tagInfo, err := c.getReleaseTagInfo(req)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
featureTrees, err := c.releaseFeatureInfo(tagInfo)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := json.MarshalIndent(&featureTrees, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
}
func statusOnBuild(buildTimeStamp *time.Time, issueTimestamp time.Time, transitions []releasecontroller.Transition) bool {
if !issueTimestamp.IsZero() && issueTimestamp.Before(*buildTimeStamp) {
return true
}
status := getPastStatus(transitions, buildTimeStamp)
if statusComplete.Has(strings.ToLower(status)) {
return true
}
return false
}
func getPastStatus(transitions []releasecontroller.Transition, buildTime *time.Time) string {
status := "New"
for _, t := range transitions {
if t.Time.After(*buildTime) {
break
}
status = t.ToStatus
}
return status
}
type FeatureTree struct {
IssueKey string `json:"key"`
Summary string `json:"summary"`
Description string `json:"description"`
ReleaseNotes string `json:"release_notes,omitempty"`
Type string `json:"type"`
NotLinkedType string `json:"-"`
IncludedInBuild bool `json:"included_in_build"`
PRs []string `json:"prs,omitempty"`
Epic string `json:"-"`
Feature string `json:"-"`
Parent string `json:"-"`
Children []*FeatureTree `json:"children,omitempty"`
Demos []string `json:"demos,omitempty"`
}
func (c *Controller) urlForArtifacts(tagName string) (string, bool) {
if len(c.artifactsHost) == 0 {
return "", false
}
return fmt.Sprintf("https://%s/%s", c.artifactsHost, url.PathEscape(tagName)), true
}
func (c *Controller) locateLatest(w http.ResponseWriter, req *http.Request) (*releasecontroller.Release, *imagev1.TagReference, bool) {
vars := mux.Vars(req)
streamName := vars["release"]
var constraint semver.Range
if inString := req.URL.Query().Get("in"); len(inString) > 0 {
r, err := semver.ParseRange(inString)
if err != nil {
http.Error(w, fmt.Sprintf("error: ?in must be a valid semantic version range: %v", err), http.StatusBadRequest)
return nil, nil, false
}
constraint = r
}
var relativeIndex int
if relativeIndexString := req.URL.Query().Get("rel"); len(relativeIndexString) > 0 {
i, err := strconv.Atoi(relativeIndexString)
if err != nil {
http.Error(w, fmt.Sprintf("error: ?rel must be non-negative integer: %v", err), http.StatusBadRequest)
return nil, nil, false
}
if i < 0 {
http.Error(w, "error: ?rel must be non-negative integer", http.StatusBadRequest)
return nil, nil, false
}
relativeIndex = i
}
var releasePrefix string
if inString := req.URL.Query().Get("prefix"); len(inString) > 0 {
releasePrefix = inString
}
r, latest, err := releasecontroller.LatestForStream(c.parsedReleaseConfigCache, c.eventRecorder, c.releaseLister, streamName, constraint, relativeIndex, releasePrefix)
if err != nil {
code := http.StatusInternalServerError
if err == releasecontroller.ErrStreamNotFound || err == releasecontroller.ErrStreamTagNotFound {
code = http.StatusNotFound
}
http.Error(w, err.Error(), code)
return nil, nil, false
}
return r, latest, true
}
func (c *Controller) apiReleaseLatest(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
r, latest, ok := c.locateLatest(w, req)
if !ok {
return
}
downloadURL, _ := c.urlForArtifacts(latest.Name)
resp := releasecontroller.APITag{
Name: latest.Name,
PullSpec: releasecontroller.FindPublicImagePullSpec(r.Target, latest.Name),
DownloadURL: downloadURL,
Phase: latest.Annotations[releasecontroller.ReleaseAnnotationPhase],
}
switch req.URL.Query().Get("format") {
case "pullSpec":
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, resp.PullSpec)
case "downloadURL":
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, resp.DownloadURL)
case "name":
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, resp.Name)
case "", "json":
data, err := json.MarshalIndent(&resp, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
fmt.Fprintln(w)
default:
http.Error(w, fmt.Sprintf("error: Must specify one of '', 'json', 'pullSpec', 'name', or 'downloadURL"), http.StatusBadRequest)
}
}
func (c *Controller) locateStream(streamName string, phases ...string) (*ReleaseStream, error) {
imageStreams, err := c.releaseLister.List(labels.Everything())
if err != nil {
return nil, err
}
for _, stream := range imageStreams {
r, ok, err := releasecontroller.ReleaseDefinition(stream, c.parsedReleaseConfigCache, c.eventRecorder, *c.releaseLister)
if err != nil || !ok {
continue
}
if r.Config.Name != streamName {
continue
}
// find all accepted tags, then sort by semantic version
tags := releasecontroller.UnsortedSemanticReleaseTags(r, phases...)
sort.Sort(tags)
return &ReleaseStream{
Release: r,
Tags: tags.Tags(),
}, nil
}
return nil, releasecontroller.ErrStreamNotFound
}
func (c *Controller) apiReleaseTags(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
vars := mux.Vars(req)
streamName := vars["release"]
filterPhase := req.URL.Query()["phase"]
r, err := c.locateStream(streamName)
if err != nil {
if err == releasecontroller.ErrStreamNotFound {
http.Error(w, fmt.Sprintf("Unable to find release %s", streamName), http.StatusNotFound)
} else {
http.Error(w, fmt.Sprintf("Unable to find release %s: %v", streamName, err), http.StatusInternalServerError)
}
return
}
var tags []releasecontroller.APITag
for _, tag := range r.Tags {
downloadURL, _ := c.urlForArtifacts(tag.Name)
phase := tag.Annotations[releasecontroller.ReleaseAnnotationPhase]
if len(filterPhase) > 0 && !releasecontroller.ContainsString(filterPhase, phase) {
continue
}
tags = append(tags, releasecontroller.APITag{
Name: tag.Name,
PullSpec: releasecontroller.FindPublicImagePullSpec(r.Release.Target, tag.Name),
DownloadURL: downloadURL,
Phase: phase,
})
}
resp := releasecontroller.APIRelease{
Name: r.Release.Config.Name,
Tags: tags,
}
switch req.URL.Query().Get("format") {
case "", "json":
data, err := json.MarshalIndent(&resp, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
fmt.Fprintln(w)
default:
http.Error(w, fmt.Sprintf("error: Must specify one of '', 'json', 'pullSpec', 'name', or 'downloadURL"), http.StatusBadRequest)
}
}
func (c *Controller) apiReleaseInfo(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
tagInfo, err := c.getReleaseTagInfo(req)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
verificationJobs, msg := c.getVerificationJobs(*tagInfo.Info.Tag, tagInfo.Info.Release)
if len(msg) > 0 {
klog.V(4).Infof("Unable to retrieve verification job results for: %s", tagInfo.Tag)
}
var changeLog []byte
var changeLogJson releasecontroller.ChangeLog
if tagInfo.Info.Previous != nil && len(tagInfo.PreviousTagPullSpec) > 0 && len(tagInfo.TagPullSpec) > 0 {
var wg sync.WaitGroup
renderHTML := renderResult{}
renderJSON := renderResult{}
for k, v := range map[string]*renderResult{
"html": &renderHTML,
"json": &renderJSON,
} {
wg.Add(1)
format := k
result := v
go func() {
defer wg.Done()
c.changeLogWorker(result, tagInfo, format)
}()
}
wg.Wait()
if renderHTML.err == nil {
result := blackfriday.Run([]byte(renderHTML.out))
// make our links targets
result = reInternalLink.ReplaceAllFunc(result, func(s []byte) []byte {
return []byte(`<a target="_blank" ` + string(bytes.TrimPrefix(s, []byte("<a "))))
})
changeLog = result
}
if renderJSON.err == nil {
err = json.Unmarshal([]byte(renderJSON.out), &changeLogJson)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
summary := releasecontroller.APIReleaseInfo{
Name: tagInfo.Tag,
Phase: tagInfo.Info.Tag.Annotations[releasecontroller.ReleaseAnnotationPhase],
Results: verificationJobs,
UpgradesTo: c.graph.UpgradesTo(tagInfo.Tag),
UpgradesFrom: c.graph.UpgradesFrom(tagInfo.Tag),
ChangeLog: changeLog,
ChangeLogJson: changeLogJson,
}
data, err := json.MarshalIndent(&summary, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
fmt.Fprintln(w)
}
func (c *Controller) changeLogWorker(result *renderResult, tagInfo *releaseTagInfo, format string) {
ch := make(chan renderResult)
// run the changelog in a goroutine because it may take significant time
go c.getChangeLog(ch, tagInfo.PreviousTagPullSpec, tagInfo.Info.Previous.Name, tagInfo.TagPullSpec, tagInfo.Info.Tag.Name, format)
select {
case *result = <-ch:
case <-time.After(500 * time.Millisecond):
select {
case *result = <-ch:
case <-time.After(15 * time.Second):
result.err = fmt.Errorf("the changelog is still loading, if this is the first access it may take several minutes to clone all repositories")
}
}
}
func (c *Controller) httpGraphSave(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Encoding", "gzip")
if err := c.graph.Save(w); err != nil {
http.Error(w, fmt.Sprintf("unable to save graph: %v", err), http.StatusInternalServerError)
}
}
func (c *Controller) httpReleaseChangelog(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
var isHtml, isJson bool
switch req.URL.Query().Get("format") {
case "html":
isHtml = true
case "json":
isJson = true
case "markdown", "":
default:
http.Error(w, fmt.Sprintf("unrecognized format= string: html, json, markdown, empty accepted"), http.StatusBadRequest)
return
}
from := req.URL.Query().Get("from")
if len(from) == 0 {
http.Error(w, fmt.Sprintf("from must be set to a valid tag"), http.StatusBadRequest)
return
}
to := req.URL.Query().Get("to")
if len(to) == 0 {
http.Error(w, fmt.Sprintf("to must be set to a valid tag"), http.StatusBadRequest)
return
}
tags, ok := c.findReleaseStreamTags(false, from, to)
if !ok {
for k, v := range tags {
if v == nil {
http.Error(w, fmt.Sprintf("could not find tag: %s", k), http.StatusBadRequest)
return
}
}
}
fromBase := tags[from].Release.Target.Status.PublicDockerImageRepository
if len(fromBase) == 0 {
http.Error(w, fmt.Sprintf("release target %s does not have a configured registry", tags[from].Release.Target.Name), http.StatusBadRequest)
return
}
toBase := tags[to].Release.Target.Status.PublicDockerImageRepository
if len(toBase) == 0 {
http.Error(w, fmt.Sprintf("release target %s does not have a configured registry", tags[to].Release.Target.Name), http.StatusBadRequest)
return
}
out, err := c.releaseInfo.ChangeLog(fromBase+":"+from, toBase+":"+to, isJson)
if err != nil {
http.Error(w, fmt.Sprintf("Internal error\n%v", err), http.StatusInternalServerError)
return
}
// Enabling CORS (OCPCRT-290)
w.Header().Set("Access-Control-Allow-Origin", "*")
if isHtml {
result := blackfriday.Run([]byte(out))
w.Header().Set("Content-Type", "text/html;charset=UTF-8")
fmt.Fprintf(w, htmlPageStart, template.HTMLEscapeString(fmt.Sprintf("Change log for %s", to)))
w.Write(result)
fmt.Fprintln(w, htmlPageEnd)
return
}
if isJson {
// There is an inconsistency with what is returned from ReleaseInfo (amd64) and what
// needs to be passed into the RHCOS diff engine (x86_64).
var architecture, archExtension string
if c.architecture == "amd64" {
architecture = "x86_64"
} else if c.architecture == "arm64" {
architecture = "aarch64"
archExtension = fmt.Sprintf("-%s", architecture)
} else {
architecture = c.architecture
archExtension = fmt.Sprintf("-%s", architecture)
}
out, err = rhcos.TransformJsonOutput(out, architecture, archExtension)
if err != nil {
http.Error(w, fmt.Sprintf("Internal error\n%v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, out)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, out)
}
func (c *Controller) httpReleaseInfoJson(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
vars := mux.Vars(req)
tag := vars["tag"]
if len(tag) == 0 {
http.Error(w, fmt.Sprintf("tag must be specified"), http.StatusBadRequest)
return
}
tags, ok := c.findReleaseStreamTags(false, tag)
if !ok {
http.Error(w, fmt.Sprintf("could not find tag: %s", tag), http.StatusBadRequest)
return
}
tagPullSpec := releasecontroller.FindPublicImagePullSpec(tags[tag].Release.Target, tag)
if len(tagPullSpec) == 0 {
http.Error(w, fmt.Sprintf("could not find pull spec for tag %s in image stream %s", tag, tags[tag].Release.Target.Name), http.StatusBadRequest)
return
}
imageInfo, err := releasecontroller.GetImageInfo(c.releaseInfo, c.architecture, tagPullSpec)
if err != nil {
http.Error(w, fmt.Sprintf("unable to determine image info for %s: %v", tagPullSpec, err), http.StatusBadRequest)
return
}
out, err := c.releaseInfo.ReleaseInfo(imageInfo.GenerateDigestPullSpec())
if err != nil {
http.Error(w, fmt.Sprintf("Internal error: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, out)
}
func (c *Controller) httpReleaseInfoDownload(w http.ResponseWriter, req *http.Request) {
start := time.Now()
defer func() { klog.V(4).Infof("rendered in %s", time.Now().Sub(start)) }()
vars := mux.Vars(req)
release := vars["release"]
tag := vars["tag"]
tags, ok := c.findReleaseStreamTags(true, tag)
if !ok {
http.Error(w, fmt.Sprintf("Unable to find release tag %s, it may have been deleted", tag), http.StatusNotFound)
return
}
info := tags[tag]
if len(release) > 0 && info.Release.Config.Name != release {
http.Error(w, fmt.Sprintf("Release tag %s does not belong to release %s", tag, release), http.StatusNotFound)
return
}
u, ok := c.urlForArtifacts(tag)
if !ok {
http.Error(w, "No artifacts download URL is configured, cannot show download link", http.StatusNotFound)
return
}
http.Redirect(w, req, u, http.StatusFound)
}
type releaseTagInfo struct {
Tag string
Info *ReleaseStreamTag
TagPullSpec string
PreviousTagPullSpec string
}
func (c *Controller) getReleaseTagInfo(req *http.Request) (*releaseTagInfo, error) {
vars := mux.Vars(req)
release := vars["release"]
tag := vars["tag"]
from := req.URL.Query().Get("from")
tags, ok := c.findReleaseStreamTags(true, tag, from)
if !ok {
return nil, fmt.Errorf("unable to find release tag %s, it may have been deleted", tag)
}
info := tags[tag]
if len(release) > 0 && info.Release.Config.Name != release {
return nil, fmt.Errorf("release tag %s does not belong to release %s", tag, release)
}
if previous := tags[from]; previous != nil {
info.Previous = previous.Tag
info.PreviousRelease = previous.Release
}
if info.Previous == nil && len(info.Older) > 0 {
info.Previous = info.Older[0]
info.PreviousRelease = info.Release
}
if info.Previous == nil {
if version, err := semver.Parse(info.Tag.Name); err == nil {
for _, release := range info.Stable.Releases {
if release.Version.Major == version.Major && release.Version.Minor == version.Minor && len(release.Versions) > 0 {
info.Previous = release.Versions[0].Tag
info.PreviousRelease = release.Release
break
}
}
}
}
// require public pull specs because we can't get the x509 cert for the internal registry without service-ca.crt
tagPull := releasecontroller.FindPublicImagePullSpec(info.Release.Target, info.Tag.Name)
var previousTagPull string
if info.Previous != nil {
previousTagPull = releasecontroller.FindPublicImagePullSpec(info.PreviousRelease.Target, info.Previous.Name)
}
return &releaseTagInfo{
Tag: tag,
Info: info,
TagPullSpec: tagPull,
PreviousTagPullSpec: previousTagPull,
}, nil
}
type Sections struct {
Tickets []*FeatureTree
Title string
Header string
Note string
}
type httpFeatureData struct {
DisplaySections []SectionInfo
From string
To string
}
type SectionInfo struct {
Name string
Section Sections
}
func sortByTitle(features []*FeatureTree) {
sort.Slice(features, func(i, j int) bool {
return features[i].IssueKey < features[j].IssueKey
})
}
func (c *Controller) httpFeatureInfo(w http.ResponseWriter, req *http.Request) {
tagInfo, err := c.getReleaseTagInfo(req)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
from := req.URL.Query().Get("from")