|
| 1 | +// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 2 | +// or more contributor license agreements. Licensed under the Elastic License; |
| 3 | +// you may not use this file except in compliance with the Elastic License. |
| 4 | + |
| 5 | +package sqs |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "strings" |
| 11 | + |
| 12 | + awssdk "github.com/aws/aws-sdk-go-v2/aws" |
| 13 | + "github.com/aws/aws-sdk-go-v2/service/sqs" |
| 14 | + "github.com/aws/aws-sdk-go-v2/service/sqs/sqsiface" |
| 15 | + "github.com/pkg/errors" |
| 16 | + |
| 17 | + "github.com/elastic/beats/v7/libbeat/logp" |
| 18 | + "github.com/elastic/beats/v7/metricbeat/mb" |
| 19 | + awscommon "github.com/elastic/beats/v7/x-pack/libbeat/common/aws" |
| 20 | +) |
| 21 | + |
| 22 | +const metadataPrefix = "aws.sqs.queue" |
| 23 | + |
| 24 | +// AddMetadata adds metadata for SQS queues from a specific region |
| 25 | +func AddMetadata(endpoint string, regionName string, awsConfig awssdk.Config, events map[string]mb.Event) map[string]mb.Event { |
| 26 | + svc := sqs.New(awscommon.EnrichAWSConfigWithEndpoint( |
| 27 | + endpoint, "sqs", regionName, awsConfig)) |
| 28 | + |
| 29 | + // Get queueUrls for each region |
| 30 | + queueURLs, err := getQueueUrls(svc) |
| 31 | + if err != nil { |
| 32 | + logp.Error(fmt.Errorf("getQueueUrls failed, skipping region %s: %w", regionName, err)) |
| 33 | + return events |
| 34 | + } |
| 35 | + |
| 36 | + // collect monitoring state for each instance |
| 37 | + for _, queueURL := range queueURLs { |
| 38 | + queueURLParsed := strings.Split(queueURL, "/") |
| 39 | + queueName := queueURLParsed[len(queueURLParsed)-1] |
| 40 | + if _, ok := events[queueName]; !ok { |
| 41 | + continue |
| 42 | + } |
| 43 | + events[queueName].RootFields.Put(metadataPrefix+"name", queueName) |
| 44 | + } |
| 45 | + return events |
| 46 | +} |
| 47 | + |
| 48 | +func getQueueUrls(svc sqsiface.ClientAPI) ([]string, error) { |
| 49 | + // ListQueues |
| 50 | + listQueuesInput := &sqs.ListQueuesInput{} |
| 51 | + req := svc.ListQueuesRequest(listQueuesInput) |
| 52 | + output, err := req.Send(context.TODO()) |
| 53 | + if err != nil { |
| 54 | + err = errors.Wrap(err, "Error ListQueues") |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + return output.QueueUrls, nil |
| 58 | +} |
0 commit comments