domotz-remote-pawn
Version:
Domotz Agent
75 lines (59 loc) • 2.65 kB
JavaScript
/** This file is part of Domotz Agent.
* Copyright (C) 2016 Domotz Ltd
*
* Domotz Agent is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Domotz Agent is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Domotz Agent. If not, see <http://www.gnu.org/licenses/>.
**/
/**
* Created by Tommaso Latini <tommaso@domotz.com> on 20/01/16.
*/
const LOG_EVENT = 'HANDLER - (suicide)';
const HOUR_IN_MILLISECONDS = 1000 * 60 * 60;
const RETRY_ATTEMPTS = 5;
const RETRY_DELAY = 3000;
const WARM_UP_EXPECTED_DELAY_DEFAULT = 20 * 60; //20 minutes
var send_options = {
maxAttempts: RETRY_ATTEMPTS ,retryDelay: RETRY_DELAY
};
var suicide = function(resourceLocator) {
var status = resourceLocator.status;
if (status.get() !== status.CONFIGURED) {
console.info(LOG_EVENT + ': The agent is not in configured mode. Skip');
return;
}
var serviceRestart = resourceLocator.utils.proc.restart;
var timeUtils = resourceLocator.utils.time;
var eventUtils = resourceLocator.utils.event;
var send = resourceLocator.engineRequest.send;
var sendWithPromise = resourceLocator.engineRequest.sendWithPromise;
var warmUpDelay = resourceLocator.configuration.warm_up_expected_delay || WARM_UP_EXPECTED_DELAY_DEFAULT;
var delta = timeUtils.getDeltaToThreeOClock(resourceLocator);
var delay = delta + Math.floor(Math.random() * HOUR_IN_MILLISECONDS);
var now = new Date();
var restartTime = new Date(now.getTime() + delay);
console.info('%s: Set services restart at %s. Delay: %s ms.', LOG_EVENT, restartTime, delay);
var resource = '/event';
var method = 'POST';
function restart () {
var body = eventUtils.getBodyForEvent("down", "scheduled");
sendWithPromise(resource, method, body, undefined, undefined, send_options).finally(serviceRestart);
}
function sendUpSignal () {
var body = eventUtils.getBodyForEvent("up", "boot");
send(resource, method, body, undefined, undefined, undefined, send_options);
}
setTimeout(sendUpSignal, (warmUpDelay * 1000));
setTimeout(restart, delay);
return delay; // For testing purposes
};
module.exports.handler = suicide;