UNPKG

domotz-remote-pawn

Version:

Domotz Agent

70 lines (55 loc) 2.62 kB
/** 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 HOUR_IN_MILLISECONDS = 1000 * 60 * 60; const WARM_UP_EXPECTED_DELAY_DEFAULT = 20 * 60; // 20 minutes const GRACEFUL_SHUTDOWN_PLATFORMS = ['luxul', 'openwrt', 'ubuntu_core', 'win', 'netgear_router']; const START_HOUR = 1; const INTERVAL_LENGTH_IN_HOURS = 4; var scheduledRestart = function (resourceLocator) { var myConsole = resourceLocator.log.decorateLogs(); var status = resourceLocator.status; if (status.get() !== status.CONFIGURED) { myConsole.info(' The agent is not in configured mode. Skip'); return; } var utils = resourceLocator.utils; function hasCurrentPlatformGracefulShutdown() { return GRACEFUL_SHUTDOWN_PLATFORMS.indexOf(process.env.DPLATFORM) !== -1; } function getScheduledRestartDelay(now) { var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()); midnight.setDate(midnight.getDate() + 1); var rebootTime = new Date(midnight.getTime() + (Math.random() * INTERVAL_LENGTH_IN_HOURS + START_HOUR) * HOUR_IN_MILLISECONDS); return rebootTime - new Date(); } var now = new Date(); var serviceRestart = hasCurrentPlatformGracefulShutdown() ? utils.proc.gracefulShutdown : utils.proc.restart; var restartDelay = getScheduledRestartDelay(now); var bootNotificationDelay = parseInt(resourceLocator.configuration.warm_up_expected_delay || WARM_UP_EXPECTED_DELAY_DEFAULT) * 1000; var restartTime = new Date(now.getTime() + restartDelay); myConsole.info( ' Set services restart at %s. Delay: %s ms. Notify the successful ' + 'boot in %s ms', restartTime, restartDelay, bootNotificationDelay ); setTimeout(serviceRestart, restartDelay); return restartDelay; // For testing purposes }; module.exports.handler = scheduledRestart;