-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathcontext.go
More file actions
665 lines (570 loc) · 21.3 KB
/
context.go
File metadata and controls
665 lines (570 loc) · 21.3 KB
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
package cluster
import (
"fmt"
"io"
"math"
"net"
"os"
"os/exec"
"strings"
"sync"
"time"
v1 "github.com/openshift-online/ocm-sdk-go/servicelogs/v1"
"github.com/openshift/osdctl/cmd/servicelog"
pd "github.com/PagerDuty/go-pagerduty"
"github.com/andygrunwald/go-jira"
"github.com/aws/aws-sdk-go-v2/service/cloudtrail"
"github.com/aws/aws-sdk-go-v2/service/cloudtrail/types"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/openshift/osdctl/cmd/dynatrace"
"github.com/openshift/osdctl/pkg/osdCloud"
"github.com/openshift/osdctl/pkg/osdctlConfig"
"github.com/openshift/osdctl/pkg/provider/pagerduty"
"github.com/openshift/osdctl/pkg/utils"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
JiraBaseURL = "https://issues.redhat.com"
JiraTokenRegistrationPath = "/secure/ViewProfile.jspa?selectedTab=com.atlassian.pats.pats-plugin:jira-user-personal-access-tokens" // #nosec G101
PagerDutyTokenRegistrationUrl = "https://martindstone.github.io/PDOAuth/" // #nosec G101
ClassicSplunkURL = "https://osdsecuritylogs.splunkcloud.com/en-US/app/search/search?q=search%%20index%%3D%%22%s%%22%%20clusterid%%3D%%22%s%%22\n\n"
HCPSplunkURL = "https://osdsecuritylogs.splunkcloud.com/en-US/app/search/search?q=search%%20index%%3D%%22%s%%22%%20annotations.managed.openshift.io%%2Fhosted-cluster-id%%3Docm-%s-%s-%s\n\n"
SGPSplunkURL = "https://osd-ase1.splunkcloud.com/en-US/app/search/search?q=search%%20index%%3D%%22%s%%22%%20annotations.managed.openshift.io%%2Fhosted-cluster-id%%3Docm-%s-%s-%s\n\n"
shortOutputConfigValue = "short"
longOutputConfigValue = "long"
jsonOutputConfigValue = "json"
delimiter = ">> "
)
// ContextOptions is a pure configuration struct containing all the parameters
// needed to query cluster context information. It has no methods except validation.
type ContextOptions struct {
ClusterID string
Days int
Pages int
FullScan bool
Verbose bool
Output string
AWSProfile string
OAuthToken string
UserToken string
JiraToken string
TeamIDs []string
}
// Validate ensures the query options are valid
func (o ContextOptions) Validate() error {
if o.Days < 1 {
return fmt.Errorf("cannot have a days value lower than 1")
}
switch o.Output {
case shortOutputConfigValue:
return nil
case longOutputConfigValue:
return nil
case jsonOutputConfigValue:
return nil
default:
return fmt.Errorf("unknown Output Format: %s", o.Output)
}
}
// ContextCache holds the runtime state and cluster information needed during execution.
type ContextCache struct {
cluster *cmv1.Cluster
clusterID string
externalClusterID string
baseDomain string
organizationID string
infraID string
regionID string
// Query options - configuration for the context query
queryOpts ContextOptions
}
type contextData struct {
// Cluster info
ClusterName string
ClusterVersion string
ClusterID string
ExternalClusterID string
InfraID string
// Current OCM environment (e.g., "production" or "stage")
OCMEnv string
// RegionID (used for region-locked clusters)
RegionID string
// Cluster object for advanced queries
Cluster *cmv1.Cluster
// Dynatrace Environment URL and Logs URL
DyntraceEnvURL string
DyntraceLogsURL string
// limited Support Status
LimitedSupportReasons []*cmv1.LimitedSupportReason
// Service Logs
ServiceLogs []*v1.LogEntry
// Jira Cards
JiraIssues []jira.Issue
HandoverAnnouncements []jira.Issue
SupportExceptions []jira.Issue
// PD Alerts
pdServiceID []string
PdAlerts map[string][]pd.Incident
HistoricalAlerts map[string][]*pagerduty.IncidentOccurrenceTracker
// CloudTrail Logs
CloudtrailEvents []*types.Event
// OCM Cluster description
Description string
// User Banned Information
UserBanned bool
BanCode string
BanDescription string
// Network data
NetworkType string
NetworkMachineCIDR string
NetworkServiceCIDR string
NetworkPodCIDR string
NetworkHostPrefix int
NetworkMaxNodesFromPodCIDR int
NetworkMaxPodsPerNode int
NetworkMaxServices int
// Migration data
SdnToOvnMigration *cmv1.SdnToOvnClusterMigration
MigrationStateValue cmv1.ClusterMigrationStateValue
}
// newCmdContext implements the context command to show the current context of a cluster
func newCmdContext() *cobra.Command {
var queryOpts ContextOptions
contextCmd := &cobra.Command{
Use: "context --cluster-id <cluster-identifier>",
Short: "Shows the context of a specified cluster",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
// Validate query options
if err := queryOpts.Validate(); err != nil {
return err
}
// Create and setup context options with query configuration
ops := newContextOptions(queryOpts)
err := ops.setup()
if err != nil {
return err
}
return ops.run()
},
}
contextCmd.Flags().StringVarP(&queryOpts.ClusterID, "cluster-id", "C", "", "Provide internal ID of the cluster")
_ = contextCmd.MarkFlagRequired("cluster-id")
contextCmd.Flags().StringVarP(&queryOpts.Output, "output", "o", "long", "Valid formats are ['long', 'short', 'json']. Output is set to 'long' by default")
contextCmd.Flags().StringVarP(&queryOpts.AWSProfile, "profile", "p", "", "AWS Profile")
contextCmd.Flags().BoolVarP(&queryOpts.Verbose, "verbose", "", false, "Verbose output")
contextCmd.Flags().BoolVar(&queryOpts.FullScan, "full", false, "Run full suite of checks.")
contextCmd.Flags().IntVarP(&queryOpts.Days, "days", "d", 30, "Command will display X days of Error SLs sent to the cluster. Days is set to 30 by default")
contextCmd.Flags().IntVar(&queryOpts.Pages, "pages", 40, "Command will display X pages of Cloud Trail logs for the cluster. Pages is set to 40 by default")
contextCmd.Flags().StringVar(&queryOpts.OAuthToken, "oauthtoken", "", fmt.Sprintf("Pass in PD oauthtoken directly. If not passed in, by default will read `pd_oauth_token` from ~/.config/%s.\nPD OAuth tokens can be generated by visiting %s", osdctlConfig.ConfigFileName, PagerDutyTokenRegistrationUrl))
contextCmd.Flags().StringVar(&queryOpts.UserToken, "usertoken", "", fmt.Sprintf("Pass in PD usertoken directly. If not passed in, by default will read `pd_user_token` from ~/config/%s", osdctlConfig.ConfigFileName))
contextCmd.Flags().StringVar(&queryOpts.JiraToken, "jiratoken", "", fmt.Sprintf("Pass in the Jira access token directly. If not passed in, by default will read `jira_token` from ~/.config/%s.\nJira access tokens can be registered by visiting %s/%s", osdctlConfig.ConfigFileName, JiraBaseURL, JiraTokenRegistrationPath))
contextCmd.Flags().StringArrayVarP(&queryOpts.TeamIDs, "team-ids", "t", []string{}, fmt.Sprintf("Pass in PD team IDs directly to filter the PD Alerts by team. Can also be defined as `team_ids` in ~/.config/%s\nWill show all PD Alerts for all PD service IDs if none is defined", osdctlConfig.ConfigFileName))
return contextCmd
}
func newContextOptions(queryOpts ContextOptions) *ContextCache {
return &ContextCache{
queryOpts: queryOpts,
}
}
func (o *ContextCache) setup() error {
// Create OCM client to talk to cluster API
defer utils.StartDelayTracker(o.queryOpts.Verbose, "OCM Clusters").End()
ocmClient, err := utils.CreateConnection()
if err != nil {
return err
}
defer func() {
if err := ocmClient.Close(); err != nil {
fmt.Printf("Cannot close the ocmClient (possible memory leak): %q", err)
}
}()
// Use the clusterID flag value instead of args
clusterArgs := []string{o.queryOpts.ClusterID}
clusters := utils.GetClusters(ocmClient, clusterArgs)
if len(clusters) != 1 {
return fmt.Errorf("unexpected number of clusters matched input. Expected 1 got %d", len(clusters))
}
o.cluster = clusters[0]
o.clusterID = o.cluster.ID()
o.externalClusterID = o.cluster.ExternalID()
o.baseDomain = o.cluster.DNS().BaseDomain()
o.infraID = o.cluster.InfraID()
if o.queryOpts.UserToken == "" {
o.queryOpts.UserToken = viper.GetString(pagerduty.PagerDutyUserTokenConfigKey)
}
if o.queryOpts.OAuthToken == "" {
o.queryOpts.OAuthToken = viper.GetString(pagerduty.PagerDutyOauthTokenConfigKey)
}
sub, err := utils.GetSubFromClusterID(ocmClient, *o.cluster)
if err != nil {
fmt.Printf("Failed to get Subscription for cluster %s - err: %q", o.clusterID, err)
}
o.organizationID = sub.OrganizationID()
o.regionID = sub.RhRegionID()
return nil
}
func (o *ContextCache) run() error {
currentData, dataErrors := o.generateContextData()
if currentData == nil {
fmt.Fprintf(os.Stderr, "Failed to query cluster info: %+v", dataErrors)
os.Exit(1)
}
if len(dataErrors) > 0 {
fmt.Fprintf(os.Stderr, "Encountered Errors during data collection. Displayed data may be incomplete: \n")
for _, dataError := range dataErrors {
fmt.Fprintf(os.Stderr, "\t%v\n", dataError)
}
}
// Use the presenter to render output
presenter := NewClusterContextPresenter(os.Stdout)
return presenter.Render(currentData, o.queryOpts)
}
func GenerateContextData(clusterId string) (string, []error) {
queryOpts := ContextOptions{
ClusterID: clusterId,
Days: 30,
Pages: 40,
FullScan: false,
Verbose: false,
Output: jsonOutputConfigValue,
}
contextOptions := newContextOptions(queryOpts)
err := contextOptions.setup()
if err != nil {
return "", []error{err}
}
contextData, errs := contextOptions.generateContextData()
builder := &strings.Builder{}
presenter := NewClusterContextPresenter(builder)
err = presenter.Render(contextData, queryOpts)
if err != nil {
errs = append(errs, err)
}
return builder.String(), errs
}
// generateContextData Creates a contextData struct that contains all the
// cluster context information requested by the contextOptions. if a certain
// data point can not be queried, the appropriate field will be null and the
// errors array will contain information about the error. The first return
// value will only be nil, if this function fails to get basic cluster
// information. The second return value will *never* be nil, but instead have a
// length of 0 if no errors occurred
func (o *ContextCache) generateContextData() (*contextData, []error) {
data := &contextData{}
errors := []error{}
wg := sync.WaitGroup{}
// For PD query dependencies
pdwg := sync.WaitGroup{}
var skipPagerDutyCollection bool
pdProvider, err := pagerduty.NewClient().
WithUserToken(o.queryOpts.UserToken).
WithOauthToken(o.queryOpts.OAuthToken).
WithBaseDomain(o.baseDomain).
WithTeamIdList(viper.GetStringSlice(pagerduty.PagerDutyTeamIDsKey)).
Init()
if err != nil {
skipPagerDutyCollection = true
errors = append(errors, fmt.Errorf("skipping PagerDuty context collection: %v", err))
}
ocmClient, err := utils.CreateConnection()
if err != nil {
return nil, []error{err}
}
defer ocmClient.Close()
// Normally the o.cluster would be set by complete function, but in case we want to call this function
// in an other context, we can make sure o.cluster is set properly from o.clusterID
if o.cluster == nil {
cluster, err := utils.GetCluster(ocmClient, o.clusterID)
if err != nil {
errors = append(errors, err)
return nil, errors
}
o.cluster = cluster
}
data.ClusterName = o.cluster.Name()
data.ClusterID = o.clusterID
data.ExternalClusterID = o.externalClusterID
data.InfraID = o.infraID
data.RegionID = o.regionID
data.Cluster = o.cluster
data.ClusterVersion = o.cluster.Version().RawID()
data.OCMEnv = utils.GetCurrentOCMEnv(ocmClient)
// network info fetch and calculations
var clusterNetwork = o.cluster.Network()
var ok bool
var podNetwork *net.IPNet
var serviceNetwork *net.IPNet
data.NetworkType = clusterNetwork.Type()
data.NetworkMachineCIDR, ok = clusterNetwork.GetMachineCIDR()
if !ok {
errors = append(errors, fmt.Errorf("missing Machine CIDR in OCM Cluster"))
return nil, errors
}
data.NetworkServiceCIDR = clusterNetwork.ServiceCIDR()
data.NetworkPodCIDR = clusterNetwork.PodCIDR()
data.NetworkHostPrefix = clusterNetwork.HostPrefix()
//max possible nodes from hostprefix
_, podNetwork, err = net.ParseCIDR(data.NetworkPodCIDR)
if err != nil {
errors = append(errors, err)
return nil, errors
}
var b, max = podNetwork.Mask.Size()
data.NetworkMaxNodesFromPodCIDR = int(math.Pow(float64(2), float64(data.NetworkHostPrefix-b)))
//max pods per node
data.NetworkMaxPodsPerNode = int(math.Pow(float64(2), float64(max-data.NetworkHostPrefix)))
//max services
_, serviceNetwork, err = net.ParseCIDR(data.NetworkServiceCIDR)
if err != nil {
errors = append(errors, err)
return nil, errors
}
b, max = serviceNetwork.Mask.Size()
data.NetworkMaxServices = int(math.Pow(float64(2), float64(max-b))) - 2 // minus 2: API and DNS service
GetLimitedSupport := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Limited Support reasons").End()
limitedSupportReasons, err := utils.GetClusterLimitedSupportReasons(ocmClient, o.clusterID)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting Limited Support status reasons: %v", err))
} else {
data.LimitedSupportReasons = append(data.LimitedSupportReasons, limitedSupportReasons...)
}
}
GetServiceLogs := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Service Logs").End()
timeToCheckSvcLogs := time.Now().AddDate(0, 0, -o.queryOpts.Days)
data.ServiceLogs, err = servicelog.GetServiceLogsSince(o.clusterID, timeToCheckSvcLogs, false, false)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting the service logs: %v", err))
}
}
GetBannedUser := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Check Banned User").End()
subscription, err := utils.GetSubscription(ocmClient, data.ClusterID)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting subscripton %v", err))
}
creator, err := utils.GetAccount(ocmClient, subscription.Creator().ID())
if err != nil {
errors = append(errors, fmt.Errorf("error while checking if user is banned %v", err))
}
data.UserBanned = creator.Banned()
data.BanCode = creator.BanCode()
data.BanDescription = creator.BanDescription()
}
GetJiraIssues := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Jira Issues").End()
data.JiraIssues, err = utils.GetJiraIssuesForCluster(o.clusterID, o.externalClusterID, o.queryOpts.JiraToken)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting the open jira tickets: %v", err))
}
}
GetHandoverAnnouncements := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Handover Announcements").End()
org, err := utils.GetOrganization(ocmClient, o.clusterID)
if err != nil {
fmt.Printf("Failed to get Subscription for cluster %s - err: %q", o.clusterID, err)
}
productID := o.cluster.Product().ID()
data.HandoverAnnouncements, err = utils.GetRelatedHandoverAnnouncements(o.clusterID, o.externalClusterID, o.queryOpts.JiraToken, org.Name(), productID, o.cluster.Hypershift().Enabled(), o.cluster.Version().RawID())
if err != nil {
errors = append(errors, fmt.Errorf("error while getting the open jira tickets: %v", err))
}
}
GetSupportExceptions := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Support Exceptions").End()
data.SupportExceptions, err = utils.GetJiraSupportExceptionsForOrg(o.organizationID, o.queryOpts.JiraToken)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting support exceptions: %v", err))
}
}
GetDynatraceDetails := func() {
var clusterID string = o.clusterID
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Dynatrace URL").End()
hcpCluster, err := dynatrace.FetchClusterDetails(clusterID)
if err != nil {
if err == dynatrace.ErrUnsupportedCluster {
data.DyntraceEnvURL = dynatrace.ErrUnsupportedCluster.Error()
} else {
errors = append(errors, fmt.Errorf("failed to acquire cluster details %v", err))
data.DyntraceEnvURL = "Failed to fetch Dynatrace URL"
}
return
}
query, err := dynatrace.GetQuery(hcpCluster, time.Time{}, time.Time{}, 1) // passing nil from/to values to use --since behaviour
if err != nil {
errors = append(errors, fmt.Errorf("failed to build query for Dynatrace %v", err))
data.DyntraceEnvURL = fmt.Sprintf("Failed to build Dynatrace query: %v", err)
return
}
queryTxt := query.Build()
data.DyntraceEnvURL = hcpCluster.DynatraceURL
data.DyntraceLogsURL, err = dynatrace.GetLinkToWebConsole(hcpCluster.DynatraceURL, "now()-10h", "now()", queryTxt)
if err != nil {
errors = append(errors, fmt.Errorf("failed to get url: %v", err))
}
}
GetPagerDutyAlerts := func() {
pdwg.Add(1)
defer wg.Done()
defer pdwg.Done()
if skipPagerDutyCollection {
return
}
delayTracker := utils.StartDelayTracker(o.queryOpts.Verbose, "PagerDuty Service")
data.pdServiceID, err = pdProvider.GetPDServiceIDs()
if err != nil {
errors = append(errors, fmt.Errorf("error getting PD Service ID: %v", err))
}
delayTracker.End()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "current PagerDuty Alerts").End()
data.PdAlerts, err = pdProvider.GetFiringAlertsForCluster(data.pdServiceID)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting current PD Alerts: %v", err))
}
}
GetMigrationInfo := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Migration Info").End()
migrationResponse, err := utils.GetMigration(ocmClient, o.clusterID)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting migration info: %v", err))
return
}
sdntoovnmigration, ok := migrationResponse.GetSdnToOvn()
if !ok {
return
}
data.SdnToOvnMigration = sdntoovnmigration
if state, ok := migrationResponse.GetState(); ok {
data.MigrationStateValue = state.Value()
}
}
var retrievers []func()
retrievers = append(
retrievers,
GetLimitedSupport,
GetServiceLogs,
GetJiraIssues,
GetHandoverAnnouncements,
GetSupportExceptions,
GetPagerDutyAlerts,
GetDynatraceDetails,
GetBannedUser,
GetMigrationInfo,
)
if o.queryOpts.Output == longOutputConfigValue {
GetDescription := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "Cluster Description").End()
cmd := "ocm describe cluster " + o.clusterID
output, err := exec.Command("bash", "-c", cmd).Output()
if err != nil {
fmt.Fprintln(os.Stderr, string(output))
fmt.Fprintln(os.Stderr, err)
}
data.Description = string(output)
}
retrievers = append(
retrievers,
GetDescription,
)
}
if o.queryOpts.FullScan {
GetHistoricalPagerDutyAlerts := func() {
pdwg.Wait()
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, "historical PagerDuty Alerts").End()
data.HistoricalAlerts, err = pdProvider.GetHistoricalAlertsForCluster(data.pdServiceID)
if err != nil {
errors = append(errors, fmt.Errorf("error while getting historical PD Alert Data: %v", err))
}
}
GetCloudTrailLogs := func() {
defer wg.Done()
defer utils.StartDelayTracker(o.queryOpts.Verbose, fmt.Sprintf("past %d pages of Cloudtrail data", o.queryOpts.Pages)).End()
data.CloudtrailEvents, err = GetCloudTrailLogsForCluster(o.queryOpts.AWSProfile, o.clusterID, o.queryOpts.Pages)
if err != nil {
errors = append(errors, fmt.Errorf("error getting cloudtrail logs for cluster: %v", err))
}
}
retrievers = append(
retrievers,
GetHistoricalPagerDutyAlerts,
GetCloudTrailLogs,
)
}
for _, retriever := range retrievers {
wg.Add(1)
go retriever()
}
wg.Wait()
return data, errors
}
func GetCloudTrailLogsForCluster(awsProfile string, clusterID string, maxPages int) ([]*types.Event, error) {
awsJumpClient, err := osdCloud.GenerateAWSClientForCluster(awsProfile, clusterID)
if err != nil {
return nil, err
}
var foundEvents []types.Event
eventSearchInput := cloudtrail.LookupEventsInput{}
for counter := 0; counter <= maxPages; counter++ {
print(".")
cloudTrailEvents, err := awsJumpClient.LookupEvents(&eventSearchInput)
if err != nil {
return nil, err
}
foundEvents = append(foundEvents, cloudTrailEvents.Events...)
// for pagination
eventSearchInput.NextToken = cloudTrailEvents.NextToken
if cloudTrailEvents.NextToken == nil {
break
}
}
var filteredEvents []*types.Event
for _, event := range foundEvents {
if skippableEvent(*event.EventName) {
continue
}
if event.Username != nil && strings.Contains(*event.Username, "RH-SRE-") {
continue
}
filteredEvents = append(filteredEvents, &event)
}
return filteredEvents, nil
}
// These are a list of skippable aws event types, as they won't indicate any modification on the customer's side.
func skippableEvent(eventName string) bool {
skippableList := []string{
"Get",
"List",
"Describe",
"AssumeRole",
"Encrypt",
"Decrypt",
"LookupEvents",
"GenerateDataKey",
}
for _, skipWord := range skippableList {
if strings.Contains(eventName, skipWord) {
return true
}
}
return false
}
func (data *contextData) printClusterHeader(w io.Writer) {
clusterHeader := fmt.Sprintf("%s -- %s", data.ClusterName, data.ClusterID)
fmt.Fprintln(w, strings.Repeat("=", len(clusterHeader)))
fmt.Fprintln(w, clusterHeader)
fmt.Fprintln(w, strings.Repeat("=", len(clusterHeader)))
}