-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
85 lines (82 loc) · 2.92 KB
/
handler.js
File metadata and controls
85 lines (82 loc) · 2.92 KB
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
'use strict';
var AWS = require('aws-sdk');
AWS.config.update({region: process.env.AWS_REGION});
var request = require('request');
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
Filters: [
{
Name: 'instance-state-code',
Values: ["16"] // select running instances only
// 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated), 64 (stopping)
},
{
Name: 'tag:serverType', // select matched serverType instances only
Values: [process.env.SERVER_TYPE]
}
]
};
module.exports.ec2Terminator = (event, context, callback) => {
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("Error", err.stack);
} else {
for(let instance of data["Reservations"]) {
console.log(instance)
var featureBranch = null
var repoOwner = null
var repoName = null
for(let tag of instance["Instances"][0]["Tags"]) {
console.log(instance)
if (tag['Key'] === 'featureBranch') {
featureBranch = tag["Value"]
} else if (tag['Key'] === 'repoOwner') {
repoOwner = tag["Value"]
} else if (tag['Key'] === 'repoName') {
repoName = tag["Value"]
}
if (featureBranch && repoOwner && repoName) {
var options = {
url: `https://api.github.com/repos/${repoOwner}/${repoName}/commits/${featureBranch}`,
headers: {
'User-Agent': 'request'
}
};
(function(instance, featureBranch, repoOwner, repoName) {
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
const info = JSON.parse(body);
var commitTime = new Date(info['commit']['committer']['date']);
var currentTime = new Date();
var diffTime = currentTime - commitTime;
var diffDay = Math.floor(diffTime / (24 * 60 * 60e3));
console.log(`Most recent commit of ${repoOwner}/${repoName}:${featureBranch} is ${diffDay} days ago`);
if (diffTime > 3 * 24 * 60 * 60e3) {
var InstanceId = instance["Instances"][0]["InstanceId"]
terminateInstance(InstanceId)
}
}
else {
return error;
}
});
})(instance, featureBranch, repoOwner, repoName);
break;
}
}
}
}
});
function terminateInstance(instanceId) {
ec2.terminateInstances({ InstanceIds: [instanceId] }, function(err, data) {
if(err) {
console.error(err.toString());
} else {
for(var i in data.TerminatingInstances) {
var instance = data.TerminatingInstances[i];
console.log('Terminating instance:\t' + instance.InstanceId);
}
}
});
}
}