-
Notifications
You must be signed in to change notification settings - Fork 90
/
gather.go
271 lines (240 loc) · 9.58 KB
/
gather.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
// Package gather contains common gathering logic for all gatherers
package gather
import (
"context"
"fmt"
"runtime"
"time"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"github.com/openshift/api/config/v1alpha1"
"github.com/openshift/insights-operator/pkg/anonymization"
"github.com/openshift/insights-operator/pkg/config/configobserver"
"github.com/openshift/insights-operator/pkg/gatherers"
"github.com/openshift/insights-operator/pkg/gatherers/clusterconfig"
"github.com/openshift/insights-operator/pkg/gatherers/conditional"
"github.com/openshift/insights-operator/pkg/gatherers/workloads"
"github.com/openshift/insights-operator/pkg/insights/insightsclient"
"github.com/openshift/insights-operator/pkg/record"
"github.com/openshift/insights-operator/pkg/recorder"
"github.com/openshift/insights-operator/pkg/types"
"github.com/openshift/insights-operator/pkg/utils"
)
// norevive
const (
// AllGatherersConst is used to specify in the config that we want to enable
// all gathering functions from all gatherers
AllGatherersConst = "ALL"
)
var programStartTime = time.Now()
// GathererFunctionReport contains the information about a specific gathering function
type GathererFunctionReport struct {
FuncName string `json:"name"`
Duration int64 `json:"duration_in_ms"`
RecordsCount int `json:"records_count"`
Errors []string `json:"errors"`
Warnings []string `json:"warnings"`
Panic interface{} `json:"panic"`
}
// ArchiveMetadata contains the information about the archive and all its' gatherers
type ArchiveMetadata struct {
// info about gathering functions.
StatusReports []GathererFunctionReport `json:"status_reports"`
// MemoryAlloc is the amount of memory taken by heap objects after processing the records
MemoryAlloc uint64 `json:"memory_alloc_bytes"`
// Uptime is the number of seconds from the program start till the point when metadata was created
Uptime float64 `json:"uptime_seconds"`
// IsGlobalObfuscationEnabled shows if obfuscation(hiding IPs and cluster domain) is enabled
IsGlobalObfuscationEnabled bool `json:"is_global_obfuscation_enabled"`
}
// CreateAllGatherers creates all the gatherers
func CreateAllGatherers(
gatherKubeConfig, gatherProtoKubeConfig, metricsGatherKubeConfig, alertsGatherKubeConfig *rest.Config,
anonymizer *anonymization.Anonymizer, configObserver *configobserver.Controller,
insightsClient *insightsclient.Client,
) []gatherers.Interface {
clusterConfigGatherer := clusterconfig.New(
gatherKubeConfig, gatherProtoKubeConfig, metricsGatherKubeConfig, alertsGatherKubeConfig,
anonymizer, configObserver,
)
workloadsGatherer := workloads.New(gatherKubeConfig, gatherProtoKubeConfig)
conditionalGatherer := conditional.New(
gatherProtoKubeConfig, metricsGatherKubeConfig, gatherKubeConfig, configObserver, insightsClient,
)
return []gatherers.Interface{clusterConfigGatherer, workloadsGatherer, conditionalGatherer}
}
// CollectAndRecordGatherer gathers enabled functions of the provided gatherer and records the results to the recorder
// and returns info about the recorded data. Panics are just logged and written
// to the resulting array (to the archive metadata)
func CollectAndRecordGatherer(
ctx context.Context,
gatherer gatherers.Interface,
rec recorder.Interface,
gatherConfig *v1alpha1.GatherConfig,
) ([]GathererFunctionReport, error) {
startTime := time.Now()
reports, totalNumberOfRecords, errs := collectAndRecordGatherer(ctx, gatherer, rec, gatherConfig)
reports = append(reports, GathererFunctionReport{
FuncName: gatherer.GetName(),
Duration: time.Since(startTime).Milliseconds(),
RecordsCount: totalNumberOfRecords,
Errors: utils.ErrorsToStrings(errs),
})
return reports, utils.SumErrors(errs)
}
func collectAndRecordGatherer(
ctx context.Context,
gatherer gatherers.Interface,
rec recorder.Interface,
gatherConfig *v1alpha1.GatherConfig,
) (reports []GathererFunctionReport, totalNumberOfRecords int, allErrors []error) {
resultsChan, err := startGatheringConcurrently(ctx, gatherer, gatherConfig)
if err != nil {
allErrors = append(allErrors, err)
return reports, totalNumberOfRecords, allErrors
}
for result := range resultsChan {
report, errs := recordGatheringFunctionResult(rec, &result, gatherer.GetName())
allErrors = append(allErrors, errs...)
reports = append(reports, report)
totalNumberOfRecords += report.RecordsCount
}
return reports, totalNumberOfRecords, allErrors
}
func recordGatheringFunctionResult(
rec recorder.Interface, result *GatheringFunctionResult, gathererName string,
) (GathererFunctionReport, []error) {
var allErrors []error
var recordWarnings []error
var recordErrs []error
if result.Panic != nil {
recordErrs = append(recordErrs, fmt.Errorf("panic: %v", result.Panic))
klog.Error(fmt.Errorf(
`gatherer "%v" function "%v" panicked with the error: %v`,
gathererName, result.FunctionName, result.Panic,
))
allErrors = append(allErrors, fmt.Errorf(`function "%v" panicked`, result.FunctionName))
}
for _, err := range result.Errs {
if w, isWarning := err.(*types.Warning); isWarning {
recordWarnings = append(recordWarnings, w)
klog.Warningf(
`gatherer "%v" function "%v" produced the warning: %v`, gathererName, result.FunctionName, w,
)
} else {
recordErrs = append(recordErrs, err)
klog.Errorf(
`gatherer "%v" function "%v" failed with the error: %v`,
gathererName, result.FunctionName, err,
)
allErrors = append(allErrors, fmt.Errorf(`function "%v" failed with an error`, result.FunctionName))
}
}
recordedRecs := 0
for _, r := range result.Records {
wasRecorded := true
if errs := rec.Record(r); len(errs) > 0 {
for _, err := range errs {
if w, isWarning := err.(*types.Warning); isWarning {
recordWarnings = append(recordWarnings, w)
klog.Warningf(
`issue recording gatherer "%v" function "%v" result "%v" because of the warning: %v`,
gathererName, result.FunctionName, r.GetFilename(), w,
)
} else {
recordErrs = append(recordErrs, err)
klog.Errorf(
`error recording gatherer "%v" function "%v" result "%v" because of the error: %v`,
gathererName, result.FunctionName, r.GetFilename(), err,
)
allErrors = append(allErrors, fmt.Errorf(
`unable to record function "%v" record "%v"`, result.FunctionName, r.GetFilename(),
))
wasRecorded = false
}
}
}
if wasRecorded {
recordedRecs++
}
}
klog.Infof(
`gatherer "%v" function "%v" took %v to process %v records`,
gathererName, result.FunctionName, result.TimeElapsed, len(result.Records),
)
return GathererFunctionReport{
FuncName: fmt.Sprintf("%v/%v", gathererName, result.FunctionName),
Duration: result.TimeElapsed.Milliseconds(),
RecordsCount: recordedRecs,
Errors: utils.ErrorsToStrings(recordErrs),
Warnings: utils.ErrorsToStrings(recordWarnings),
Panic: result.Panic,
}, allErrors
}
// RecordArchiveMetadata records info about archive and gatherers' reports
func RecordArchiveMetadata(
functionReports []GathererFunctionReport,
rec recorder.Interface,
anonymizer *anonymization.Anonymizer,
) error {
var m runtime.MemStats
runtime.ReadMemStats(&m)
archiveMetadata := record.Record{
Name: recorder.MetadataRecordName,
Item: record.JSONMarshaller{Object: ArchiveMetadata{
StatusReports: functionReports,
MemoryAlloc: m.HeapAlloc,
Uptime: time.Since(programStartTime).Truncate(time.Millisecond).Seconds(),
IsGlobalObfuscationEnabled: anonymizer.IsObfuscationEnabled(),
}},
}
if errs := rec.Record(archiveMetadata); len(errs) > 0 {
return fmt.Errorf("unable to record archive metadata because of the errors: %v", errs)
}
return nil
}
// startGatheringConcurrently starts gathering of enabled functions of the provided gatherer and returns a channel
// with results which will be closed when processing is done
func startGatheringConcurrently(
ctx context.Context, gatherer gatherers.Interface, gatheringConfig *v1alpha1.GatherConfig,
) (chan GatheringFunctionResult, error) {
var tasks []Task
var gatheringFunctions map[string]gatherers.GatheringClosure
gatheringFunctions, err := gatherer.GetGatheringFunctions(ctx)
if err != nil {
return nil, err
}
// This is from TechPreview feature so we have to check the nil
if gatheringConfig != nil {
gatheringFunctions = getEnabledGatheringFunctions(gatherer.GetName(), gatheringFunctions, gatheringConfig.DisabledGatherers)
}
if len(gatheringFunctions) == 0 {
return nil, fmt.Errorf("no gather functions are specified to run")
}
for functionName, gatheringClosure := range gatheringFunctions {
tasks = append(tasks, Task{
Name: functionName,
F: gatheringClosure,
})
}
return HandleTasksConcurrently(ctx, tasks), nil
}
// getEnabledGatheringFunctions iterates over all gathering functions and
// creates a new map without all the disabled functions
func getEnabledGatheringFunctions(gathererName string,
allGatheringFunctions map[string]gatherers.GatheringClosure,
disabledFunctions []string) map[string]gatherers.GatheringClosure {
enabledGatheringFunctions := make(map[string]gatherers.GatheringClosure)
// disabling a complete gatherer - e.g workloads
if utils.StringInSlice(gathererName, disabledFunctions) {
klog.Infof("%s gatherer is completely disabled", gathererName)
return enabledGatheringFunctions
}
for fName, gatherinClosure := range allGatheringFunctions {
fullGathererName := fmt.Sprintf("%s/%s", gathererName, fName)
if !utils.StringInSlice(fullGathererName, disabledFunctions) {
enabledGatheringFunctions[fName] = gatherinClosure
}
}
return enabledGatheringFunctions
}