forked from LeanerCloud/AutoSpotting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autospotting.go
94 lines (77 loc) · 2.41 KB
/
autospotting.go
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
// Copyright (c) 2016-2019 Cristian Măgherușan-Stanciu
// Licensed under the Open Software License version 3.0
package main
import (
"context"
"encoding/json"
"log"
"os"
autospotting "github.com/AutoSpotting/AutoSpotting/core"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
var conf autospotting.Config
// Version represents the build version being used
var Version = "number missing"
func main() {
if os.Getenv("AWS_LAMBDA_FUNCTION_NAME") != "" {
lambda.Start(Handler)
} else {
run()
}
}
func run() {
log.Println("Starting autospotting agent, build", Version)
log.Printf("Configuration flags: %#v", conf)
autospotting.Run(&conf)
log.Println("Execution completed, nothing left to do")
}
// this is the equivalent of a main for when running from Lambda, but on Lambda
// the run() is executed within the handler function every time we have an event
func init() {
conf = autospotting.Config{
Version: Version,
}
autospotting.ParseConfig(&conf)
}
// Handler implements the AWS Lambda handler
func Handler(ctx context.Context, rawEvent json.RawMessage) {
var snsEvent events.SNSEvent
var cloudwatchEvent events.CloudWatchEvent
parseEvent := rawEvent
// Try to parse event as an Sns Message
if err := json.Unmarshal(parseEvent, &snsEvent); err != nil {
log.Println(err.Error())
return
}
// If event is from Sns - extract Cloudwatch's one
if snsEvent.Records != nil {
snsRecord := snsEvent.Records[0]
parseEvent = []byte(snsRecord.SNS.Message)
}
// Try to parse event as Cloudwatch Event Rule
if err := json.Unmarshal(parseEvent, &cloudwatchEvent); err != nil {
log.Println(err.Error())
return
}
// If event is Instance Spot Interruption
if cloudwatchEvent.DetailType == "EC2 Spot Instance Interruption Warning" {
instanceID, err := autospotting.GetInstanceIDDueForTermination(cloudwatchEvent)
if err != nil || instanceID == nil {
return
}
spotTermination := autospotting.NewSpotTermination(cloudwatchEvent.Region)
if spotTermination.IsInAutoSpottingASG(instanceID, conf.TagFilteringMode, conf.FilterByTags) {
err := spotTermination.ExecuteAction(instanceID, conf.TerminationNotificationAction)
if err != nil {
log.Printf("Error executing spot termination action: %s\n", err.Error())
}
} else {
log.Printf("Instance %s is not in AutoSpotting ASG\n", *instanceID)
return
}
} else {
// Event is Autospotting Cron Scheduling
run()
}
}