Created
February 26, 2025 01:28
-
-
Save mizzy/f4b07ae6bbb89812f8f8f1301ec1418b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"github.com/aws/aws-lambda-go/events" | |
"github.com/aws/aws-lambda-go/lambda" | |
"github.com/aws/aws-sdk-go-v2/aws" | |
"github.com/aws/aws-sdk-go-v2/config" | |
"github.com/aws/aws-sdk-go-v2/service/cloudwatch" | |
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types" | |
"github.com/aws/aws-sdk-go-v2/service/ecs" | |
"io" | |
"net/http" | |
"time" | |
) | |
type Stats struct { | |
Sidekiq Sidekiq | |
} | |
type Sidekiq struct { | |
Enqueued float64 | |
} | |
func HandleRequest(ctx context.Context, event *events.CloudWatchEvent) error { | |
if event == nil { | |
return fmt.Errorf("received nil event") | |
} | |
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("ap-northeast-1")) | |
if err != nil { | |
return err | |
} | |
ecsClient := ecs.NewFromConfig(cfg) | |
tasks, err := ecsClient.ListTasks(ctx, &ecs.ListTasksInput{ | |
Cluster: aws.String("example-cluster"), | |
ServiceName: aws.String("example-service"), | |
}) | |
if err != nil { | |
return err | |
} | |
if len(tasks.TaskArns) == 0 { | |
return nil | |
} | |
desc, err := ecsClient.DescribeTasks(ctx, &ecs.DescribeTasksInput{ | |
Cluster: aws.String("example-cluster"), | |
Tasks: tasks.TaskArns, | |
}) | |
if err != nil { | |
return err | |
} | |
var host string | |
for _, attachment := range desc.Tasks[0].Attachments { | |
if *attachment.Type == "ElasticNetworkInterface" { | |
for _, detail := range attachment.Details { | |
if *detail.Name == "privateIPv4Address" { | |
host = *detail.Value | |
} | |
} | |
} | |
} | |
res, err := http.Get(fmt.Sprintf("http://%s/sidekiq/stats", host)) | |
if err != nil { | |
return err | |
} | |
body, _ := io.ReadAll(res.Body) | |
var stats Stats | |
err = json.Unmarshal(body, &stats) | |
if err != nil { | |
return err | |
} | |
cwClient := cloudwatch.NewFromConfig(cfg) | |
metricData := &cloudwatch.PutMetricDataInput{ | |
Namespace: aws.String("Sidekiq"), | |
MetricData: []types.MetricDatum{ | |
{ | |
MetricName: aws.String("Stats"), | |
Dimensions: []types.Dimension{ | |
{ | |
Name: aws.String("SidekiqStats"), | |
Value: aws.String("Enqueued"), | |
}, | |
}, | |
Timestamp: aws.Time(time.Now()), | |
Value: aws.Float64(stats.Sidekiq.Enqueued), | |
Unit: types.StandardUnitCount, | |
}, | |
}, | |
} | |
_, err = cwClient.PutMetricData(context.TODO(), metricData) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
func main() { | |
lambda.Start(HandleRequest) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment