This repository has been archived on 2025-12-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
qmi-cloud/server/stop5.js
Manuel Romero a42eb85772 fix
2020-04-20 13:19:36 +02:00

144 lines
4.6 KiB
JavaScript

var myArgs = process.argv.slice(2);
if ( myArgs.length < 3 ) {
console.log("Missing args", myArgs);
process.exit(0);
}
var db = require('./mongo');
const sendEmail = require("./send-email");
const moment = require('moment');
const azurecli = require('./azurecli');
const IS_REAL = myArgs[2] !== 'test';
const RUNNING_PERIOD = 4; //Days
const RUNNING_LIMIT_HOURS_WARNING = myArgs[1]*(RUNNING_PERIOD-1);
const RUNNING_LIMIT_HOURS_STOP = myArgs[1]*RUNNING_PERIOD;
function timeRunning(p) {
let runningFromTime = p.runningFrom? new Date(p.runningFrom).getTime() : new Date(p.created).getTime();
let totalRunningFromTime;
if (p.statusVms !== 'Stopped' && p.statusVms !== 'Starting' && !p.isDestroyed) {
totalRunningFromTime = Math.abs(new Date().getTime() - runningFromTime);
}
let duration = moment.duration(totalRunningFromTime);
p.duration = {
hours: Math.floor(duration.asHours()),
complete: Math.floor(duration.asDays()) +"d "+duration.hours()+"h "+duration.minutes()
};
}
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
async function init(type) {
var limit, cb;
var filter = {
"isDestroyed":false,
"isDeleted": false,
"statusVms": "Running"
};
if ( type === "warning" ) {
limit = RUNNING_LIMIT_HOURS_WARNING;
filter.pendingNextAction = {$ne: "stopVms"};
cb = doSendEmailWarning;
} else if ( type === "stop" ) {
limit = RUNNING_LIMIT_HOURS_STOP;
filter.pendingNextAction = "stopVms";
cb = doSendEmailStop;
} else {
console.log("Invalid 'type'. Do nothing.");
return;
}
let provisions = await db.provision.get(filter);
let scenarios = await db.scenario.get();
await asyncForEach(provisions, async function(p) {
var _scenario = scenarios.filter(s=>{
return s.name === p.scenario
});
if ( _scenario.length ){
p._scenario = _scenario[0];
}
timeRunning(p);
console.log(p._id, "limit: " +limit, "duration:"+p.duration.hours);
if ( p.duration && p.duration.hours >= limit) {
await cb(p);
}
});
}
const doSendEmailStop = async function(p) {
let id = p._id.toString();
try {
console.log(`STOP VM!! - Send Warning Email to ${p.user.displayName} (${p.user.upn}) about provision '${p._scenario.title}' (${p._id}) being 'Running' more than ${RUNNING_LIMIT_HOURS_STOP} hours (exactly ${p.duration.complete})`);
if ( IS_REAL ) {
await db.provision.update(id, {"statusVms": "Stopping"});
await azurecli.deallocate(p);
await sendEmail.sendVMsStopped(p, p._scenario);
db.notification.add({
provision: p._id,
type: 'stop',
message: `VMs stopped for provision '${p._scenario.title}' (${p._id})`
});
}
await db.provision.update(p._id, {"pendingNextAction": undefined});
} catch (error) {
console.log("doSendEmailStop Error", error);
await db.provision.update(id, {"statusVms": "Error_Stopping"});
}
}
const doSendEmailWarning = async function(p) {
if ( p.pendingNextAction === 'stopVms') {
console.log(`Warning Email already sent. Wait for pending action to complete.`);
} else {
console.log(`Send Warning Email to ${p.user.displayName} (${p.user.upn}) about provision '${p._scenario.title}' (${p._id}) being 'Running' more than ${RUNNING_LIMIT_HOURS_WARNING} hours (exactly ${p.duration.complete})`);
if ( IS_REAL ) {
await sendEmail.sendWillStopIn24(p, p._scenario);
db.notification.add({
provision: p._id,
type: 'warningStop',
message: `Provision '${p._scenario.title}' (${p._id}) being 'Running' more than ${RUNNING_LIMIT_HOURS_WARNING} hours (exactly ${p.duration.complete})`
});
}
await db.provision.update(p._id, {"pendingNextAction": "stopVms"});
}
}
function check(type) {
init(type).then(function(){
db.mongoose.connection.close()
process.exit(0);
}).catch(function(e){
db.mongoose.connection.close()
console.log("Error", e);
process.exit(0);
});
}
// --------------------------------
switch (myArgs[0]) {
case 'warning':
check("warning");
break;
case 'stop':
check("stop");
break;
default:
console.log('Sorry, that is not something I know how to do.');
process.exit(0);
}