Skip to content

Instantly share code, notes, and snippets.

@fujiwara

fujiwara/main.go

Created Feb 18, 2019
Embed
What would you like to do?
cloudwatch-to-mackerel
package main
import (
"context"
"encoding/json"
"errors"
"log"
"os"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
mackerel "github.com/mackerelio/mackerel-client-go"
)
const MaxMetricValues = 100
func main() {
lambda.Start(handler)
}
func handler(ctx context.Context, event *events.AutoScalingEvent) error {
var qs []*cloudwatch.MetricDataQuery
f, err := os.Open(os.Getenv("QUERY_FILE"))
if err != nil {
return err
}
if err := json.NewDecoder(f).Decode(&qs); err != nil {
return err
}
svc := cloudwatch.New(session.Must(session.NewSession(&aws.Config{})))
now := time.Now()
service := os.Getenv("SERVICE")
if service == "" {
return errors.New("SERVICE required")
}
apiKey := os.Getenv("MACKEREL_APIKEY")
if apiKey == "" {
return errors.New("MACKEREL_APIKEY required")
}
res, err := svc.GetMetricData(&cloudwatch.GetMetricDataInput{
StartTime: aws.Time(now.Add(-3 * time.Minute)),
EndTime: aws.Time(now),
MetricDataQueries: qs,
})
if err != nil {
return err
}
client := mackerel.NewClient(apiKey)
values := make([]*mackerel.MetricValue, 0, MaxMetricValues)
for _, r := range res.MetricDataResults {
for i, ts := range r.Timestamps {
label, ts, value := *r.Label, (*ts).Unix(), *(r.Values[i])
values = append(values, &mackerel.MetricValue{
Name: label,
Time: ts,
Value: value,
})
if len(values) >= MaxMetricValues {
if err := client.PostServiceMetricValues(service, values); err != nil {
log.Println("[warn] failed to post to Mackerel", err)
} else {
log.Printf("[info] %d metric values posted", len(values))
}
values = values[0:0]
}
}
}
if len(values) > 0 {
if err := client.PostServiceMetricValues(service, values); err != nil {
return err
} else {
log.Printf("[info] %d metric values posted", len(values))
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment