|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "math" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "strings" |
| 10 | + "text/template" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/prometheus/client_golang/api" |
| 14 | + v1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 15 | + "github.com/prometheus/common/model" |
| 16 | +) |
| 17 | + |
| 18 | +var ( |
| 19 | + summaryTemplate = "summary.md.tmpl" |
| 20 | + alertsTemplate = "alert.md.tmpl" |
| 21 | + chartTemplate = "mermaid_chart.md.tmpl" |
| 22 | + defaultPromUrl = "http://localhost:30900" |
| 23 | +) |
| 24 | + |
| 25 | +type summaryAlerts struct { |
| 26 | + FiringAlerts []summaryAlert |
| 27 | + PendingAlerts []summaryAlert |
| 28 | +} |
| 29 | + |
| 30 | +type summaryAlert struct { |
| 31 | + v1.Alert |
| 32 | + Name string |
| 33 | + Description string |
| 34 | +} |
| 35 | + |
| 36 | +type xychart struct { |
| 37 | + Title string |
| 38 | + YMax float64 |
| 39 | + YMin float64 |
| 40 | + YLabel string |
| 41 | + Data string |
| 42 | +} |
| 43 | + |
| 44 | +type githubSummary struct { |
| 45 | + client api.Client |
| 46 | + Pods []string |
| 47 | +} |
| 48 | + |
| 49 | +func NewSummary(c api.Client, pods ...string) githubSummary { |
| 50 | + return githubSummary{ |
| 51 | + client: c, |
| 52 | + Pods: pods, |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// PerformanceQuery queries the prometheus server and generates a mermaid xychart with the data |
| 57 | +func (s githubSummary) PerformanceQuery(title, pod, query string, yLabel string, scaler float64) (string, error) { |
| 58 | + v1api := v1.NewAPI(s.client) |
| 59 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 60 | + defer cancel() |
| 61 | + |
| 62 | + fullQuery := fmt.Sprintf(query, pod) |
| 63 | + result, warnings, err := v1api.Query(ctx, fullQuery, time.Now()) |
| 64 | + if err != nil { |
| 65 | + return "", err |
| 66 | + } else if len(warnings) > 0 { |
| 67 | + fmt.Printf("warnings returned from performance query; query=%s, warnings=%v", fullQuery, warnings) |
| 68 | + } else if result.Type() != model.ValMatrix { |
| 69 | + return "", fmt.Errorf("incompatible result type; need: %s, got: %s", model.ValMatrix, result.Type().String()) |
| 70 | + } |
| 71 | + |
| 72 | + matrix, ok := result.(model.Matrix) |
| 73 | + if !ok { |
| 74 | + return "", fmt.Errorf("typecast for metrics samples failed; aborting") |
| 75 | + } else if len(matrix) > 1 { |
| 76 | + return "", fmt.Errorf("expected 1 set of results; got: %d", len(matrix)) |
| 77 | + } |
| 78 | + chart := xychart{ |
| 79 | + Title: title, |
| 80 | + YLabel: yLabel, |
| 81 | + YMax: math.SmallestNonzeroFloat64, |
| 82 | + YMin: math.MaxFloat64, |
| 83 | + } |
| 84 | + formattedData := make([]string, 0) |
| 85 | + // matrix does not allow [] access, so we just do one iteration for the single result |
| 86 | + for _, metric := range matrix { |
| 87 | + if len(metric.Values) < 1 { |
| 88 | + return "", fmt.Errorf("expected at least one data point; got: %d", len(metric.Values)) |
| 89 | + } |
| 90 | + for _, sample := range metric.Values { |
| 91 | + floatSample := float64(sample.Value) * scaler |
| 92 | + formattedData = append(formattedData, fmt.Sprintf("%f", floatSample)) |
| 93 | + if floatSample > chart.YMax { |
| 94 | + chart.YMax = floatSample |
| 95 | + } |
| 96 | + if floatSample < chart.YMin { |
| 97 | + chart.YMin = floatSample |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + // Add some padding |
| 102 | + chart.YMax = (chart.YMax + (math.Abs(chart.YMax) * 0.05)) |
| 103 | + chart.YMin = (chart.YMin - (math.Abs(chart.YMin) * 0.05)) |
| 104 | + // Pretty print the values, ex: [1,2,3,4] |
| 105 | + chart.Data = strings.ReplaceAll(fmt.Sprintf("%v", formattedData), " ", ",") |
| 106 | + |
| 107 | + return executeTemplate(chartTemplate, chart) |
| 108 | +} |
| 109 | + |
| 110 | +// Alerts queries the prometheus server for alerts and generates markdown output for anything found. |
| 111 | +// If no alerts are found, the alerts section will contain only "None." in the final output. |
| 112 | +func (s githubSummary) Alerts() (string, error) { |
| 113 | + v1api := v1.NewAPI(s.client) |
| 114 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 115 | + defer cancel() |
| 116 | + result, err := v1api.Alerts(ctx) |
| 117 | + if err != nil { |
| 118 | + fmt.Printf("Error querying Prometheus: %v\n", err) |
| 119 | + os.Exit(1) |
| 120 | + } |
| 121 | + |
| 122 | + firingAlerts := make([]summaryAlert, 0) |
| 123 | + pendingAlerts := make([]summaryAlert, 0) |
| 124 | + if len(result.Alerts) > 0 { |
| 125 | + for _, a := range result.Alerts { |
| 126 | + aConv := summaryAlert{ |
| 127 | + Alert: a, |
| 128 | + Name: string(a.Labels["alertname"]), |
| 129 | + Description: string(a.Annotations["description"]), |
| 130 | + } |
| 131 | + switch a.State { |
| 132 | + case v1.AlertStateFiring: |
| 133 | + firingAlerts = append(firingAlerts, aConv) |
| 134 | + case v1.AlertStatePending: |
| 135 | + pendingAlerts = append(pendingAlerts, aConv) |
| 136 | + // Ignore AlertStateInactive; the alerts endpoint doesn't return them |
| 137 | + } |
| 138 | + } |
| 139 | + } else { |
| 140 | + return "None.", nil |
| 141 | + } |
| 142 | + |
| 143 | + return executeTemplate(alertsTemplate, summaryAlerts{ |
| 144 | + FiringAlerts: firingAlerts, |
| 145 | + PendingAlerts: pendingAlerts, |
| 146 | + }) |
| 147 | +} |
| 148 | + |
| 149 | +func executeTemplate(templateFile string, obj any) (string, error) { |
| 150 | + wd, err := os.Getwd() |
| 151 | + if err != nil { |
| 152 | + return "", fmt.Errorf("failed to get working directory: %w", err) |
| 153 | + } |
| 154 | + tmpl, err := template.New(templateFile).ParseGlob(filepath.Join(wd, "../utils/templates", templateFile)) |
| 155 | + if err != nil { |
| 156 | + return "", err |
| 157 | + } |
| 158 | + buffer := new(strings.Builder) |
| 159 | + err = tmpl.Execute(buffer, obj) |
| 160 | + if err != nil { |
| 161 | + return "", err |
| 162 | + } |
| 163 | + return buffer.String(), nil |
| 164 | +} |
| 165 | + |
| 166 | +// PrintSummary executes the main summary template, generating the full test report. |
| 167 | +// The markdown is template-driven; the summary methods are called from within the |
| 168 | +// template. This allows us to add or change queries (hopefully) without needing to |
| 169 | +// touch code. The summary will be output to a file supplied by the env target. |
| 170 | +func PrintSummary(envTarget string) error { |
| 171 | + client, err := api.NewClient(api.Config{ |
| 172 | + Address: defaultPromUrl, |
| 173 | + }) |
| 174 | + if err != nil { |
| 175 | + fmt.Printf("Error creating prometheus client: %v\n", err) |
| 176 | + os.Exit(1) |
| 177 | + } |
| 178 | + |
| 179 | + summary := NewSummary(client, "operator-controller", "catalogd") |
| 180 | + summaryMarkdown, err := executeTemplate(summaryTemplate, summary) |
| 181 | + if err != nil { |
| 182 | + return err |
| 183 | + } |
| 184 | + if path := os.Getenv(envTarget); path != "" { |
| 185 | + err = os.WriteFile(path, []byte(summaryMarkdown), 0o600) |
| 186 | + if err != nil { |
| 187 | + return err |
| 188 | + } |
| 189 | + fmt.Printf("Test summary output to %s successful\n", envTarget) |
| 190 | + } else { |
| 191 | + fmt.Printf("No summary output specified; skipping") |
| 192 | + } |
| 193 | + return nil |
| 194 | +} |
0 commit comments