-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmain.go
188 lines (153 loc) · 4.86 KB
/
main.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"context"
"os"
"os/signal"
"syscall"
"time"
"github.com/alecthomas/kingpin"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/buildkite/lifecycled"
cloudwatchlogs "github.com/kdar/logrus-cloudwatchlogs"
"github.com/sirupsen/logrus"
)
var (
Version string
)
func main() {
app := kingpin.New("lifecycled",
"Handle AWS autoscaling lifecycle events gracefully")
app.Version(Version)
app.DefaultEnvars()
var (
instanceID string
snsTopic string
disableSpotListener bool
handler *os.File
jsonLogging bool
debugLogging bool
cloudwatchGroup string
cloudwatchStream string
spotListenerInterval time.Duration
autoscalingHeartbeatInterval time.Duration
)
app.Flag("instance-id", "The instance id to listen for events for").
StringVar(&instanceID)
app.Flag("sns-topic", "The SNS topic that receives events").
StringVar(&snsTopic)
app.Flag("no-spot", "Disable the spot termination listener").
BoolVar(&disableSpotListener)
app.Flag("handler", "The script to invoke to handle events").
Required().
FileVar(&handler)
app.Flag("json", "Enable JSON logging").
BoolVar(&jsonLogging)
app.Flag("cloudwatch-group", "Write logs to a specific Cloudwatch Logs group").
StringVar(&cloudwatchGroup)
app.Flag("cloudwatch-stream", "Write logs to a specific Cloudwatch Logs stream, defaults to instance-id").
StringVar(&cloudwatchStream)
app.Flag("debug", "Show debugging info").
BoolVar(&debugLogging)
app.Flag("spot-listener-interval", "Interval to check for spot instance termination notices").
Default("5s").
DurationVar(&spotListenerInterval)
app.Flag("autoscaling-heartbeat-interval", "Interval to send AWS Lifecycle Heartbeat Actions").
Default("10s").
DurationVar(&autoscalingHeartbeatInterval)
app.Action(func(c *kingpin.ParseContext) error {
logger := logrus.New()
if jsonLogging {
logger.SetFormatter(&logrus.JSONFormatter{})
} else {
logger.SetFormatter(&logrus.TextFormatter{})
}
if debugLogging {
logger.SetLevel(logrus.DebugLevel)
}
region := os.Getenv("AWS_REGION")
if region == "" {
logger.Info("Looking up region from metadata service")
sess, err := session.NewSession()
if err != nil {
logger.WithError(err).Fatal("Failed to create new aws session")
}
region, err = ec2metadata.New(sess).Region()
if err != nil {
logger.WithError(err).Fatal("Failed to look up region")
}
}
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
})
if err != nil {
logger.WithError(err).Fatal("Failed to create new aws session")
}
if instanceID == "" {
logger.Info("Looking up instance id from metadata service")
instanceID, err = ec2metadata.New(sess).GetMetadata("instance-id")
if err != nil {
logger.WithError(err).Fatal("Failed to lookup instance id")
}
}
if cloudwatchStream == "" {
cloudwatchStream = instanceID
}
if cloudwatchGroup != "" {
hook, err := cloudwatchlogs.NewHook(cloudwatchGroup, cloudwatchStream, sess)
if err != nil {
logger.Fatal(err)
}
logger.WithFields(logrus.Fields{
"group": cloudwatchGroup,
"stream": cloudwatchStream,
}).Info("Writing logs to CloudWatch")
logger.AddHook(hook)
if !jsonLogging {
logger.SetFormatter(&logrus.TextFormatter{
DisableColors: true,
DisableTimestamp: true,
})
}
}
sigs := make(chan os.Signal)
defer close(sigs)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigs)
// Create an execution context for the daemon that can be cancelled on OS signal
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for sig := range sigs {
logger.WithField("signal", sig.String()).Info("Received signal: shutting down...")
cancel()
break
}
}()
handler := lifecycled.NewFileHandler(handler)
daemon := lifecycled.New(&lifecycled.Config{
InstanceID: instanceID,
SNSTopic: snsTopic,
SpotListener: !disableSpotListener,
SpotListenerInterval: spotListenerInterval,
AutoscalingHeartbeatInterval: autoscalingHeartbeatInterval,
}, sess, logger)
notice, err := daemon.Start(ctx)
if err != nil {
return err
}
if notice != nil {
log := logger.WithFields(logrus.Fields{"instanceId": instanceID, "notice": notice.Type()})
log.Info("Executing handler")
start, err := time.Now(), notice.Handle(ctx, handler, log)
log = log.WithField("duration", time.Since(start).String())
if err != nil {
log.WithError(err).Error("Failed to execute handler")
}
log.Info("Handler finished successfully")
}
return nil
})
kingpin.MustParse(app.Parse(os.Args[1:]))
}