forked from itsdalmo/ssm-sh
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
388 lines (337 loc) · 10.1 KB
/
manager.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package manager
import (
"bytes"
"context"
"fmt"
"io"
"regexp"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
"github.com/pkg/errors"
)
// TagFilter represents a key=value pair for AWS EC2 tags.
type TagFilter struct {
Key string
Values []string
}
// Filter returns the ec2.Filter representation of the TagFilter.
func (t *TagFilter) Filter() *ec2.Filter {
return &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", t.Key)),
Values: aws.StringSlice(t.Values),
}
}
// CommandOutput is the return type transmitted over a channel when fetching output.
type CommandOutput struct {
InstanceID string
Status string
Output string
OutputUrl string
Error error
}
// Manager handles the clients interfacing with AWS.
type Manager struct {
ssmClient ssmiface.SSMAPI
s3Client s3iface.S3API
ec2Client ec2iface.EC2API
extendOutput bool
region string
s3Bucket string
s3KeyPrefix string
commandComment string
}
type Opts struct {
ExtendOutput bool
S3Bucket string
S3KeyPrefix string
CommandComment string
}
// NewManager creates a new Manager from an AWS session and region.
func NewManager(sess *session.Session, region string, opts Opts) *Manager {
awsCfg := &aws.Config{}
if region != "" {
awsCfg.Region = aws.String(region)
}
m := &Manager{
ssmClient: ssm.New(sess, awsCfg),
s3Client: s3.New(sess, awsCfg),
ec2Client: ec2.New(sess, awsCfg),
region: region,
}
m.extendOutput = opts.ExtendOutput
m.s3Bucket = opts.S3Bucket
m.s3KeyPrefix = opts.S3KeyPrefix
m.commandComment = opts.CommandComment
return m
}
// NewTestManager creates a new manager for testing purposes.
func NewTestManager(ssm ssmiface.SSMAPI, s3 s3iface.S3API, ec2 ec2iface.EC2API) *Manager {
return &Manager{
ssmClient: ssm,
s3Client: s3,
ec2Client: ec2,
region: "eu-west-1",
}
}
// ListInstances fetches a list of instances managed by SSM. Paginates until all responses have been collected.
func (m *Manager) ListInstances(limit int64, tagFilters []*TagFilter) ([]*Instance, error) {
var out []*Instance
input := &ssm.DescribeInstanceInformationInput{
MaxResults: &limit,
}
for {
response, err := m.ssmClient.DescribeInstanceInformation(input)
if err != nil {
return nil, errors.Wrap(err, "failed to describe instance information")
}
ssmInstances, ec2Instances, err := m.describeInstances(response.InstanceInformationList, tagFilters)
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve ec2 instance information")
}
// NOTE: ec2Instances will be a shorter list when filtering is applied.
// E.g. managed on-prem instances will not be there.
for k := range ssmInstances {
out = append(out, NewInstance(ssmInstances[k], ec2Instances[k]))
}
if response.NextToken == nil {
break
}
input.NextToken = response.NextToken
}
return out, nil
}
// ListDocuments fetches a list of documents managed by SSM. Paginates until all responses have been collected.
func (m *Manager) ListDocuments(limit int64, documentFilters []*ssm.DocumentFilter) ([]*DocumentIdentifier, error) {
var out []*DocumentIdentifier
input := &ssm.ListDocumentsInput{
MaxResults: &limit,
DocumentFilterList: documentFilters,
}
for {
response, err := m.ssmClient.ListDocuments(input)
if err != nil {
return nil, errors.Wrap(err, "failed to list document")
}
for _, document := range response.DocumentIdentifiers {
out = append(out, NewDocumentIdentifier(document))
}
if response.NextToken == nil {
break
}
input.NextToken = response.NextToken
}
return out, nil
}
// DescribeDocument lists information for a specific document managed by SSM.
func (m *Manager) DescribeDocument(name string) (*DocumentDescription, error) {
input := &ssm.DescribeDocumentInput{
Name: aws.String(name),
}
response, err := m.ssmClient.DescribeDocument(input)
if err != nil {
return nil, errors.Wrap(err, "failed to describe document")
}
document := NewDocumentDescription(response.Document)
return document, nil
}
// describeInstances retrieves additional information about SSM managed instances from EC2.
func (m *Manager) describeInstances(instances []*ssm.InstanceInformation, tagFilters []*TagFilter) (map[string]*ssm.InstanceInformation, map[string]*ec2.Instance, error) {
var ids []*string
var filters []*ec2.Filter
org := make(map[string]*ssm.InstanceInformation)
out := make(map[string]*ec2.Instance)
for _, instance := range instances {
org[aws.StringValue(instance.InstanceId)] = instance
ids = append(ids, instance.InstanceId)
}
filters = append(filters, &ec2.Filter{
Name: aws.String("instance-id"),
Values: ids,
})
for _, f := range tagFilters {
filters = append(filters, f.Filter())
}
input := &ec2.DescribeInstancesInput{
Filters: filters,
}
for {
response, err := m.ec2Client.DescribeInstances(input)
if err != nil {
return nil, nil, err
}
for _, reservation := range response.Reservations {
for _, instance := range reservation.Instances {
id := aws.StringValue(instance.InstanceId)
out[id] = instance
}
}
if response.NextToken == nil {
break
}
input.NextToken = response.NextToken
}
return org, out, nil
}
// RunCommand on the given instance ids.
func (m *Manager) RunCommand(instanceIds []string, name string, parameters map[string]string) (string, error) {
var params map[string][]*string
if len(parameters) > 0 {
params = make(map[string][]*string)
for k, v := range parameters {
params[k] = aws.StringSlice([]string{v})
}
}
input := &ssm.SendCommandInput{
InstanceIds: aws.StringSlice(instanceIds),
DocumentName: aws.String(name),
Comment: aws.String(m.commandComment),
Parameters: params,
}
if m.s3Bucket != "" {
input.OutputS3BucketName = aws.String(m.s3Bucket)
}
if m.s3KeyPrefix != "" {
input.OutputS3KeyPrefix = aws.String(m.s3KeyPrefix)
}
res, err := m.ssmClient.SendCommand(input)
if err != nil {
return "", err
}
return aws.StringValue(res.Command.CommandId), nil
}
// AbortCommand command on the given instance ids.
func (m *Manager) AbortCommand(instanceIds []string, commandID string) error {
_, err := m.ssmClient.CancelCommand(&ssm.CancelCommandInput{
CommandId: aws.String(commandID),
InstanceIds: aws.StringSlice(instanceIds),
})
if err != nil {
return err
}
return nil
}
// GetCommandOutput fetches the results from a command invocation for all specified instanceIds and
// closes the receiving channel before exiting.
func (m *Manager) GetCommandOutput(ctx context.Context, instanceIds []string, commandID string, out chan<- *CommandOutput) {
defer close(out)
var wg sync.WaitGroup
for _, id := range instanceIds {
wg.Add(1)
go m.pollInstanceOutput(ctx, id, commandID, out, &wg)
}
wg.Wait()
return
}
// Fetch output from a command invocation on an instance.
func (m *Manager) pollInstanceOutput(ctx context.Context, instanceID string, commandID string, c chan<- *CommandOutput, wg *sync.WaitGroup) {
defer wg.Done()
retry := time.NewTicker(time.Millisecond * time.Duration(500))
for {
select {
case <-ctx.Done():
// Main thread is no longer waiting for output
return
case <-retry.C:
// Time to retry at the given frequency
result, err := m.ssmClient.GetCommandInvocation(&ssm.GetCommandInvocationInput{
CommandId: aws.String(commandID),
InstanceId: aws.String(instanceID),
})
if out, ok := m.newCommandOutput(result, err); ok {
c <- out
return
}
}
}
}
func (m *Manager) newCommandOutput(result *ssm.GetCommandInvocationOutput, err error) (*CommandOutput, bool) {
out := &CommandOutput{
InstanceID: aws.StringValue(result.InstanceId),
Status: aws.StringValue(result.StatusDetails),
Output: "",
Error: err,
}
if err != nil {
if strings.HasPrefix(err.Error(), "InvocationDoesNotExist") {
// Needs more time
out.Status = "Pending"
out.Error = nil
} else {
return out, true
}
}
switch out.Status {
case "Pending", "InProgress", "Delayed":
return out, false
case "Cancelled":
out.Output = "Command was cancelled"
return out, true
case "Success":
out.Output = aws.StringValue(result.StandardOutputContent)
out.OutputUrl = aws.StringValue(result.StandardOutputUrl)
if m.extendOutput {
return m.extendTruncatedOutput(*out), true
}
return out, true
case "Failed":
out.Output = aws.StringValue(result.StandardErrorContent)
out.OutputUrl = aws.StringValue(result.StandardErrorUrl)
if m.extendOutput {
return m.extendTruncatedOutput(*out), true
}
return out, true
default:
out.Error = fmt.Errorf("Unrecoverable status: %s", out.Status)
return out, true
}
}
func (m *Manager) extendTruncatedOutput(out CommandOutput) *CommandOutput {
const truncationMarker = "--output truncated--"
if strings.Contains(out.Output, truncationMarker) {
s3out, err := m.readOutput(out.OutputUrl)
if err != nil {
out.Error = errors.Wrap(err, "failed to fetch extended output")
}
out.Output = s3out
return &out
}
return &out
}
func (m *Manager) readOutput(url string) (string, error) {
regex := regexp.MustCompile(`://s3[\-a-z0-9]*\.amazonaws.com/([^/]+)/(.+)|://([^.]+)\.s3\.amazonaws\.com/(.+)`)
matches := regex.FindStringSubmatch(url)
if len(matches) == 0 {
return "", errors.Errorf("failed due to unexpected s3 url pattern: %s", url)
}
bucket := matches[1]
key := matches[2]
out, err := m.readS3Object(bucket, key)
if err != nil {
return "", errors.Wrapf(err, "failed to fetch s3 object: %s", url)
}
return out, nil
}
func (m *Manager) readS3Object(bucket, key string) (string, error) {
output, err := m.s3Client.GetObject(&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
})
if err != nil {
return "", err
}
defer output.Body.Close()
b := bytes.NewBuffer(nil)
if _, err := io.Copy(b, output.Body); err != nil {
return "", err
}
return b.String(), nil
}