Skip to content

Instantly share code, notes, and snippets.

@jasdel
Last active October 17, 2017 16:43
Show Gist options
  • Save jasdel/ef4d52e94ad91e84eddef6452c53f4d4 to your computer and use it in GitHub Desktop.
Save jasdel/ef4d52e94ad91e84eddef6452c53f4d4 to your computer and use it in GitHub Desktop.
Makes a series of cloudwatch requests while connection status logging.
package main
import (
"context"
"fmt"
"net"
"net/http"
"net/http/httptrace"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
)
func main() {
config := &aws.Config{
Region: aws.String("us-west-1"),
HTTPClient: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
},
}
// config.WithLogLevel(aws.LogDebug)
// config.WithDisableSSL(true)
sess := session.Must(session.NewSession())
client := cloudwatch.New(sess, config)
ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{
ConnectStart: func(network, addr string) {
fmt.Println("Connection started", network, addr)
},
ConnectDone: func(network, addr string, err error) {
fmt.Println("Connection done", network, addr, err)
},
PutIdleConn: func(err error) {
fmt.Println("Connection put in idle pool", err)
},
GetConn: func(port string) {
fmt.Println("Get connection", port)
},
GotConn: func(connInfo httptrace.GotConnInfo) {
fmt.Printf("Got connection info %+v\n", connInfo)
},
})
now := time.Now()
period := 60 * time.Second
for {
end := now.Add(-period)
start := end.Add(-period)
input := &cloudwatch.GetMetricStatisticsInput{
StartTime: aws.Time(start),
EndTime: aws.Time(end),
MetricName: aws.String("StatusCheckFailed_Instance"),
Namespace: aws.String("AWS/EC2"),
Period: aws.Int64(int64(period.Seconds())),
Dimensions: []*cloudwatch.Dimension{
&cloudwatch.Dimension{
Name: aws.String("InstanceId"),
Value: aws.String("i-abcdefgh"),
},
},
Statistics: []*string{
aws.String(cloudwatch.StatisticSampleCount)},
}
stats, err := client.GetMetricStatisticsWithContext(ctx, input)
if err != nil {
fmt.Println(err)
return
}
for _, point := range stats.Datapoints {
fmt.Println("SampleCount:", *point.SampleCount)
}
time.Sleep(100 * time.Millisecond)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment