-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·197 lines (170 loc) · 5.95 KB
/
index.js
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
#!/usr/bin/env node
import { pathToFileURL } from "url";
import { realpathSync } from "fs";
import readline from "readline";
import util from "util";
import { DescribeStacksCommand, ListStacksCommand } from "@aws-sdk/client-cloudformation";
import chalk from "chalk";
import randomColor from "randomcolor";
import cfnEvents from "./lib/cfn-events.js";
import helpers from "./lib/helpers.js";
import output from "./lib/output.js";
const IN_PROGRESS_STATUSES = [
"CREATE_IN_PROGRESS",
"DELETE_IN_PROGRESS",
"REVIEW_IN_PROGRESS",
"ROLLBACK_IN_PROGRESS",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_IN_PROGRESS",
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_ROLLBACK_IN_PROGRESS",
];
const seenStackArns = new Set();
const monitoredStackArns = new Set();
/**
* Checks the given input for CloudFormation stack ARN and
* starts to monitor a stack if one is found from the given
* input.
*
* @param {String} input the input to parse
*/
async function maybeStartToMonitorStack(input) {
const info = helpers.getStackInfoFromInput(input);
if (!info) {
return;
}
seenStackArns.add(info.arn);
const color = randomColor();
const cfn = helpers.getCloudFormationClient({ region: info.region });
const cmd = new DescribeStacksCommand({ StackName: info.arn });
const res = await cfn.send(cmd).catch((err) => {
if (err.message.endsWith("does not exist")) {
output.write(chalk.hex(color)(info.name), "Stack does not exist");
return;
}
throw err;
});
if (!res) {
return;
}
const stack = res.Stacks[0];
const status = stack.StackStatus;
if (!status.endsWith("_IN_PROGRESS")) {
output.write(chalk.hex(color)(info.name), "No operations ongoing");
return;
}
if (monitoredStackArns.has(info.arn)) {
// Skip this stack. It's being monitored already.
return;
}
monitoredStackArns.add(info.arn);
const nestedStacks = [];
for await (const e of cfnEvents.streamStackEvents(stack.StackName, stack.StackId, info.region)) {
const reason = e.ResourceStatusReason ? util.format(" (Reason: %s)", e.ResourceStatusReason) : "";
output.write(
util.format(
"%s %s %s %s %s %s",
chalk.hex(color)(info.name),
e.Timestamp.toISOString(),
e.ResourceStatus,
e.ResourceType,
e.LogicalResourceId,
reason,
),
);
if (e.ResourceType === "AWS::CloudFormation::Stack" && e.StackId !== e.PhysicalResourceId) {
// This event was about nested stack. Start to monitor that as well
nestedStacks.push(maybeStartToMonitorStack(e.PhysicalResourceId));
}
}
monitoredStackArns.delete(info.arn);
await Promise.all(nestedStacks);
}
async function startToMonitorInProgressStacks() {
const cfn = helpers.getCloudFormationClient({});
const cmd = new ListStacksCommand({ StackStatusFilter: IN_PROGRESS_STATUSES });
const res = await cfn.send(cmd);
const stacks = res.StackSummaries;
if (stacks.length === 0) {
output.write(`${chalk.green("INFO")}: No stacks are being created / deleted / updated.`);
return;
}
output.write(`${chalk.green("INFO")}: ${stacks.length} stack${stacks.length === 1 ? " is" : "s are"} being changed.`);
await Promise.all(stacks.map((stack) => maybeStartToMonitorStack(stack.StackId)));
}
async function startToMonitorDeletingStacks() {
const cfn = helpers.getCloudFormationClient({});
const cmd = new ListStacksCommand({ StackStatusFilter: ["DELETE_IN_PROGRESS"] });
const res = await cfn.send(cmd);
const stacks = res.StackSummaries;
if (stacks.length === 0) {
output.write(`${chalk.green("INFO")}: No stacks are being deleted.`);
return;
}
output.write(`${chalk.green("INFO")}: ${stacks.length} stack${stacks.length === 1 ? " is" : "s are"} being deleted.`);
await Promise.all(stacks.map((stack) => maybeStartToMonitorStack(stack.StackId)));
}
async function run() {
const promises = [];
// See if we have a stack ARN(s) given as command line argument(s)
if (process.argv.length > 2) {
process.argv.slice(2).forEach((arg) => {
promises.push(maybeStartToMonitorStack(arg));
});
}
// Also check if we have been piped some input and detect stack
// IDs from there
if (!process.stdin.isTTY) {
const rl = readline.createInterface({
input: process.stdin,
});
let isDeploy = false;
let hasContent = false;
rl.on("line", (line) => {
// echo to stdout
console.log(line);
promises.push(maybeStartToMonitorStack(line));
hasContent = true;
if (!isDeploy && line.match(/Waiting for stack create\/update to complete/)) {
output.write(
chalk.green("INFO") +
": The command piped to cfn-monitor " +
"seems to be aws cloudformation deploy. The command does not echo the " +
"stack name it is operating on. Starting to monitor all stacks that are " +
"being modified.",
);
isDeploy = true;
promises.push(startToMonitorInProgressStacks());
}
});
await new Promise((resolve) => {
rl.on("close", () => {
if (!hasContent) {
output.write(
chalk.green("INFO") +
": The command piped to cfn-monitor " +
"did not produce any output. Assuming it was a delete-stack operation. " +
"Starting to monitor stacks that are being deleted.",
);
promises.push(startToMonitorDeletingStacks());
}
resolve();
});
});
} else {
if (!seenStackArns.size) {
output.write(
chalk.green("INFO") +
": No input nor stacks from the command " +
"line. Starting to monitor all stacks that are being modified.",
);
promises.push(startToMonitorInProgressStacks());
}
}
return promises;
}
/* istanbul ignore next */
if (import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
run();
}
export { maybeStartToMonitorStack, run, startToMonitorDeletingStacks, startToMonitorInProgressStacks };