-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
274 lines (244 loc) · 9.34 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
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
'use strict';
/**
* Serverless Autoprune Plugin
* Kenneth Falck <[email protected]> 2016
*/
module.exports = function(S) {
const path = require('path'),
fs = require('fs'),
SUtils = require(S.getServerlessPath('utils')),
SCli = require(S.getServerlessPath('utils/cli')),
SError = require(S.getServerlessPath('Error')),
BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)
/**
* ServerlessPluginAutoprune
*/
class ServerlessPluginAutoprune extends S.classes.Plugin {
/**
* Constructor
* - Keep this and don't touch it unless you know what you're doing.
*/
constructor() {
super();
}
/**
* Define your plugins name
* - We recommend adding prefixing your personal domain to the name so people know the plugin author
*/
static getName() {
return 'net.kfalck.' + ServerlessPluginAutoprune.name;
}
/**
* Register Actions
* - If you would like to register a Custom Action or overwrite a Core Serverless Action, add this function.
* - If you would like your Action to be used programatically, include a "handler" which can be called in code.
* - If you would like your Action to be used via the CLI, include a "description", "context", "action" and any options you would like to offer.
* - Your custom Action can be called programatically and via CLI, as in the example provided below
*/
registerActions() {
S.addAction(this.autoprune.bind(this), {
handler: 'functionAutoprune',
description: 'Automatically deletes old Lambda function versions not attached to a stage',
context: 'function',
contextAction: 'autoprune',
options: [
{
option: 'stage',
shortcut: 's',
description: 'Optional if only one stage is defined in project'
}, {
option: 'region',
shortcut: 'r',
description: 'Optional - Target one region to deploy to'
}, {
option: 'all',
shortcut: 'a',
description: 'Autoprune all functions'
}
],
parameters: [
{
parameter: 'function',
description: 'Function to autoprune (use -a for all)',
position: '0->'
}
]
});
return BbPromise.resolve();
}
/**
* Register Hooks
* - If you would like to register hooks (i.e., functions) that fire before or after a core Serverless Action or your Custom Action, include this function.
* - Make sure to identify the Action you want to add a hook for and put either "pre" or "post" to describe when it should happen.
*/
registerHooks() {
S.addHook(this._hookPostFunctionDeploy.bind(this), {
action: 'functionDeploy',
event: 'post'
});
return BbPromise.resolve();
}
autoprune(evt) {
var promise = BbPromise.resolve();
var project = S.getProject();
var functions = project.functions;
var found = 0;
var stage = evt.options.stage;
var region = evt.options.region;
var stats = {deleted:0, kept:0, skipped:0};
if (!evt.options.all && !evt.options.function.length) {
return BbPromise.reject(new SError('Function name or -a required'));
}
if (stage && !project.validateStageExists(stage)) {
return BbPromise.reject(new SError(`Stage ${stage} doesnt exist in this project!`))
}
return BbPromise.resolve()
.then(() => {
if (!stage) {
return this.cliPromptSelectStage('Function Autoprune - Choose a stage: ', stage, false)
.then(aStage => {
stage = aStage;
});
}
})
.then(() => {
if (stage && region && !proj.validateRegionExists(stage, region)) {
return BbPromise.reject(new SError(`Region ${region} doesnt exist in stage ${stage}!`))
}
// Select default region in stage if not specified
if (stage && !region) {
var stageObj = project.getStage(stage);
var regions = stageObj.getAllRegions();
if (regions.length == 1) {
region = regions[0].getName();
} else {
return BbPromise.reject(new SError('Region has multiple stages, specify one with -r'));
}
}
Object.keys(functions).map((functionName) => {
if (evt.options.all || evt.options.function.indexOf(functionName) >= 0) {
found += 1;
promise = promise.then(() => {
return this.autopruneFunction({stage:stage, region:region, stats:stats}, functions[functionName]);
});
}
});
if (evt.options.function.length && found < evt.options.function.length) {
return BbPromise.reject(new SError('Function not found'));
}
return promise;
})
.then(() => {
SCli.log('Autoprune deleted ' + stats.deleted + ', kept ' + stats.kept + ' and skipped ' + stats.skipped + ' function version(s)');
return evt;
});
}
/**
* Post deploy prune hook
* - Be sure to ALWAYS accept and return the "evt" object, or you will break the entire flow.
* - The "evt" object contains Action-specific data. You can add custom data to it, but if you change any data it will affect subsequent Actions and Hooks.
* - You can also access other Project-specific data @ S Again, if you mess with data on this object, it could break everything, so make sure you know what you're doing ;)
*/
_hookPostFunctionDeploy(evt) {
var self = this;
var promise = BbPromise.resolve();
var stats = {deleted:0, kept:0, skipped:0};
Object.keys(evt.data.deployed || []).map(function (region) {
evt.data.deployed[region].map(function (deployed) {
var func = S.getProject().getFunction(deployed.functionName);
promise = promise.then(function () {
return self.autopruneFunction({stage:evt.options.stage, region:region, stats:stats}, func)
});
});
});
return promise.then(function () {
SCli.log('Autoprune deleted ' + stats.deleted + ', kept ' + stats.kept + ' and skipped ' + stats.skipped + ' function version(s)');
return evt;
});
}
listAllAliases(aws, stage, region, functionName) {
var self = this;
var allAliases = [];
function getMore(nextMarker) {
return aws.request('Lambda', 'listAliases', {
FunctionName: functionName,
Marker: nextMarker
}, stage, region)
.then(function (response) {
allAliases = allAliases.concat(response.Aliases);
if (response.NextMarker) {
return getMore(response.NextMarker);
} else {
return allAliases;
}
});
}
return getMore();
}
listAllVersions(aws, stage, region, functionName) {
var self = this;
var allVersions = [];
function getMore(nextMarker) {
return aws.request('Lambda', 'listVersionsByFunction', {
FunctionName: functionName,
Marker: nextMarker
}, stage, region)
.then(function (response) {
allVersions = allVersions.concat(response.Versions);
if (response.NextMarker) {
return getMore(response.NextMarker);
} else {
return allVersions;
}
});
}
return getMore();
}
autopruneFunction(options, func) {
var self = this;
var functionName = func.getDeployedName(options);
var versions;
var aliases;
var aliasMap = {};
return self.listAllVersions(S.providers.aws, options.stage, options.region, functionName)
.then(function (aVersions) {
versions = aVersions;
return self.listAllAliases(S.providers.aws, options.stage, options.region, functionName);
})
.then(function (aAliases) {
aliases = aAliases;
if (!aliases.length) {
// No aliases, don't autoprune everything
//SCli.log('Skipping autoprune for ' + functionName + ' because it has no aliases defined.');
options.stats.skipped += 1;
return;
}
aliases.map(function (alias) {
aliasMap[alias.FunctionVersion] = alias.Name;
});
var promise = BbPromise.resolve();
versions.map(function (version) {
if (version.Version.match(/^\d+$/)) {
if (!aliasMap[version.Version]) {
promise = promise.then(function () {
//SCli.log('Autopruning ' + functionName + ' version ' + version.Version);
options.stats.deleted += 1;
return S.providers.aws.request('Lambda', 'deleteFunction', {
FunctionName: functionName,
Qualifier: version.Version
}, options.stage, options.region);
});
} else {
//SCli.log('Keeping ' + functionName + ' version ' + version.Version + ' (has alias ' + aliasMap[version.Version] + ')');
options.stats.kept += 1;
}
}
});
return promise;
});
}
}
// Export Plugin Class
return ServerlessPluginAutoprune;
};
// Godspeed!