From 2e28f86fd5fa1d555f4eae2cb9f6cc14fb70c34d Mon Sep 17 00:00:00 2001 From: Luis Fernando Molina Date: Wed, 6 Jun 2018 16:27:51 +0200 Subject: [PATCH] Logging functionality re-written, all modules affected --- Assistant.js | 251 +++++++------- AzureStorage.js | 15 +- BlobStorage.js | 168 +++++---- CloudRequire.js | 23 +- CloudUtilities.js | 25 +- Context.js | 133 ++++---- DataDependencies.js | 21 +- DataSet.js | 43 ++- DebugLog.js | 148 +++----- EventHandler.js | 63 ---- ExchangeAPI.js | 95 +++--- ExtractionBotProcessMainLoop.js | 488 +++++++++++++------------- IndicatorBotProcessMainLoop.js | 449 ++++++++++++------------ PoloniexAPIClient.js | 15 +- Project.njsproj | 1 - Root.js | 201 ++++++----- StatusDependencies.js | 41 +-- StatusReport.js | 118 ++++--- TradingBotProcessMainLoop.js | 588 ++++++++++++++++---------------- 19 files changed, 1362 insertions(+), 1524 deletions(-) delete mode 100644 EventHandler.js diff --git a/Assistant.js b/Assistant.js index 73c8f909a..a470b691d 100644 --- a/Assistant.js +++ b/Assistant.js @@ -1,4 +1,4 @@ -exports.newAssistant = function newAssistant(BOT, DEBUG_MODULE, UTILITIES) { +exports.newAssistant = function newAssistant(BOT, logger, UTILITIES) { /* @@ -10,11 +10,6 @@ let bot = BOT; - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(); - let thisObject = { dataDependencies: undefined, initialize: initialize, @@ -30,7 +25,7 @@ sendMessage: sendMessage }; - let utilities = UTILITIES.newCloudUtilities(bot); + let utilities = UTILITIES.newCloudUtilities(bot, logger); let exchangePositions = []; // These are the open positions at the exchange at the account the bot is authorized to use. let openPositions = []; // These are the open positions the bot knows it made by itself. @@ -47,7 +42,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } /* Save local values. */ @@ -73,8 +68,8 @@ } default: { - logger.write("[ERROR] initialize -> Unexpected bot.startMode."); - logger.write("[ERROR] initialize -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] initialize -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] initialize -> bot.startMode = " + bot.startMode); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -84,7 +79,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getMarketRateFromExchange -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromExchange -> Entering function."); } exchangeAPI.getTicker(global.MARKET.assetA + '_' + global.MARKET.assetB, onTicker); @@ -94,11 +89,11 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getMarketRateFromExchange -> onTicker -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromExchange -> onTicker -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getMarketRateFromExchange -> onTicker -> We could not get the Market Price now."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromExchange -> onTicker -> We could not get the Market Price now."); } callBackFunction(err); return; @@ -112,13 +107,13 @@ validateExchangeSyncronicity(); } catch (err) { - logger.write("[ERROR] initialize -> getMarketRateFromExchange -> onTicker -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getMarketRateFromExchange -> onTicker -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] initialize -> getMarketRateFromExchange -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getMarketRateFromExchange -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -127,7 +122,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getMarketRateFromIndicator -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromIndicator -> Entering function."); } /* Procedure to get the current market rate. */ @@ -138,7 +133,7 @@ global.PLATFORM_CONFIG.marketRateProvider.dataSet + "-" + global.PLATFORM_CONFIG.marketRateProvider.dataSetVersion; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getMarketRateFromIndicator -> key = " + key); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromIndicator -> key = " + key); } let dataSet = thisObject.dataDependencies.dataSets.get(key); @@ -150,8 +145,8 @@ function onFileReceived(err, text) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getMarketRateFromIndicator -> onFileReceived -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] initialize -> getMarketRateFromIndicator -> onFileReceived -> text = " + text); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromIndicator -> onFileReceived -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromIndicator -> onFileReceived -> text = " + text); } let candleArray; @@ -197,18 +192,18 @@ } } catch (err) { - logger.write("[ERROR] initialize -> getMarketRateFromIndicator -> onFileReceived -> err = " + err.message); - logger.write("[ERROR] initialize -> getMarketRateFromIndicator -> onFileReceived -> Asuming this is a temporary situation. Requesting a Retry."); + logger.write(MODULE_NAME, "[ERROR] initialize -> getMarketRateFromIndicator -> onFileReceived -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getMarketRateFromIndicator -> onFileReceived -> Asuming this is a temporary situation. Requesting a Retry."); callBackFunction(global.DEFAULT_RETRY_RESPONSE); } } else { - logger.write("[ERROR] initialize -> getMarketRateFromIndicator -> onFileReceived -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getMarketRateFromIndicator -> onFileReceived -> err = " + err.message); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] initialize -> getMarketRateFromIndicator -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getMarketRateFromIndicator -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -217,7 +212,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> validateExchangeSyncronicity -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> validateExchangeSyncronicity -> Entering function."); } /* Procedure to validate we are in sync with the exchange. */ @@ -226,23 +221,23 @@ function onDone(err) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> validateExchangeSyncronicity -> onDone -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> validateExchangeSyncronicity -> onDone -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] initialize -> validateExchangeSyncronicity -> onDone -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] initialize -> validateExchangeSyncronicity -> onDone -> Execution finished well."); calculateProfits(); return; } break; case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] initialize -> validateExchangeSyncronicity -> onDone -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] initialize -> validateExchangeSyncronicity -> onDone -> Retry Later. Requesting Execution Retry."); callBackFunction(err); return; } break; case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] initialize -> validateExchangeSyncronicity -> onDone -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] initialize -> validateExchangeSyncronicity -> onDone -> Operation Failed. Aborting the process."); callBackFunction(err); return; } @@ -250,13 +245,13 @@ } } catch (err) { - logger.write("[ERROR] initialize -> validateExchangeSyncronicity -> onDone -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> validateExchangeSyncronicity -> onDone -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] initialize -> onDone -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> onDone -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -265,7 +260,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> calculateProfits -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> calculateProfits -> Entering function."); } /* Calculate Profits */ @@ -304,14 +299,14 @@ callBackFunction(global.DEFAULT_OK_RESPONSE); } catch (err) { - logger.write("[ERROR] initialize -> calculateProfits -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> calculateProfits -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -320,7 +315,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getPositionsAtExchange -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> Entering function."); } /* @@ -334,14 +329,14 @@ case "Live": { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getPositionsAtExchange -> Live Mode Detected."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> Live Mode Detected."); } exchangeAPI.getOpenPositions(global.MARKET, onResponse); break; } case "Backtest": { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getPositionsAtExchange -> Backtest Mode Detected."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> Backtest Mode Detected."); } let exchangePositions = []; // We simulate all positions were executed. onResponse(global.DEFAULT_OK_RESPONSE, exchangePositions); break; @@ -349,14 +344,14 @@ case "Competition": { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getPositionsAtExchange -> Competition Mode Detected."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> Competition Mode Detected."); } exchangeAPI.getOpenPositions(global.MARKET, onResponse); break; } default: { - logger.write("[ERROR] getPositionsAtExchange -> Unexpected bot.startMode."); - logger.write("[ERROR] getPositionsAtExchange -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] getPositionsAtExchange -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] getPositionsAtExchange -> bot.startMode = " + bot.startMode); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -364,25 +359,25 @@ function onResponse(err, pExchangePositions) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getPositionsAtExchange -> onResponse -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getPositionsAtExchange -> onResponse -> pExchangePositions = " + JSON.stringify(pExchangePositions)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> onResponse -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> onResponse -> pExchangePositions = " + JSON.stringify(pExchangePositions)); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. - logger.write("[INFO] getPositionsAtExchange -> onResponse -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] getPositionsAtExchange -> onResponse -> Execution finished well."); exchangePositions = pExchangePositions; ordersExecutionCheck(callBack); return; } break; case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] getPositionsAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] getPositionsAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); callBack(err); return; } break; case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] getPositionsAtExchange -> onResponse -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] getPositionsAtExchange -> onResponse -> Operation Failed. Aborting the process."); callBack(err); return; } @@ -390,7 +385,7 @@ } } } catch (err) { - logger.write("[ERROR] getPositionsAtExchange -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] getPositionsAtExchange -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } @@ -399,7 +394,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> Entering function."); } /* @@ -443,7 +438,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> Entering function."); } let position = context.executionContext.positions[i]; let exchangePosition; @@ -463,7 +458,7 @@ function positionFound() { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> positionFound -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> positionFound -> Entering function."); } /* @@ -490,7 +485,7 @@ function positionNotFound() { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> positionNotFound -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> positionNotFound -> Entering function."); } /* Position not found: we need to know if the order was executed. */ @@ -502,8 +497,8 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> pPositionId = " + pPositionId); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> pPositionId = " + pPositionId); } /* @@ -515,7 +510,7 @@ case "Live": { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Live Mode Detected."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Live Mode Detected."); } exchangeAPI.getExecutedTrades(pPositionId, onResponse); return; @@ -523,7 +518,7 @@ case "Backtest": { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Backtest Mode Detected."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Backtest Mode Detected."); } let trades = []; @@ -558,21 +553,21 @@ } } - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Position not found at Executioin Context."); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Position not found at Executioin Context."); callBack(global.DEFAULT_FAIL_RESPONSE); return; } case "Competition": { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Competition Mode Detected."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Competition Mode Detected."); } exchangeAPI.getExecutedTrades(pPositionId, onResponse); return; } default: { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Unexpected bot.startMode."); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> bot.startMode = " + bot.startMode); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -581,34 +576,34 @@ function onResponse(err, pTrades) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. - logger.write("[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Execution finished well."); innerCallBack(pTrades); } break; case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); callBack(global.DEFAULT_RETRY_RESPONSE); return; } break; case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Operation Failed. Aborting the process."); callBack(global.DEFAULT_FAIL_RESPONSE); return; } break; } } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } @@ -617,8 +612,8 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> pTrades = " + JSON.stringify(pTrades)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> pTrades = " + JSON.stringify(pTrades)); } /* @@ -641,12 +636,12 @@ sumAssetB = Number(sumAssetB.toFixed(8)); if (position.amountB !== sumAssetB) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> position.amountB = " + position.amountB); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> sumAssetB = " + sumAssetB); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> position.amountB = " + position.amountB); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> sumAssetB = " + sumAssetB); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> Cannot be confirmed that the order was executed. It must be manually cancelled by the user or cancelled by the exchange itself."); - logger.write("[HINT] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> If the process was abruptally cancelled and then restarted, it is possible that now is not sincronized with the exchange."); - logger.write("[HINT] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> In any case, to continue, you must manually delete the orders at the exchange."); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> Cannot be confirmed that the order was executed. It must be manually cancelled by the user or cancelled by the exchange itself."); + logger.write(MODULE_NAME, "[HINT] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> If the process was abruptally cancelled and then restarted, it is possible that now is not sincronized with the exchange."); + logger.write(MODULE_NAME, "[HINT] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> In any case, to continue, you must manually delete the orders at the exchange."); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -679,7 +674,7 @@ next(); } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -688,7 +683,7 @@ function confirmOrderWasPartiallyExecuted(pTrades) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> Entering function."); } /* @@ -716,12 +711,12 @@ sumAssetB = Number(sumAssetB.toFixed(8)); if (position.amountA !== sumAssetA || position.amountB !== sumAssetB ) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> position.amountA = " + position.amountA); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> sumAssetA = " + sumAssetA); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> position.amountB = " + position.amountB); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> sumAssetB = " + sumAssetB); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> position.amountA = " + position.amountA); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> sumAssetA = " + sumAssetA); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> position.amountB = " + position.amountB); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> sumAssetB = " + sumAssetB); - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> Cannot be confirmed that a partially execution was done well."); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> Cannot be confirmed that a partially execution was done well."); /* There are diferences on the responses between the getPosition and getTrades that causes some issues, let's retry. */ callBack(global.DEFAULT_RETRY_RESPONSE); @@ -752,7 +747,7 @@ next(); } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -762,7 +757,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> loopBody -> applyTradesToContext -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> applyTradesToContext -> Entering function."); } /* Here we apply the trades that already happened at the exchange to the balance and available balance of the bot. We also calculate its profits. */ @@ -805,14 +800,14 @@ } } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> applyTradesToContext -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> applyTradesToContext -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> loopBody -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -820,7 +815,7 @@ function next() { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> next -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> next -> Entering function."); } i++; controlLoop(); @@ -829,7 +824,7 @@ function controlLoop() { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> controlLoop -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> controlLoop -> Entering function."); } if (i < context.executionContext.positions.length) { @@ -844,14 +839,14 @@ function final() { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] ordersExecutionCheck -> final -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> final -> Entering function."); } callBack(global.DEFAULT_OK_RESPONSE); } } catch (err) { - logger.write("[ERROR] ordersExecutionCheck -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } @@ -859,11 +854,11 @@ function putPosition(pType, pRate, pAmountA, pAmountB, callBackFunction) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pType = " + pType); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pRate = " + pRate); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pAmountA = " + pAmountA); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pAmountB = " + pAmountB); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pType = " + pType); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pRate = " + pRate); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pAmountA = " + pAmountA); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pAmountB = " + pAmountB); } /* Removing extra decimals. */ @@ -877,9 +872,9 @@ if (pAmountA > context.executionContext.availableBalance.assetA) { - logger.write("[ERROR] putPosition -> Input Validations -> pAmountA is grater than the Available Balance."); - logger.write("[ERROR] putPosition -> Input Validations -> pAmountA = " + pAmountA); - logger.write("[ERROR] putPosition -> Input Validations -> Available Balance = " + context.executionContext.availableBalance.assetA); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountA is grater than the Available Balance."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountA = " + pAmountA); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> Available Balance = " + context.executionContext.availableBalance.assetA); let err = { result: global.DEFAULT_FAIL_RESPONSE.result, @@ -894,10 +889,10 @@ if (aRate !== pAmountB) { - logger.write("[ERROR] putPosition -> Input Validations -> pAmountA / pRate !== pAmountB."); - logger.write("[ERROR] putPosition -> Input Validations -> pAmountA = " + pAmountA); - logger.write("[ERROR] putPosition -> Input Validations -> pAmountB = " + pAmountB); - logger.write("[ERROR] putPosition -> Input Validations -> pRate = " + pRate); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountA / pRate !== pAmountB."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountA = " + pAmountA); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountB = " + pAmountB); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pRate = " + pRate); let err = { result: global.DEFAULT_FAIL_RESPONSE.result, @@ -913,9 +908,9 @@ if (pAmountB > context.executionContext.availableBalance.assetB) { - logger.write("[ERROR] putPosition -> Input Validations -> pAmountB is grater than the Available Balance."); - logger.write("[ERROR] putPosition -> Input Validations -> pAmountB = " + pAmountB); - logger.write("[ERROR] putPosition -> Input Validations -> Available Balance = " + context.executionContext.availableBalance.assetB); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountB is grater than the Available Balance."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountB = " + pAmountB); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> Available Balance = " + context.executionContext.availableBalance.assetB); let err = { result: global.DEFAULT_FAIL_RESPONSE.result, @@ -930,10 +925,10 @@ if (bRate !== pAmountA) { - logger.write("[ERROR] putPosition -> Input Validations -> pAmountB * pRate !== pAmountA."); - logger.write("[ERROR] putPosition -> Input Validations -> pAmountA = " + pAmountA); - logger.write("[ERROR] putPosition -> Input Validations -> pAmountB = " + pAmountB); - logger.write("[ERROR] putPosition -> Input Validations -> pRate = " + pRate); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountB * pRate !== pAmountA."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountA = " + pAmountA); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pAmountB = " + pAmountB); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> pRate = " + pRate); let err = { result: global.DEFAULT_FAIL_RESPONSE.result, @@ -959,12 +954,12 @@ if (pRate !== marketRate) { - logger.write("[ERROR] putPosition -> Input Validations -> putPosition Rate can not be different to marketRate while in Backtesting Mode. "); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Input Validations -> putPosition Rate can not be different to marketRate while in Backtesting Mode. "); onResponse(global.DEFAULT_FAIL_RESPONSE, positionId); } let positionId = Math.trunc(Math.random(1) * 1000000); - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> Simulating Exchange Response -> orderId = " + positionId); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> Simulating Exchange Response -> orderId = " + positionId); } onResponse(global.DEFAULT_OK_RESPONSE, positionId); return; } @@ -976,8 +971,8 @@ } default: { - logger.write("[ERROR] putPosition -> Unexpected bot.startMode."); - logger.write("[ERROR] putPosition -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] putPosition -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> bot.startMode = " + bot.startMode); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -986,12 +981,12 @@ function onResponse(err, pPositionId) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> onResponse -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> onResponse -> pPositionId = " + pPositionId); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onResponse -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onResponse -> pPositionId = " + pPositionId); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. - logger.write("[INFO] putPosition -> onResponse -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] putPosition -> onResponse -> Execution finished well."); let position = { id: pPositionId, @@ -1038,25 +1033,25 @@ } break; case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] putPosition -> onResponse -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> onResponse -> Retry Later. Requesting Execution Retry."); callBackFunction(global.DEFAULT_RETRY_RESPONSE); return; } break; case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] putPosition -> onResponse -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> onResponse -> Operation Failed. Aborting the process."); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } break; } } catch (err) { - logger.write("[ERROR] putPosition -> onResponse -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] putPosition -> onResponse -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] putPosition -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] putPosition -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -1064,9 +1059,9 @@ function movePosition(pPosition, pNewRate, callBackFunction) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> pPosition = " + JSON.stringify(pPosition)); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> pNewRate = " + pNewRate); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> pPosition = " + JSON.stringify(pPosition)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> pNewRate = " + pNewRate); } switch (bot.startMode) { @@ -1079,7 +1074,7 @@ case "Backtest": { let positionId = Math.trunc(Math.random(1) * 1000000); - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> Simulating Exchange Response -> orderId = " + positionId); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> Simulating Exchange Response -> orderId = " + positionId); } onResponse(global.DEFAULT_OK_RESPONSE, positionId); return; } @@ -1091,8 +1086,8 @@ } default: { - logger.write("[ERROR] movePosition -> Unexpected bot.startMode."); - logger.write("[ERROR] movePosition -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] movePosition -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] movePosition -> bot.startMode = " + bot.startMode); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -1101,12 +1096,12 @@ function onResponse(err, pPositionId) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> onResponse -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> onResponse -> pPositionId = " + pPositionId); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onResponse -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onResponse -> pPositionId = " + pPositionId); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. - logger.write("[INFO] movePosition -> onResponse -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] movePosition -> onResponse -> Execution finished well."); let newPosition = { id: pPositionId, @@ -1149,25 +1144,25 @@ } break; case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] movePosition -> onResponse -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] movePosition -> onResponse -> Retry Later. Requesting Execution Retry."); callBackFunction(global.DEFAULT_RETRY_RESPONSE); return; } break; case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] movePosition -> onResponse -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] movePosition -> onResponse -> Operation Failed. Aborting the process."); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } break; } } catch (err) { - logger.write("[ERROR] movePosition -> onResponse -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] movePosition -> onResponse -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] movePosition -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] movePosition -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/AzureStorage.js b/AzureStorage.js index fb978c209..8a8432bbc 100644 --- a/AzureStorage.js +++ b/AzureStorage.js @@ -1,4 +1,4 @@ -exports.newAzureStorage = function newAzureStorage(BOT) { +exports.newAzureStorage = function newAzureStorage(BOT, logger) { let FULL_LOG = true; let LOG_FILE_CONTENT = false; @@ -6,13 +6,8 @@ let bot = BOT; const ROOT_DIR = './'; - const MODULE_NAME = "AzureStorage"; - - const DEBUG_MODULE = require('./DebugLog'); - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(true); + const MODULE_NAME = "Azure Storage"; + const REQUEST_TIMEOUT = 180; let thisObject = { createBlobService: createBlobService @@ -128,7 +123,7 @@ let options = { host: pEndPoint, port: 443, - path: '/' + pContainer + '/' + pBlobPath + '?' + pSAS + '&timeout=60', + path: '/' + pContainer + '/' + pBlobPath + '?' + pSAS + '&timeout=' + REQUEST_TIMEOUT, method: 'GET', headers: {}, agent: false @@ -182,7 +177,7 @@ let options = { host: pEndPoint, port: 443, - path: '/' + pContainer + '/' + pBlobPath + '?' + pSAS + '&timeout=60', + path: '/' + pContainer + '/' + pBlobPath + '?' + pSAS + '&timeout=' + REQUEST_TIMEOUT, method: 'PUT', headers: {}, agent: false diff --git a/BlobStorage.js b/BlobStorage.js index a87052dac..4ed071117 100644 --- a/BlobStorage.js +++ b/BlobStorage.js @@ -1,21 +1,19 @@  -exports.newBlobStorage = function newBlobStorage(BOT) { +exports.newBlobStorage = function newBlobStorage(BOT, logger) { let FULL_LOG = true; + let ERROR_LOG = true; let LOG_FILE_CONTENT = false; let bot = BOT; const ROOT_DIR = './'; - const MODULE_NAME = "BlobStorage"; + const MODULE_NAME = "Blob Storage"; + const SECOND_TRY_WAIT_TIME = 10000; let AZURE_STORAGE = require('./AzureStorage'); - let storage = AZURE_STORAGE.newAzureStorage(bot); - - const DEBUG_MODULE = require('./DebugLog'); - let logger; - - + let storage = AZURE_STORAGE.newAzureStorage(bot, logger); + let thisObject = { initialize: initialize, createFolder: createFolder, @@ -36,20 +34,15 @@ exports.newBlobStorage = function newBlobStorage(BOT) { containerName = pDataOwner.toLowerCase(); - logger = DEBUG_MODULE.newDebugLog(); - logger.bot = bot; - logger.fileName = MODULE_NAME + '.' + pDataOwner; - logger.initialize(disableLogging); - if (pDataOwner.environment !== undefined) { // This is use for data migration from one environment to the other. environment = pDataOwner.environment; } - if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } - if (FULL_LOG === true) { logger.write("[INFO] initialize -> environment = " + environment); } - if (FULL_LOG === true) { logger.write("[INFO] initialize -> containerName = " + containerName); } + if (FULL_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } + if (FULL_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[INFO] initialize -> environment = " + environment); } + if (FULL_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[INFO] initialize -> containerName = " + containerName); } let readConnectionString = global.STORAGE_PERMISSIONS[environment][containerName].readConnectionString; @@ -71,14 +64,14 @@ exports.newBlobStorage = function newBlobStorage(BOT) { } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } function createFolder(pFolderPath, callBackFunction) { - if (FULL_LOG === true) { logger.write("[INFO] createFolder -> Entering function."); } + if (FULL_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[INFO] createFolder -> Entering function."); } try { @@ -89,7 +82,7 @@ exports.newBlobStorage = function newBlobStorage(BOT) { } catch (err) { - logger.write("[ERROR] createFolder -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createFolder -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -98,18 +91,18 @@ exports.newBlobStorage = function newBlobStorage(BOT) { if (writeOnlyBlobService === undefined) { - logger.write("[ERROR] createTextFile -> initialize function not executed or failed. Can not process this request. Sorry."); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> initialize function not executed or failed. Can not process this request. Sorry."); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } try { - if (FULL_LOG === true) { - logger.write("[INFO] createTextFile -> About to create a text file."); - logger.write("[INFO] createTextFile -> containerName = " + containerName); - logger.write("[INFO] createTextFile -> pFolderPath = " + pFolderPath); - logger.write("[INFO] createTextFile -> pFileName = " + pFileName); + if (FULL_LOG === true && logger !== undefined) { + logger.write(MODULE_NAME, "[INFO] createTextFile -> About to create a text file."); + logger.write(MODULE_NAME, "[INFO] createTextFile -> containerName = " + containerName); + logger.write(MODULE_NAME, "[INFO] createTextFile -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[INFO] createTextFile -> pFileName = " + pFileName); } writeOnlyBlobService.createBlockBlobFromText(containerName, pFolderPath + "/" + pFileName, pFileContent, onFileCreated); @@ -118,18 +111,19 @@ exports.newBlobStorage = function newBlobStorage(BOT) { try { - if (FULL_LOG === true) { - logger.write("[INFO] createTextFile -> onFileCreated -> Response from Azure received."); - logger.write("[INFO] createTextFile -> onFileCreated -> err = " + JSON.stringify(err)); - logger.write("[INFO] createTextFile -> onFileCreated -> result = " + JSON.stringify(result)); - logger.write("[INFO] createTextFile -> onFileCreated -> response = " + JSON.stringify(response)); + if (FULL_LOG === true && logger !== undefined) { + logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> Response from Azure received."); + logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> err = " + JSON.stringify(err)); + logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> result = " + JSON.stringify(result)); + logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> response = " + JSON.stringify(response)); } if (err) { - logger.write("[ERROR] createTextFile -> onFileCreated -> err = " + JSON.stringify(err)); - logger.write("[ERROR] createTextFile -> onFileCreated -> result = " + JSON.stringify(result)); - logger.write("[ERROR] createTextFile -> onFileCreated -> response = " + JSON.stringify(response)); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> err = " + JSON.stringify(err)); } + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> result = " + JSON.stringify(result)); } + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> response = " + JSON.stringify(response)); } + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> err.code = " + err.code); } if ( err.code === 'ECONNRESET' || @@ -144,14 +138,14 @@ exports.newBlobStorage = function newBlobStorage(BOT) { ) { - setTimeout(secondTry, 1000); + setTimeout(secondTry, SECOND_TRY_WAIT_TIME); return; function secondTry() { try { - logger.write("[INFO] createTextFile -> onFileCreated -> secondTry -> Retrying to create the file."); + logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> secondTry -> Retrying to create the file."); writeOnlyBlobService.createBlockBlobFromText(containerName, pFolderPath + "/" + pFileName, pFileContent, onSecondTry); @@ -160,42 +154,50 @@ exports.newBlobStorage = function newBlobStorage(BOT) { try { if (err) { - logger.write("[ERROR] createTextFile -> onFileCreated -> secondTry -> File not created. Giving Up."); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> secondTry -> File not created. Giving Up."); } + + if (ERROR_LOG === true && logger !== undefined) { + logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> secondTry -> containerName = " + containerName); + logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> secondTry -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> secondTry -> pFileName = " + pFileName); + logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> secondTry -> err.code = " + err.code); + } + callBackFunction(global.DEFAULT_RETRY_RESPONSE); } else { - logger.write("[INFO] createTextFile -> onFileCreated -> secondTry -> File succesfully created on second try."); + logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> secondTry -> File succesfully created on second try."); callBackFunction(global.DEFAULT_OK_RESPONSE); } } catch (err) { - logger.write("[ERROR] 'createTextFile' -> onFileCreated -> secondTry -> onSecondTry -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'createTextFile' -> onFileCreated -> secondTry -> onSecondTry -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] 'createTextFile' -> onFileCreated -> secondTry -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'createTextFile' -> onFileCreated -> secondTry -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } - logger.write("[ERROR] createTextFile -> onFileCreated -> Dont know what to do here. Cancelling operation. "); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] createTextFile -> onFileCreated -> Dont know what to do here. Cancelling operation. "); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } else { - if (FULL_LOG === true) { logger.write("[INFO] createTextFile -> onFileCreated -> File Created."); } + if (FULL_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> File Created."); } callBackFunction(global.DEFAULT_OK_RESPONSE); } } catch (err) { - logger.write("[ERROR] 'createTextFile' -> onFileCreated -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'createTextFile' -> onFileCreated -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] 'createTextFile' -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'createTextFile' -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -204,18 +206,18 @@ exports.newBlobStorage = function newBlobStorage(BOT) { if (readOnlyBlobService === undefined) { - logger.write("[ERROR] getTextFile -> initialize function not executed or failed. Can not process this request. Sorry."); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] getTextFile -> initialize function not executed or failed. Can not process this request. Sorry."); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } try { - if (FULL_LOG === true) { - logger.write("[INFO] getTextFile -> About to get a text file."); - logger.write("[INFO] getTextFile -> containerName = " + containerName); - logger.write("[INFO] getTextFile -> pFolderPath = " + pFolderPath); - logger.write("[INFO] getTextFile -> pFileName = " + pFileName); + if (FULL_LOG === true && logger !== undefined) { + logger.write(MODULE_NAME, "[INFO] getTextFile -> About to get a text file."); + logger.write(MODULE_NAME, "[INFO] getTextFile -> containerName = " + containerName); + logger.write(MODULE_NAME, "[INFO] getTextFile -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[INFO] getTextFile -> pFileName = " + pFileName); } readOnlyBlobService.getBlobToText(containerName, pFolderPath + "/" + pFileName, onFileReceived); @@ -224,18 +226,26 @@ exports.newBlobStorage = function newBlobStorage(BOT) { try { - if (FULL_LOG === true) { - logger.write("[INFO] getTextFile -> onFileReceived -> Response from Azure received."); - logger.write("[INFO] getTextFile -> onFileReceived -> err = " + JSON.stringify(err)); - logger.write("[INFO] getTextFile -> onFileReceived -> response = " + JSON.stringify(response)); + if (FULL_LOG === true && logger !== undefined) { + logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> Response from Azure received."); + logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> err = " + JSON.stringify(err)); + logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> response = " + JSON.stringify(response)); } - if (LOG_FILE_CONTENT === true) { - logger.write("[INFO] getTextFile -> onFileReceived -> text = " + text); + if (LOG_FILE_CONTENT === true && logger !== undefined) { + logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> text = " + text); } if (err) { + if (ERROR_LOG === true && logger !== undefined && err.code !== 'BlobNotFound') { + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> Error trying to get this file."); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> containerName = " + containerName); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> pFileName = " + pFileName); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> err.code = " + err.code); + } + if ( err.code === 'ECONNRESET' || err.code === 'ENOTFOUND' || @@ -250,14 +260,14 @@ exports.newBlobStorage = function newBlobStorage(BOT) { { - setTimeout(secondTry, 1000); + setTimeout(secondTry, SECOND_TRY_WAIT_TIME); return; function secondTry() { try { - logger.write("[INFO] getTextFile -> onFileReceived -> secondTry -> Retrying to get the file."); + logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> secondTry -> Retrying to get the file."); readOnlyBlobService.getBlobToText(containerName, pFolderPath + "/" + pFileName, onSecondTry); @@ -266,21 +276,29 @@ exports.newBlobStorage = function newBlobStorage(BOT) { try { if (err) { - logger.write("[ERROR] getTextFile -> onFileReceived -> secondTry -> File not retrieved. Giving Up."); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> secondTry -> File not retrieved. Giving Up."); } + + if (ERROR_LOG === true && logger !== undefined) { + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> secondTry -> containerName = " + containerName); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> secondTry -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> secondTry -> pFileName = " + pFileName); + logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> secondTry -> err.code = " + err.code); + } + callBackFunction(global.DEFAULT_RETRY_RESPONSE); } else { - logger.write("[INFO] getTextFile -> onFileReceived -> secondTry -> File succesfully retrieved on second try."); + logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> secondTry -> File succesfully retrieved on second try."); callBackFunction(global.DEFAULT_OK_RESPONSE, text); } } catch (err) { - logger.write("[ERROR] 'getTextFile' -> onFileReceived -> secondTry -> onSecondTry -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'getTextFile' -> onFileReceived -> secondTry -> onSecondTry -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] 'getTextFile' -> onFileReceived -> secondTry -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'getTextFile' -> onFileReceived -> secondTry -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -295,10 +313,10 @@ exports.newBlobStorage = function newBlobStorage(BOT) { message: "File does not exist." }; - logger.write("[WARN] getTextFile -> onFileReceived -> Custom Response -> message = " + customErr.message); - logger.write("[WARN] getTextFile -> containerName = " + containerName); - logger.write("[WARN] getTextFile -> pFolderPath = " + pFolderPath); - logger.write("[WARN] getTextFile -> pFileName = " + pFileName); + logger.write(MODULE_NAME, "[WARN] getTextFile -> onFileReceived -> Custom Response -> message = " + customErr.message); + logger.write(MODULE_NAME, "[WARN] getTextFile -> containerName = " + containerName); + logger.write(MODULE_NAME, "[WARN] getTextFile -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[WARN] getTextFile -> pFileName = " + pFileName); callBackFunction(customErr); return; @@ -314,35 +332,35 @@ exports.newBlobStorage = function newBlobStorage(BOT) { message: "Folder does not exist." }; - logger.write("[WARN] getTextFile -> onFileReceived -> Custom Response -> message = " + customErr.message); - logger.write("[WARN] getTextFile -> containerName = " + containerName); - logger.write("[WARN] getTextFile -> pFolderPath = " + pFolderPath); - logger.write("[WARN] getTextFile -> pFileName = " + pFileName); + logger.write(MODULE_NAME, "[WARN] getTextFile -> onFileReceived -> Custom Response -> message = " + customErr.message); + logger.write(MODULE_NAME, "[WARN] getTextFile -> containerName = " + containerName); + logger.write(MODULE_NAME, "[WARN] getTextFile -> pFolderPath = " + pFolderPath); + logger.write(MODULE_NAME, "[WARN] getTextFile -> pFileName = " + pFileName); callBackFunction(customErr); return; } - logger.write("[ERROR] getTextFile -> onFileCreated -> err = " + JSON.stringify(err)); - logger.write("[ERROR] getTextFile -> onFileCreated -> response = " + JSON.stringify(response)); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileCreated -> err = " + JSON.stringify(err)); } + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileCreated -> response = " + JSON.stringify(response)); } - logger.write("[ERROR] getTextFile -> onFileReceived -> Dont know what to do here. Cancelling operation. "); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] getTextFile -> onFileReceived -> Dont know what to do here. Cancelling operation. "); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } else { - if (FULL_LOG === true) { logger.write("[INFO] getTextFile -> onFileReceived -> File retrieved."); } + if (FULL_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> File retrieved."); } callBackFunction(global.DEFAULT_OK_RESPONSE, text); } } catch (err) { - logger.write("[ERROR] 'getTextFile' -> onFileReceived -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'getTextFile' -> onFileReceived -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] 'getTextFile' -> err = " + err.message); + if (ERROR_LOG === true && logger !== undefined) { logger.write(MODULE_NAME, "[ERROR] 'getTextFile' -> err = " + err.message); } callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/CloudRequire.js b/CloudRequire.js index c1c305165..1597614d5 100644 --- a/CloudRequire.js +++ b/CloudRequire.js @@ -1,17 +1,12 @@ -exports.newCloudRequire = function newCloudRequire(BOT, DEBUG_MODULE) { +exports.newCloudRequire = function newCloudRequire(BOT, logger) { const FULL_LOG = true; const LOG_FILE_CONTENT = false; - const MODULE_NAME = "CloudRequire"; + const MODULE_NAME = "Cloud Require"; let bot = BOT; - const logger = DEBUG_MODULE.newDebugLog(); - logger.bot = bot; - logger.fileName = MODULE_NAME; - logger.initialize(); - let thisObject = { downloadBot: downloadBot, downloadCommons: downloadCommons @@ -23,7 +18,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] downloadBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] downloadBot -> Entering function."); } let fileName = "User.Bot.js"; @@ -33,7 +28,7 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] downloadBot -> onFileReceived -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] downloadBot -> onFileReceived -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -46,14 +41,14 @@ callBackFunction(global.DEFAULT_OK_RESPONSE, USER_BOT_MODULE); } catch (err) { - logger.write("[ERROR] downloadBot -> onFileReceived -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] downloadBot -> onFileReceived -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] downloadBot -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] downloadBot -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -62,7 +57,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] downloadCommons -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] downloadCommons -> Entering function."); } let fileName = "Commons.js"; @@ -85,14 +80,14 @@ callBackFunction(global.DEFAULT_OK_RESPONSE, COMMONS_MODULE); } catch (err) { - logger.write("[ERROR] downloadCommons -> onFileReceived -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] downloadCommons -> onFileReceived -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] downloadCommons -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] downloadCommons -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/CloudUtilities.js b/CloudUtilities.js index 3bcf55cc2..7ed58470e 100644 --- a/CloudUtilities.js +++ b/CloudUtilities.js @@ -1,19 +1,12 @@  -exports.newCloudUtilities = function newCloudUtilities(BOT) { +exports.newCloudUtilities = function newCloudUtilities(BOT, logger) { const FULL_LOG = false; let bot = BOT; const ROOT_DIR = '../'; - const MODULE_NAME = "CloudUtilities"; - - - const DEBUG_MODULE = require('./DebugLog'); - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(); + const MODULE_NAME = "Cloud Utilities"; let utilities = { pad: pad, @@ -27,8 +20,8 @@ exports.newCloudUtilities = function newCloudUtilities(BOT) { try { - if (FULL_LOG === true) { logger.write("[INFO] createFolderIfNeeded -> Entering function."); } - if (FULL_LOG === true) { logger.write("[INFO] createFolderIfNeeded -> path = " + path); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] createFolderIfNeeded -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] createFolderIfNeeded -> path = " + path); } let splittedPath = path.split("/"); @@ -40,23 +33,23 @@ exports.newCloudUtilities = function newCloudUtilities(BOT) { function loop() { - if (FULL_LOG === true) { logger.write("[INFO] createFolderIfNeeded -> path = " + path); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] createFolderIfNeeded -> path = " + path); } partialPath = partialPath + separator + splittedPath[i]; separator = "/"; i++; - if (FULL_LOG === true) { logger.write("[INFO] createFolderIfNeeded -> partialPath = " + partialPath); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] createFolderIfNeeded -> partialPath = " + partialPath); } azureFileStorage.createFolder(partialPath, checkLoop); function checkLoop(err) { - if (FULL_LOG === true) { logger.write("[INFO] createFolderIfNeeded -> loop -> checkLoop -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] createFolderIfNeeded -> loop -> checkLoop -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] createFolderIfNeeded -> loop -> checkLoop -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] createFolderIfNeeded -> loop -> checkLoop -> err = " + err.message); callBackFunction(err); return; } @@ -73,7 +66,7 @@ exports.newCloudUtilities = function newCloudUtilities(BOT) { } } } catch (err) { - logger.write("[ERROR] createFolderIfNeeded -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] createFolderIfNeeded -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/Context.js b/Context.js index 5ed1c7570..76db4c8d5 100644 --- a/Context.js +++ b/Context.js @@ -1,14 +1,9 @@ -exports.newContext = function newContext(BOT, DEBUG_MODULE, BLOB_STORAGE, UTILITIES, STATUS_REPORT) { +exports.newContext = function newContext(BOT, logger, BLOB_STORAGE, UTILITIES, STATUS_REPORT) { let bot = BOT; const MODULE_NAME = "Context"; - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(); - /* This module allows deals with keeping the context between different executions of the bot. @@ -78,11 +73,11 @@ /* Utilities needed. */ - let utilities = UTILITIES.newCloudUtilities(bot); + let utilities = UTILITIES.newCloudUtilities(bot, logger); /* Storage account to be used here. */ - let cloudStorage = BLOB_STORAGE.newBlobStorage(bot); + let cloudStorage = BLOB_STORAGE.newBlobStorage(bot, logger); let statusDependencies; @@ -94,7 +89,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } statusDependencies = pStatusDependencies; @@ -119,7 +114,7 @@ getStatusReport(onDone); } else { - logger.write("[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message); callBackFunction(err); } } @@ -130,7 +125,7 @@ switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] initialize -> onDone -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] initialize -> onDone -> Execution finished well."); bot.hasTheBotJustStarted = false; @@ -138,23 +133,23 @@ return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] initialize -> onDone -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] initialize -> onDone -> Retry Later. Requesting Execution Retry."); callBackFunction(err); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] initialize -> onDone -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] initialize -> onDone -> Operation Failed. Aborting the process."); callBackFunction(err); return; } default: { - logger.write("[ERROR] initialize -> onDone -> Operation Failed with custom response."); + logger.write(MODULE_NAME, "[ERROR] initialize -> onDone -> Operation Failed with custom response."); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] initialize -> onDone -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> onDone -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -163,7 +158,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getStatusReport -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getStatusReport -> Entering function."); } let key = bot.devTeam + "-" + bot.codeName + "-" + bot.process + "-" + bot.dataSetVersion; @@ -197,8 +192,8 @@ } default: { - logger.write("[ERROR] initialize -> createConext -> Unexpected bot.startMode."); - logger.write("[ERROR] initialize -> createConext -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] initialize -> createConext -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] initialize -> createConext -> bot.startMode = " + bot.startMode); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -209,7 +204,7 @@ } } catch (err) { - logger.write("[ERROR] initialize -> getStatusReport -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getStatusReport -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } @@ -218,26 +213,26 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getExecutionHistory -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionHistory -> Entering function."); } let fileName = "Execution.History." + bot.startMode + "." + runIndex + ".json"; let filePath = bot.filePathRoot + "/Output/" + bot.process; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getExecutionHistory -> fileName = " + fileName); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getExecutionHistory -> filePath = " + filePath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionHistory -> fileName = " + fileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionHistory -> filePath = " + filePath); } cloudStorage.getTextFile(filePath, fileName, onFileReceived); function onFileReceived(err, text) { if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> getExecutionHistory -> onFileReceived -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionHistory -> onFileReceived -> err = " + err.message); callBack(err); return; } if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { - logger.write("[INFO] initialize -> getExecutionHistory -> onFileReceived -> Content received = " + text); + logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionHistory -> onFileReceived -> Content received = " + text); } try { @@ -261,13 +256,13 @@ */ - logger.write("[ERROR] initialize -> getExecutionHistory -> onFileReceived -> Bot cannot execute without the Execution History. -> Err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionHistory -> onFileReceived -> Bot cannot execute without the Execution History. -> Err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] initialize -> getExecutionHistory -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionHistory -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } @@ -276,7 +271,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getExecutionContext -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionContext -> Entering function."); } let date; @@ -302,8 +297,8 @@ } default: { - logger.write("[ERROR] initialize -> getExecutionContext -> Unexpected bot.startMode."); - logger.write("[ERROR] initialize -> getExecutionContext -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionContext -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionContext -> bot.startMode = " + bot.startMode); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -313,21 +308,21 @@ let dateForPath = date.getUTCFullYear() + '/' + utilities.pad(date.getUTCMonth() + 1, 2) + '/' + utilities.pad(date.getUTCDate(), 2) + '/' + utilities.pad(date.getUTCHours(), 2) + '/' + utilities.pad(date.getUTCMinutes(), 2); let filePath = bot.filePathRoot + "/Output/" + bot.process + '/' + dateForPath; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getExecutionContext -> fileName = " + fileName); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> getExecutionContext -> filePath = " + filePath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionContext -> fileName = " + fileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionContext -> filePath = " + filePath); } cloudStorage.getTextFile(filePath, fileName, onFileReceived); function onFileReceived(err, text) { if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> getExecutionContext -> onFileReceived -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionContext -> onFileReceived -> err = " + err.message); callBack(err); return; } if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { - logger.write("[INFO] initialize -> getExecutionContext -> onFileReceived -> Content received = " + text); + logger.write(MODULE_NAME, "[INFO] initialize -> getExecutionContext -> onFileReceived -> Content received = " + text); } try { @@ -355,13 +350,13 @@ */ - logger.write("[ERROR] initialize -> getExecutionContext -> onFileReceived -> Bot cannot execute without the Execution Context. -> Err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionContext -> onFileReceived -> Bot cannot execute without the Execution Context. -> Err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] initialize -> getExecutionContext -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> getExecutionContext -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } @@ -369,7 +364,7 @@ function createConext(callBack) { try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> createConext -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> createConext -> Entering function."); } /* When the bot is executed for the very first time, there are a few files that do not exist and need to be created, and that @@ -430,8 +425,8 @@ } default: { - logger.write("[ERROR] initialize -> createConext -> Unexpected bot.startMode."); - logger.write("[ERROR] initialize -> createConext -> bot.startMode = " + bot.startMode); + logger.write(MODULE_NAME, "[ERROR] initialize -> createConext -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] initialize -> createConext -> bot.startMode = " + bot.startMode); callBack(global.DEFAULT_FAIL_RESPONSE); return; } @@ -475,13 +470,13 @@ callBack(global.DEFAULT_OK_RESPONSE); } catch (err) { - logger.write("[ERROR] initialize -> createConext -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> createConext -> err = " + err.message); callBack(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -497,19 +492,19 @@ switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] saveThemAll -> onDone -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] saveThemAll -> onDone -> Execution finished well."); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } break; case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] saveThemAll -> onDone -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> onDone -> Retry Later. Requesting Execution Retry."); callBackFunction(err); return; } break; case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] saveThemAll -> onDone -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> onDone -> Operation Failed. Aborting the process."); callBackFunction(err); return; } @@ -517,7 +512,7 @@ } } catch (err) { - logger.write("[ERROR] saveThemAll -> onDone -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> onDone -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -526,14 +521,14 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExecutionContext -> Entering function."); } let fileName = "Execution.Context." + bot.startMode + "." + runIndex +".json"; let dateForPath = bot.processDatetime.getUTCFullYear() + '/' + utilities.pad(bot.processDatetime.getUTCMonth() + 1, 2) + '/' + utilities.pad(bot.processDatetime.getUTCDate(), 2) + '/' + utilities.pad(bot.processDatetime.getUTCHours(), 2) + '/' + utilities.pad(bot.processDatetime.getUTCMinutes(), 2); let filePath = bot.filePathRoot + "/Output/" + bot.process + '/' + dateForPath; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> fileName = " + fileName); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> filePath = " + filePath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExecutionContext -> fileName = " + fileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExecutionContext -> filePath = " + filePath); } utilities.createFolderIfNeeded(filePath, cloudStorage, onFolderCreated); @@ -541,10 +536,10 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message); callBack(err); return; } @@ -555,16 +550,16 @@ function onFileCreated(err) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> err = " + err.message); callBack(err); return; } if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { - logger.write("[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> Content written = " + fileContent); + logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> Content written = " + fileContent); } writeExucutionHistory(callBack); @@ -572,13 +567,13 @@ } } catch (err) { - logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] saveThemAll -> writeExecutionContext -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExecutionContext -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -587,13 +582,13 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> Entering function."); } let fileName = "Execution.History." + bot.startMode + "." + runIndex + ".json"; let filePath = bot.filePathRoot + "/Output/" + bot.process; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> fileName = " + fileName); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> filePath = " + filePath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> fileName = " + fileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> filePath = " + filePath); } utilities.createFolderIfNeeded(filePath, cloudStorage, onFolderCreated); @@ -601,10 +596,10 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message); callBack(err); return; } @@ -641,16 +636,16 @@ function onFileCreated(err) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> err = " + err.message); callBack(err); return; } if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { - logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> Content written = " + fileContent); + logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> Content written = " + fileContent); } /* Here we will write the file containing the max sequence number. */ @@ -663,10 +658,10 @@ function onSequenceFileCreated(err) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> onSequenceFileCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> onSequenceFileCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> onSequenceFileCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> onSequenceFileCreated -> err = " + err.message); callBack(err); return; } @@ -677,13 +672,13 @@ } } catch (err) { - logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeExucutionHistory -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -692,20 +687,20 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] saveThemAll -> writeStatusReport -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] saveThemAll -> writeStatusReport -> Entering function."); } statusReportModule.file = thisObject.statusReport; statusReportModule.save(callBack); } catch (err) { - logger.write("[ERROR] saveThemAll -> writeStatusReport -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> writeStatusReport -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] saveThemAll -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] saveThemAll -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/DataDependencies.js b/DataDependencies.js index d550176a6..db08c5a77 100644 --- a/DataDependencies.js +++ b/DataDependencies.js @@ -1,18 +1,13 @@ -exports.newDataDependencies = function newDataDependencies(BOT, DEBUG_MODULE, DATA_SET, BLOB_STORAGE, UTILITIES) { +exports.newDataDependencies = function newDataDependencies(BOT, logger, DATA_SET, BLOB_STORAGE, UTILITIES) { const FULL_LOG = true; const LOG_FILE_CONTENT = false; - const MODULE_NAME = "DataDependencies"; + const MODULE_NAME = "Data Dependencies"; let bot = BOT; let ownerBot; // This is the bot owner of the Data Set. - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(); - let thisObject = { dataSets: new Map(), initialize: initialize, @@ -26,7 +21,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } /* @@ -38,14 +33,14 @@ for (let i = 0; i < pDataDependenciesConfig.length; i++) { - let dataSetModule = DATA_SET.newDataSet(BOT, DEBUG_MODULE, BLOB_STORAGE, UTILITIES); + let dataSetModule = DATA_SET.newDataSet(BOT, logger, BLOB_STORAGE, UTILITIES); dataSetModule.initialize(pDataDependenciesConfig[i], onInitilized); function onInitilized(err) { if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInitilized -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> onInitilized -> err = " + err.message); alreadyCalledBack = true; callBackFunction(err); @@ -57,7 +52,7 @@ function addDataSet() { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> addDataSet -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] initialize -> addDataSet -> Entering function."); } addCount++; @@ -68,7 +63,7 @@ thisObject.keys.push(key); thisObject.dataSets.set(key, dataSetModule); - if (FULL_LOG === true) { logger.write("[INFO] initialize -> addDataSet -> DataSet added to Map. -> key = " + key); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] initialize -> addDataSet -> DataSet added to Map. -> key = " + key); } if (addCount === pDataDependenciesConfig.length) { if (alreadyCalledBack === false) { @@ -80,7 +75,7 @@ } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/DataSet.js b/DataSet.js index f7e95bf82..074135d0a 100644 --- a/DataSet.js +++ b/DataSet.js @@ -1,14 +1,9 @@ -exports.newDataSet = function newDataSet(BOT, DEBUG_MODULE, BLOB_STORAGE, UTILITIES) { +exports.newDataSet = function newDataSet(BOT, logger, BLOB_STORAGE, UTILITIES) { - const MODULE_NAME = "DataSet"; + const MODULE_NAME = "Data Set"; let bot = BOT; - const logger = DEBUG_MODULE.newDebugLog(); - logger.bot = bot; - logger.fileName = MODULE_NAME; - logger.initialize(); - let thisObject = { file: undefined, // Here we have the JSON object representing the file content. initialize: initialize, @@ -20,11 +15,11 @@ /* Utilities needed. */ - let utilities = UTILITIES.newCloudUtilities(bot); + let utilities = UTILITIES.newCloudUtilities(bot, logger); /* Storage account to be used here. */ - let cloudStorage = BLOB_STORAGE.newBlobStorage(bot); + let cloudStorage = BLOB_STORAGE.newBlobStorage(bot, logger); return thisObject; @@ -36,7 +31,7 @@ dependencyConfig = pDependencyConfig; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } initializeStorage(); @@ -48,17 +43,17 @@ if (err.result === global.DEFAULT_OK_RESPONSE.result) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> initializeStorage -> onInizialized -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> initializeStorage -> onInizialized -> Entering function."); } callBackFunction(global.DEFAULT_OK_RESPONSE); } else { - logger.write("[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message); callBackFunction(err); } } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -67,9 +62,9 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getTextFile -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getTextFile -> pFolderPath = " + pFolderPath); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getTextFile -> pFileName = " + pFileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTextFile -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTextFile -> pFolderPath = " + pFolderPath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTextFile -> pFileName = " + pFileName); } let filePathRoot = dependencyConfig.devTeam + "/" + dependencyConfig.bot + "." + dependencyConfig.botVersion.major + "." + dependencyConfig.botVersion.minor + "/" + global.PLATFORM_CONFIG.codeName + "." + global.PLATFORM_CONFIG.version.major + "." + global.PLATFORM_CONFIG.version.minor + "/" + global.EXCHANGE_NAME + "/" + dependencyConfig.dataSetVersion; let filePath = filePathRoot + "/Output/" + pFolderPath; @@ -78,14 +73,14 @@ function onFileReceived(err, text) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getTextFile -> onFileReceived -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTextFile -> onFileReceived -> Entering function."); } callBackFunction(err, text); } } catch (err) { - logger.write("[ERROR] 'getTextFile' -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] 'getTextFile' -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -94,9 +89,9 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] createTextFile -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] createTextFile -> pFolderPath = " + pFolderPath); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] createTextFile -> pFileName = " + pFileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] createTextFile -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] createTextFile -> pFolderPath = " + pFolderPath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] createTextFile -> pFileName = " + pFileName); } let ownerId = dependencyConfig.devTeam + "-" + dependencyConfig.bot + "-" + dependencyConfig.botVersion.major + "-" + dependencyConfig.botVersion.minor + "-" + dependencyConfig.dataSetVersion; let botId = bot.devTeam + "-" + bot.codeName + "-" + bot.version.major + "-" + bot.version.minor + "-" + bot.dataSetVersion; @@ -107,7 +102,7 @@ result: global.CUSTOM_FAIL_RESPONSE.result, message: "Only bots owners of a Data Set can create text files on them." }; - logger.write("[ERROR] save -> customErr = " + customErr.message); + logger.write(MODULE_NAME, "[ERROR] save -> customErr = " + customErr.message); callBackFunction(customErr); return; } @@ -119,14 +114,14 @@ function onFileCreated(err) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] createTextFile -> onFileCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] createTextFile -> onFileCreated -> Entering function."); } callBackFunction(err); } } catch (err) { - logger.write("[ERROR] 'createTextFile' -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] 'createTextFile' -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/DebugLog.js b/DebugLog.js index 9a5c725fd..148d44a17 100644 --- a/DebugLog.js +++ b/DebugLog.js @@ -3,22 +3,19 @@ const ROOT_DIR = './'; const MODULE_NAME = "DebugLog"; - let executionDatetime = "Y." + global.EXECUTION_DATETIME.getUTCFullYear() + - ".M." + pad(global.EXECUTION_DATETIME.getUTCMonth() + 1, 2) + - ".D." + pad(global.EXECUTION_DATETIME.getUTCDate(), 2) + - ".H." + pad(global.EXECUTION_DATETIME.getUTCHours(),2) + - ".M." + pad(global.EXECUTION_DATETIME.getUTCMinutes(),2) + - ".S." + pad(global.EXECUTION_DATETIME.getUTCSeconds(),2); + let executionDatetime = "D." + global.EXECUTION_DATETIME.getUTCFullYear() + + "." + pad(global.EXECUTION_DATETIME.getUTCMonth() + 1, 2) + + "." + pad(global.EXECUTION_DATETIME.getUTCDate(), 2) + + ".T." + pad(global.EXECUTION_DATETIME.getUTCHours(),2) + + "." + pad(global.EXECUTION_DATETIME.getUTCMinutes(),2) + + "." + pad(global.EXECUTION_DATETIME.getUTCSeconds(),2); let messageId = 0; - let loopCounter; - let loopIncremented = false; let thisObject = { bot: undefined, - fileName: undefined, - forceLoopSplit: false, // When set to 'true' this will force that the logs of the current module are split in many different Loop folders. write: write, + persist: persist, initialize: initialize }; @@ -34,19 +31,24 @@ disableLogging = pdisableLogging - if (disableLogging !== true) { - thisObject.bot.eventHandler.listenToEvent("Close Log File", onLoopFinished); - } - } catch (err) { - console.log("[ERROR] DebugLog -> initialize -> err = " + err.message); + console.log("[ERROR] Debug Log -> initialize -> err = " + err.message); } } - function onLoopFinished(event) { + function persist() { + + /* Here we actually write the content of the in-memory log to a blob */ try { + if (global.CURRENT_EXECUTION_AT === "Browser") { + + console.log("[INFO] DebugLog -> persist -> We do not persist logs while running at the Browser"); + return; + + } + const BLOB_STORAGE = require(ROOT_DIR + 'BlobStorage'); let cloudStorage = BLOB_STORAGE.newBlobStorage(thisObject.bot); @@ -58,8 +60,6 @@ if (err.result === global.DEFAULT_OK_RESPONSE.result) { - /* We save a file for the module doing the logging at this instance of DebugLog. */ - let filePath = thisObject.bot.filePathRoot + "/Logs/" + thisObject.bot.process + "/" + executionDatetime; if (thisObject.bot.debug.year !== undefined) { @@ -67,135 +67,79 @@ filePath = filePath + "/" + thisObject.bot.debug.year + "/" + thisObject.bot.debug.month; } - if (loopCounter === undefined) { loopCounter = 0 }; + let fileName = "Loop." + pad(thisObject.bot.loopCounter, 8) + ".json"; - filePath = filePath + "/Loop." + pad(loopCounter, 5); - - cloudStorage.createTextFile(filePath, thisObject.fileName + ".json", blobContent + '\r\n' + "]", onFileCreated); + cloudStorage.createTextFile(filePath, fileName, blobContent + '\r\n' + "]", onFileCreated); function onFileCreated(err) { if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - console.log("[ERROR] DebugLog -> onLoopFinished -> onInizialized -> onFileCreated -> err = " + err.message); + console.log("[ERROR] DebugLog -> persist -> onInizialized -> onFileCreated -> err = " + err.message); + console.log("[ERROR] DebugLog -> persist -> onInizialized -> onFileCreated -> filePath = " + filePath); + console.log("[ERROR] DebugLog -> persist -> onInizialized -> onFileCreated -> fileName = " + fileName); return; } - } - /* We save a single file for the whole Process of the bot, inlcuding AACloud modules. */ - - if (thisObject.bot.sharedLogFileMap !== undefined) { - - let fileSaved = thisObject.bot.sharedLogFileMap.get(loopCounter); - - if (fileSaved !== true) { - - thisObject.bot.sharedLogFileMap.set(loopCounter, true); - - let sharedFileContent = "["; - - for (let i = 0; i < thisObject.bot.blobContent.length; i++) { - - sharedFileContent = sharedFileContent + thisObject.bot.blobContent[i]; - } - - thisObject.bot.blobContent = []; - - sharedFileContent = sharedFileContent + '\r\n' + "]"; - - cloudStorage.createTextFile(filePath, "AllModules" + ".json", sharedFileContent, onSharedFileCreated); - - function onSharedFileCreated(err) { - - if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - console.log("[ERROR] DebugLog -> onLoopFinished -> onInizialized -> onSharedFileCreated -> err = " + err.message); - return; - } - } - } - - } else { - console.log("[ERROR] DebugLog -> onLoopFinished -> onInizialized -> err = " + err.message); + blobContent = ""; + thisObject = {}; } } else { - console.log("[ERROR] DebugLog -> onLoopFinished -> onInizialized -> sharedLogFileMap is undefined. "); + + console.log("[ERROR] DebugLog -> persist -> onInizialized -> cloud storge failed to initialize. "); + console.log("[ERROR] DebugLog -> persist -> onInizialized -> err.message = " + err.message); + } } catch (err) { - console.log("[ERROR] DebugLog -> onLoopFinished -> onInizialized -> err = " + err.message); + console.log("[ERROR] DebugLog -> persist -> onInizialized -> err = " + err.message); } } } catch (err) { - console.log("[ERROR] DebugLog -> onLoopFinished -> err = " + err.message); + console.log("[ERROR] DebugLog -> persist -> err = " + err.message); } } - function write(Message) { + + function write(pModule, pMessage) { try { if (disableLogging === true) { return; } - console.log("AACloud" + spacePad(thisObject.fileName, 50) + " : " + Message); + if (global.CURRENT_EXECUTION_AT === "Browser") { - if (thisObject.bot === undefined) { return; } + /* Only at the browser we send the messages to the console. At the Cloud it does not make sense. */ - if (thisObject.bot.loopCounter !== loopCounter) { + console.log("AACloud" + spacePad(pModule, 50) + " : " + pMessage); + return; + } - if (thisObject.forceLoopSplit === false) { + if (global.CURRENT_EXECUTION_AT === "Cloud") { - if (loopIncremented === false) { + /* Only ERRORs go to the cloud console. */ - loopIncremented = true; + if (pMessage.indexOf("[ERROR]") >= 0) { - loopCounter = thisObject.bot.loopCounter; - - blobContent = "["; // Local version - } - } else { - - loopIncremented = true; - - loopCounter = thisObject.bot.loopCounter; + console.log("AACloud" + spacePad(pModule, 50) + " : " + pMessage); } } + + if (thisObject.bot === undefined) { return; } let newDate = new Date(); newDate = newDate.toISOString(); messageId++; - /* When writing one file pero module we need this. */ - - let fileLine = '\r\n' + "['" + newDate + "'," + messageId + ",'" + Message + "']"; - - if (blobContent === "[") { - - blobContent = blobContent + fileLine; - - } else { - - blobContent = blobContent + "," + fileLine; - } - /* When writting one file for all modules we use this. */ - let sharedFileLine; + let logLine = '\r\n' + "['" + newDate + "'," + messageId + ",'" + pModule + "','" + pMessage + "']"; - if (thisObject.bot.blobContent === undefined || thisObject.bot.blobContent.length === 0) { - - thisObject.bot.blobContent = []; - sharedFileLine = '\r\n' + "['" + newDate + "'," + (thisObject.bot.blobContent.length + 1) + ",'" + thisObject.fileName + "','" + Message + "']"; - thisObject.bot.blobContent.push(sharedFileLine.toString()); - - } else { - sharedFileLine = '\r\n' + "['" + newDate + "'," + (thisObject.bot.blobContent.length + 1) + ",'" + thisObject.fileName + "','" + Message + "']"; - thisObject.bot.blobContent.push("," + sharedFileLine.toString()); - } + blobContent = blobContent + logLine; - } catch (err) { console.log("[ERROR] DebugLog -> write -> err = " + err.message); } diff --git a/EventHandler.js b/EventHandler.js deleted file mode 100644 index 3b847868c..000000000 --- a/EventHandler.js +++ /dev/null @@ -1,63 +0,0 @@ - -exports.newEventHandler = function newEventHandler() { - - const CONSOLE_LOG = false; - - let thisObject = { - name: undefined, // This is for debugging purposes only. - parentEventHandler: undefined, // Here we store the parent cointainer zoom object. - listenToEvent: listenToEvent, - raiseEvent: raiseEvent, - initialize: initialize - }; - - var eventHandlers = []; // Here we store all the functions we will call when an event is comming. - - return thisObject; - - function initialize() { - - - } - - function listenToEvent(eventType, handler, extraData) { - - eventHandlers.push([eventType, handler, extraData]); - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to listenToEvent " + eventType + " and call " + (handler.toString()).substring(0, 50)); - - } - - } - - function raiseEvent(eventType, event) { - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to raiseEvent " + eventType + " with this data " + (event.toString()).substring(0, 50)); - - } - - for (var i = 0; i < eventHandlers.length; i++) { - - /* We will execute all the functions listening to this event type. */ - - if (eventHandlers[i][0] === eventType) { - - var handler = eventHandlers[i][1]; - var extraData = eventHandlers[i][2]; - - if (thisObject.name !== undefined && CONSOLE_LOG === true) { - - console.log("Event Handler named " + thisObject.name + " received a request to raiseEvent " + eventType + " and will call this handler: " + (handler.toString()).substring(0,50)); - - } - - handler(event, extraData); - - } - } - } -} diff --git a/ExchangeAPI.js b/ExchangeAPI.js index 9b6d78ab0..07b4dd0d4 100644 --- a/ExchangeAPI.js +++ b/ExchangeAPI.js @@ -1,4 +1,4 @@ -exports.newExchangeAPI = function newExchangeAPI(BOT, DEBUG_MODULE, POLONIEX_CLIENT_MODULE) { +exports.newExchangeAPI = function newExchangeAPI(BOT, logger, POLONIEX_CLIENT_MODULE) { /* @@ -6,15 +6,10 @@ */ - const MODULE_NAME = "ExchangeAPI"; + const MODULE_NAME = "Exchange API"; let bot = BOT; - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(); - let thisObject = { initialize: initialize, getOpenPositions: getOpenPositions, @@ -32,7 +27,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } poloniexApiClient = POLONIEX_CLIENT_MODULE.newPoloniexAPIClient(global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Key, global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Secret); @@ -40,7 +35,7 @@ } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -49,8 +44,8 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getOpenPositions -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getOpenPositions -> pMarket = " + JSON.stringify(pMarket)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> pMarket = " + JSON.stringify(pMarket)); } poloniexApiClient.API.returnOpenOrders(pMarket.assetA, pMarket.assetB, onExchangeCallReturned); @@ -58,9 +53,9 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getOpenPositions -> onExchangeCallReturned -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getOpenPositions -> onExchangeCallReturned -> err = " + err); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] getOpenPositions -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> onExchangeCallReturned -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> onExchangeCallReturned -> err = " + err); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk); @@ -101,12 +96,12 @@ } } catch (err) { - logger.write("[ERROR] getOpenPositions -> onExchangeCallReturned -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] getOpenPositions -> onExchangeCallReturned -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] getOpenPositions -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] getOpenPositions -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -115,8 +110,8 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getExecutedTrades -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getExecutedTrades -> pPositionId = " + pPositionId); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> pPositionId = " + pPositionId); } poloniexApiClient.API.returnOrderTrades(pPositionId, onExchangeCallReturned); @@ -124,9 +119,9 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getExecutedTrades -> onExchangeCallReturned -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getExecutedTrades -> onExchangeCallReturned -> err = " + err); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] getExecutedTrades -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> onExchangeCallReturned -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> onExchangeCallReturned -> err = " + err); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk); @@ -174,12 +169,12 @@ } } catch (err) { - logger.write("[ERROR] getExecutedTrades -> onExchangeCallReturned -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] getExecutedTrades -> onExchangeCallReturned -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] getExecutedTrades -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] getExecutedTrades -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -188,12 +183,12 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pMarket = " + JSON.stringify(pMarket)); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pType = " + pType); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pRate = " + pRate); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pAmountA = " + pAmountA); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> pAmountB = " + pAmountB); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pMarket = " + JSON.stringify(pMarket)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pType = " + pType); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pRate = " + pRate); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pAmountA = " + pAmountA); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pAmountB = " + pAmountB); } if (pType === "buy") { poloniexApiClient.API.buy(pMarket.assetA, pMarket.assetB, pRate, pAmountB, onExchangeCallReturned); @@ -205,7 +200,7 @@ return; } - logger.write("[ERROR] putPosition -> pType must be either 'buy' or 'sell'."); + logger.write(MODULE_NAME, "[ERROR] putPosition -> pType must be either 'buy' or 'sell'."); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; @@ -213,9 +208,9 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> onExchangeCallReturned -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] putPosition -> onExchangeCallReturned -> err = " + err); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] putPosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onExchangeCallReturned -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onExchangeCallReturned -> err = " + err); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk); @@ -244,13 +239,13 @@ } } catch (err) { - logger.write("[ERROR] putPosition -> onExchangeCallReturned -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] putPosition -> onExchangeCallReturned -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] putPosition -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] putPosition -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -259,17 +254,17 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> pPosition = " + JSON.stringify(pPosition)); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> pNewRate = " + pNewRate); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> pPosition = " + JSON.stringify(pPosition)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> pNewRate = " + pNewRate); } poloniexApiClient.API.moveOrder(pPosition.id, pNewRate, pPosition.amountB, onExchangeCallReturned); function onExchangeCallReturned(err, exchangeResponse) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> onExchangeCallReturned -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> onExchangeCallReturned -> err = " + err); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] movePosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> err = " + err); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } try { @@ -278,7 +273,7 @@ function onResponseOk() { if (exchangeResponse.success !== 1) { - logger.write("[ERROR] movePosition -> onExchangeCallReturned -> exchangeResponse.success = " + exchangeResponse.success); + logger.write(MODULE_NAME, "[ERROR] movePosition -> onExchangeCallReturned -> exchangeResponse.success = " + exchangeResponse.success); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -305,13 +300,13 @@ } } catch (err) { - logger.write("[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] movePosition -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] movePosition -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -320,15 +315,15 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] getTicker -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTicker -> Entering function."); } poloniexApiClient.API.returnTicker(onExchangeCallReturned); function onExchangeCallReturned(err, exchangeResponse) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> onExchangeCallReturned -> Entering function."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] movePosition -> onExchangeCallReturned -> err = " + err); } - if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write("[INFO] movePosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> err = " + err); } + if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); } try { @@ -368,13 +363,13 @@ } } catch (err) { - logger.write("[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message); + logger.write(MODULE_NAME, "[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] movePosition -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] movePosition -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/ExtractionBotProcessMainLoop.js b/ExtractionBotProcessMainLoop.js index c0970ed02..8b6a94b30 100644 --- a/ExtractionBotProcessMainLoop.js +++ b/ExtractionBotProcessMainLoop.js @@ -1,9 +1,8 @@ -exports.newExtractionBotProcessMainLoop = function newExtractionBotProcessMainLoop(BOT) { +exports.newExtractionBotProcessMainLoop = function newExtractionBotProcessMainLoop(bot, parentLogger) { - let bot = BOT; const ROOT_DIR = './'; - const MODULE_NAME = "ExtractionBotProcessMainLoop"; + const MODULE_NAME = "Extraction Bot Process Main Loop"; const FULL_LOG = true; let USER_BOT_MODULE; @@ -11,18 +10,6 @@ const BLOB_STORAGE = require(ROOT_DIR + 'BlobStorage'); - const EVENT_HANDLER_MODULE = require(ROOT_DIR + 'EventHandler'); - bot.eventHandler = EVENT_HANDLER_MODULE.newEventHandler(); - - const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); - let logger; - - logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.forceLoopSplit = true; - logger.initialize(); - let thisObject = { initialize: initialize, run: run @@ -35,19 +22,21 @@ function initialize(pUI_COMMANDS, pProcessConfig, callBackFunction) { + /* This function is exactly the same in the 3 modules representing the 2 different bot types loops. */ + try { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } UI_COMMANDS = pUI_COMMANDS; processConfig = pProcessConfig; - cloudStorage = BLOB_STORAGE.newBlobStorage(bot); + cloudStorage = BLOB_STORAGE.newBlobStorage(bot, parentLogger); cloudStorage.initialize("AAPlatform", onInizialized); function onInizialized(err) { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] initialize -> onInizialized -> Entering function."); } if (err.result === global.DEFAULT_OK_RESPONSE.result) { @@ -63,15 +52,14 @@ break; } default: { - logger.write("[ERROR] initialize -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] initialize -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } } const CLOUD_REQUIRE = require(ROOT_DIR + 'CloudRequire'); - let cloudRequire = CLOUD_REQUIRE.newCloudRequire(bot, DEBUG_MODULE); + let cloudRequire = CLOUD_REQUIRE.newCloudRequire(bot, parentLogger); cloudRequire.downloadBot(cloudStorage, filePath, onBotDownloaded); @@ -79,9 +67,8 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> err.message = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } @@ -97,8 +84,8 @@ break; } default: { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -110,9 +97,8 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> onCommonsDownloaded -> err.message = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> onCommonsDownloaded -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } @@ -123,14 +109,12 @@ } } else { - logger.write("[ERROR] Root -> start -> getBotConfig -> onInizialized -> err = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] Root -> start -> getBotConfig -> onInizialized -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -138,9 +122,7 @@ function run(pMonth, pYear, callBackFunction) { try { - if (FULL_LOG === true) { logger.write("[INFO] run -> Entering function."); } - - bot.eventHandler.raiseEvent("Close Log File"); + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] run -> Entering function."); } let intervalHandle; @@ -160,16 +142,17 @@ try { /* For each loop we want to create a new log file. */ - + + const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); + let logger; + logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; logger.bot = bot; - logger.forceLoopSplit = true; logger.initialize(); bot.loopCounter++; - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Entering function."); } /* We define here all the modules that the rest of the infraestructure, including the bots themselves can consume. */ @@ -195,9 +178,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeStatusDependencies -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> Entering function."); } - statusDependencies = STATUS_DEPENDENCIES.newStatusDependencies(bot, DEBUG_MODULE, STATUS_REPORT, BLOB_STORAGE, UTILITIES); + statusDependencies = STATUS_DEPENDENCIES.newStatusDependencies(bot, logger, STATUS_REPORT, BLOB_STORAGE, UTILITIES); statusDependencies.initialize(processConfig.statusDependencies, pMonth, pYear, onInizialized); @@ -205,32 +188,32 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Execution finished well."); initializeUserBot(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; @@ -238,16 +221,16 @@ } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> err = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> err = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); } @@ -257,9 +240,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeUserBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> Entering function."); } - usertBot = USER_BOT_MODULE.newUserBot(bot, COMMONS_MODULE, UTILITIES, DEBUG_MODULE, BLOB_STORAGE, STATUS_REPORT, POLONIEX_CLIENT_MODULE); + usertBot = USER_BOT_MODULE.newUserBot(bot, logger, COMMONS_MODULE, UTILITIES, BLOB_STORAGE, STATUS_REPORT, POLONIEX_CLIENT_MODULE); usertBot.initialize(statusDependencies, pMonth, pYear, onInizialized); @@ -267,23 +250,23 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeUserBot -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeUserBot -> onInizialized > Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> onInizialized > Execution finished well."); startUserBot(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized > Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized > Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized > Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized > Operation Failed. Aborting the process."); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); return; @@ -292,22 +275,22 @@ switch (err.message) { case "Too far in the future.": { - logger.write("[WARN] run -> loop -> initializeUserBot -> onInizialized > Too far in the future. This Loop will enter in coma."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> initializeUserBot -> onInizialized > Too far in the future. This Loop will enter in coma."); nextWaitTime = 'Coma'; clearInterval(intervalHandle); loopControl(nextWaitTime); return; } case "Not needed now, but soon.": { - logger.write("[WARN] run -> loop -> initializeUserBot -> onInizialized > Not needed now, but soon. This Loop will continue with Normal wait time."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> initializeUserBot -> onInizialized > Not needed now, but soon. This Loop will continue with Normal wait time."); nextWaitTime = 'Normal'; clearInterval(intervalHandle); loopControl(nextWaitTime); return; } default: { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled custom response received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled custom response received. -> err.message = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); return; @@ -315,10 +298,10 @@ } } default: { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; @@ -326,16 +309,16 @@ } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> err = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeUserBot -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> err = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); } @@ -345,7 +328,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> startUserBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> Entering function."); } usertBot.start(onFinished); @@ -353,24 +336,24 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> startUserBot -> onFinished -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> onFinished -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> startUserBot -> onFinished > Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> onFinished > Execution finished well."); nextWaitTime = 'Normal'; loopControl(nextWaitTime); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished > Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished > Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished > Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished > Operation Failed. Aborting the process."); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); return; @@ -379,41 +362,41 @@ switch (err.message) { case "Dependency does not exist.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished > Dependency does not exist. This Loop will go to sleep."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished > Dependency does not exist. This Loop will go to sleep."); nextWaitTime = 'Sleep'; loopControl(nextWaitTime); return; } case "Dependency not ready.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished > Dependency not ready. This Loop will go to sleep."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished > Dependency not ready. This Loop will go to sleep."); nextWaitTime = 'Sleep'; loopControl(nextWaitTime); return; } case "Month before it is needed.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished > Month before it is needed. This Loop will be terminated."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished > Month before it is needed. This Loop will be terminated."); + logger.persist(); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } case "Month fully processed.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished > Month fully processed. This Loop will be terminated."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished > Month fully processed. This Loop will be terminated."); + logger.persist(); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } case "End of the month reached.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished > End of the month reached. This Loop will be terminated."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished > End of the month reached. This Loop will be terminated."); + logger.persist(); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } default: { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished > Unhandled custom response received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished > Unhandled custom response received. -> err.message = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); return; @@ -421,10 +404,10 @@ } } default: { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished > Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished > Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished > Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished > Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; @@ -432,188 +415,187 @@ } } catch (err) { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> err = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> startUserBot -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> err = " + err.message); + logger.persist(); clearInterval(intervalHandle); callBackFunction(err); } } + function loopControl(nextWaitTime) { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> nextWaitTime = " + nextWaitTime); } + + /* Here we check if we must stop the loop gracefully. */ + + shallWeStop(onStop, onContinue); + + function onStop() { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Stopping the Loop Gracefully. See you next time!"); } + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_OK_RESPONSE); + return; + + } + + function onContinue() { + + /* Extraction bots are going to be executed after a configured period of time after the last execution ended. This is to avoid overlapping executions. */ + + switch (nextWaitTime) { + case 'Normal': { + if (bot.runAtFixedInterval === true) { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Fixed Interval Normal exit point reached."); } + logger.persist(); + return; + } else { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.normalWaitTime / 1000) + " seconds."); } + logger.persist(); + setTimeout(loop, processConfig.normalWaitTime); + } + } + break; + case 'Retry': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.retryWaitTime / 1000) + " seconds."); } + logger.persist(); + setTimeout(loop, processConfig.retryWaitTime); + } + break; + case 'Sleep': { + if (bot.runAtFixedInterval === true) { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Fixed Interval Sleep exit point reached."); } + logger.persist(); + return; + } else { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.sleepWaitTime / 60000) + " minutes."); } + logger.persist(); + setTimeout(loop, processConfig.sleepWaitTime); + } + } + break; + case 'Coma': { + if (bot.runAtFixedInterval === true) { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Fixed Interval Coma exit point reached."); } + logger.persist(); + return; + } else { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.comaWaitTime / 3600000) + " hours."); } + logger.persist(); + setTimeout(loop, processConfig.comaWaitTime); + } + } + break; + } + } + } + + function shallWeStop(stopCallBack, continueCallBack) { + + try { + + /* IMPORTANT: This function is exactly the same on the 3 modules. */ + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> shallWeStop -> Entering function. "); } + + cloudStorage = BLOB_STORAGE.newBlobStorage(bot, logger); + + cloudStorage.initialize("AAPlatform", onInizialized); + + function onInizialized(err) { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> shallWeStop -> onInizialized -> Entering function."); } + + if (err.result === global.DEFAULT_OK_RESPONSE.result) { + + let filePath; + + switch (global.CURRENT_EXECUTION_AT) { // This is what determines if the bot is loaded from the devTeam or an endUser copy. + case "Cloud": { + filePath = global.DEV_TEAM + "/" + "AACloud"; // DevTeams bots only are run at the cloud. + break; + } + case "Browser": { + if (global.SHALL_BOT_STOP === false) { + continueCallBack(); + } else { + stopCallBack(); + } + break; + } + default: { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + + let fileName = "this.config.json"; + + cloudStorage.getTextFile(filePath, fileName, onFileReceived); + + function onFileReceived(err, text) { + + if (err.result !== global.DEFAULT_OK_RESPONSE.result) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onFileReceived -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + + try { + + let configRead = JSON.parse(text); + + if (configRead.stopGracefully === false && global.SHALL_BOT_STOP === false) { + continueCallBack(); + } else { + stopCallBack(); + } + + } catch (err) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onFileReceived -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + } + } + } + catch (err) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + } catch (err) { - logger.write("[ERROR] run -> loop -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] run -> loop -> err = " + err.message); clearInterval(intervalHandle); callBackFunction(err); } } - - function loopControl(nextWaitTime) { - - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> nextWaitTime = " + nextWaitTime); } - - /* Here we check if we must stop the loop gracefully. */ - - shallWeStop(onStop, onContinue); - - function onStop() { - - if (bot.runAtFixedInterval === true) { intervalHandle.clearInterval();} - - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Stopping the Loop Gracefully. See you next time!"); } - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_OK_RESPONSE); - return; - - } - - function onContinue() { - - /* Extraction bots are going to be executed after a configured period of time after the last execution ended. This is to avoid overlapping executions. */ - - switch (nextWaitTime) { - case 'Normal': { - if (bot.runAtFixedInterval === true) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Fixed Interval Normal exit point reached."); } - bot.eventHandler.raiseEvent("Close Log File"); - return; - } else { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.normalWaitTime / 1000) + " seconds."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.normalWaitTime); - } - } - break; - case 'Retry': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.retryWaitTime / 1000) + " seconds."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.retryWaitTime); - } - break; - case 'Sleep': { - if (bot.runAtFixedInterval === true) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Fixed Interval Sleep exit point reached."); } - bot.eventHandler.raiseEvent("Close Log File"); - return; - } else { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.sleepWaitTime / 60000) + " minutes."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.sleepWaitTime); - } - } - break; - case 'Coma': { - if (bot.runAtFixedInterval === true) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Fixed Interval Coma exit point reached."); } - bot.eventHandler.raiseEvent("Close Log File"); - return; - } else { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.comaWaitTime / 3600000) + " hours."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.comaWaitTime); - } - } - break; - } - } - } - - function shallWeStop(stopCallBack, continueCallBack) { - - try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> shallWeStop -> Entering function. "); } - - cloudStorage = BLOB_STORAGE.newBlobStorage(bot); - - cloudStorage.initialize("AAPlatform", onInizialized); - - function onInizialized(err) { - - if (FULL_LOG === true) { logger.write("[INFO] initialize -> onInizialized -> Entering function."); } - - if (err.result === global.DEFAULT_OK_RESPONSE.result) { - - let filePath; - - switch (global.CURRENT_EXECUTION_AT) { // This is what determines if the bot is loaded from the devTeam or an endUser copy. - case "Cloud": { - filePath = global.DEV_TEAM + "/" + "AACloud"; // DevTeams bots only are run at the cloud. - break; - } - case "Browser": { - if (global.SHALL_BOT_STOP === false) { - continueCallBack(); - } else { - stopCallBack(); - } - break; - } - default: { - logger.write("[ERROR] shallWeStop -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] shallWeStop -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } - - let fileName = "this.config.json"; - - cloudStorage.getTextFile(filePath, fileName, onFileReceived); - - function onFileReceived(err, text) { - - if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> onFileReceived -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - - try { - - let configRead = JSON.parse(text); - - if (configRead.stopGracefully === false && global.SHALL_BOT_STOP === false) { - continueCallBack(); - } else { - stopCallBack(); - } - - } catch (err) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> onFileReceived -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } - } - } - } - catch (err) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } } catch (err) { - logger.write("[ERROR] run -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] run -> err = " + err.message); clearInterval(intervalHandle); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } diff --git a/IndicatorBotProcessMainLoop.js b/IndicatorBotProcessMainLoop.js index 676d16594..09e728fbc 100644 --- a/IndicatorBotProcessMainLoop.js +++ b/IndicatorBotProcessMainLoop.js @@ -1,9 +1,8 @@ -exports.newIndicatorBotProcessMainLoop = function newIndicatorBotProcessMainLoop(BOT) { +exports.newIndicatorBotProcessMainLoop = function newIndicatorBotProcessMainLoop(bot, parentLogger) { - let bot = BOT; const ROOT_DIR = './'; - const MODULE_NAME = "IndicatorBotProcessMainLoop"; + const MODULE_NAME = "Indicator Bot Process Main Loop"; const FULL_LOG = true; let USER_BOT_MODULE; @@ -11,18 +10,6 @@ const BLOB_STORAGE = require(ROOT_DIR + 'BlobStorage'); - const EVENT_HANDLER_MODULE = require(ROOT_DIR + 'EventHandler'); - bot.eventHandler = EVENT_HANDLER_MODULE.newEventHandler(); - - const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); - let logger; - - logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.forceLoopSplit = true; - logger.initialize(); - let thisObject = { initialize: initialize, run: run @@ -35,19 +22,21 @@ function initialize(pUI_COMMANDS, pProcessConfig, callBackFunction) { + /* This function is exactly the same in the 3 modules representing the 2 different bot types loops. */ + try { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } UI_COMMANDS = pUI_COMMANDS; processConfig = pProcessConfig; - cloudStorage = BLOB_STORAGE.newBlobStorage(bot); + cloudStorage = BLOB_STORAGE.newBlobStorage(bot, parentLogger); cloudStorage.initialize("AAPlatform", onInizialized); function onInizialized(err) { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] initialize -> onInizialized -> Entering function."); } if (err.result === global.DEFAULT_OK_RESPONSE.result) { @@ -63,16 +52,15 @@ break; } default: { - logger.write("[ERROR] initialize -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] initialize -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } } const CLOUD_REQUIRE = require(ROOT_DIR + 'CloudRequire'); - let cloudRequire = CLOUD_REQUIRE.newCloudRequire(bot, DEBUG_MODULE); + let cloudRequire = CLOUD_REQUIRE.newCloudRequire(bot, parentLogger); cloudRequire.downloadBot(cloudStorage, filePath, onBotDownloaded); @@ -80,9 +68,8 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> err.message = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } @@ -98,8 +85,8 @@ break; } default: { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -111,9 +98,8 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> onCommonsDownloaded -> err.message = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> onCommonsDownloaded -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } @@ -124,14 +110,12 @@ } } else { - logger.write("[ERROR] Root -> start -> getBotConfig -> onInizialized -> err = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] Root -> start -> getBotConfig -> onInizialized -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -139,9 +123,8 @@ function run(pMonth, pYear, callBackFunction) { try { - if (FULL_LOG === true) { logger.write("[INFO] run -> Entering function."); } - bot.eventHandler.raiseEvent("Close Log File"); + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] run -> Entering function."); } let intervalHandle; @@ -161,15 +144,16 @@ /* For each loop we want to create a new log file. */ + const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); + let logger; + logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; logger.bot = bot; - logger.forceLoopSplit = true; logger.initialize(); bot.loopCounter++; - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Entering function."); } /* We define here all the modules that the rest of the infraestructure, including the bots themselves can consume. */ @@ -194,9 +178,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeStatusDependencies -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> Entering function."); } - statusDependencies = STATUS_DEPENDENCIES.newStatusDependencies(bot, DEBUG_MODULE, STATUS_REPORT, BLOB_STORAGE, UTILITIES); + statusDependencies = STATUS_DEPENDENCIES.newStatusDependencies(bot, logger, STATUS_REPORT, BLOB_STORAGE, UTILITIES); statusDependencies.initialize(processConfig.statusDependencies, pMonth, pYear, onInizialized); @@ -204,47 +188,47 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Execution finished well."); initializeUserBot(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Operation Failed. Aborting the process."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -253,9 +237,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeUserBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> Entering function."); } - usertBot = USER_BOT_MODULE.newUserBot(bot, COMMONS_MODULE, UTILITIES, DEBUG_MODULE, BLOB_STORAGE); + usertBot = USER_BOT_MODULE.newUserBot(bot, logger, COMMONS_MODULE, UTILITIES, BLOB_STORAGE); usertBot.initialize(statusDependencies, pMonth, pYear, onInizialized); @@ -263,23 +247,23 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeUserBot -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeUserBot -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> onInizialized -> Execution finished well."); startUserBot(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } @@ -287,45 +271,45 @@ switch (err.message) { case "Too far in the future.": { - logger.write("[WARN] run -> loop -> initializeUserBot -> onInizialized > Too far in the future. This Loop will enter in coma."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> initializeUserBot -> onInizialized > Too far in the future. This Loop will enter in coma."); nextWaitTime = 'Coma'; loopControl(nextWaitTime); return; } case "Not needed now, but soon.": { - logger.write("[WARN] run -> loop -> initializeUserBot -> onInizialized > Not needed now, but soon. This Loop will continue with Normal wait time."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> initializeUserBot -> onInizialized > Not needed now, but soon. This Loop will continue with Normal wait time."); nextWaitTime = 'Normal'; loopControl(nextWaitTime); return; } default: { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled custom response received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized > Unhandled custom response received. -> err.message = " + err.message); + logger.persist(); callBackFunction(err); return; } } } default: { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeUserBot -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -334,7 +318,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> startUserBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> Entering function."); } usertBot.start(onFinished); @@ -342,24 +326,24 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> startUserBot -> onFinished -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> onFinished -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> startUserBot -> onFinished -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> onFinished -> Execution finished well."); nextWaitTime = 'Normal'; loopControl(nextWaitTime); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } @@ -367,213 +351,216 @@ switch (err.message) { case "Dependency does not exist.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished -> Dependency does not exist. This Loop will go to sleep."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished -> Dependency does not exist. This Loop will go to sleep."); nextWaitTime = 'Sleep'; loopControl(nextWaitTime); return; } case "Dependency not ready.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished -> Dependency not ready. This Loop will go to sleep."); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished -> Dependency not ready. This Loop will go to sleep."); nextWaitTime = 'Sleep'; loopControl(nextWaitTime); return; } case "Month before it is needed.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished -> Month before it is needed. This Loop will be terminated."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished -> Month before it is needed. This Loop will be terminated."); + logger.persist(); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } case "Month fully processed.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished -> Month fully processed. This Loop will be terminated."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished -> Month fully processed. This Loop will be terminated."); + logger.persist(); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } case "End of the month reached.": { - logger.write("[WARN] run -> loop -> startUserBot -> onFinished -> End of the month reached. This Loop will be terminated."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[WARN] run -> loop -> startUserBot -> onFinished -> End of the month reached. This Loop will be terminated."); + logger.persist(); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } default: { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled custom response received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled custom response received. -> err.message = " + err.message); + logger.persist(); callBackFunction(err); return; } } } default: { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> startUserBot -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> err = " + err.message); + logger.persist(); callBackFunction(err); } } + function loopControl(nextWaitTime) { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> nextWaitTime = " + nextWaitTime); } + + /* Here we check if we must stop the loop gracefully. */ + + shallWeStop(onStop, onContinue); + + function onStop() { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Stopping the Loop Gracefully. See you next time!"); } + + logger.persist(); + callBackFunction(global.DEFAULT_OK_RESPONSE); + return; + + } + + function onContinue() { + + /* Indicator bots are going to be executed after a configured period of time after the last execution ended. This is to avoid overlapping executions. */ + + switch (nextWaitTime) { + case 'Normal': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.normalWaitTime / 1000) + " seconds."); } + logger.persist(); + setTimeout(loop, processConfig.normalWaitTime); + } + break; + case 'Retry': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.retryWaitTime / 1000) + " seconds."); } + logger.persist(); + setTimeout(loop, processConfig.retryWaitTime); + } + break; + case 'Sleep': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.sleepWaitTime / 60000) + " minutes."); } + logger.persist(); + setTimeout(loop, processConfig.sleepWaitTime); + } + break; + case 'Coma': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Restarting Loop in " + (processConfig.comaWaitTime / 3600000) + " hours."); } + logger.persist(); + setTimeout(loop, processConfig.comaWaitTime); + } + break; + } + } + } + + function shallWeStop(stopCallBack, continueCallBack) { + + try { + + /* IMPORTANT: This function is exactly the same on the 3 modules. */ + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> shallWeStop -> Entering function. "); } + + cloudStorage = BLOB_STORAGE.newBlobStorage(bot, logger); + + cloudStorage.initialize("AAPlatform", onInizialized); + + function onInizialized(err) { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> shallWeStop -> onInizialized -> Entering function."); } + + if (err.result === global.DEFAULT_OK_RESPONSE.result) { + + let filePath; + + switch (global.CURRENT_EXECUTION_AT) { // This is what determines if the bot is loaded from the devTeam or an endUser copy. + case "Cloud": { + filePath = global.DEV_TEAM + "/" + "AACloud"; // DevTeams bots only are run at the cloud. + break; + } + case "Browser": { + if (global.SHALL_BOT_STOP === false) { + continueCallBack(); + } else { + stopCallBack(); + } + break; + } + default: { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + + let fileName = "this.config.json"; + + cloudStorage.getTextFile(filePath, fileName, onFileReceived); + + function onFileReceived(err, text) { + + if (err.result !== global.DEFAULT_OK_RESPONSE.result) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onFileReceived -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + + try { + + let configRead = JSON.parse(text); + + if (configRead.stopGracefully === false && global.SHALL_BOT_STOP === false) { + continueCallBack(); + } else { + stopCallBack(); + } + + } catch (err) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onFileReceived -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + } + } + } + catch (err) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + } catch (err) { - logger.write("[ERROR] run -> loop -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - callBackFunction(err); - } - } - - function loopControl(nextWaitTime) { - - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> nextWaitTime = " + nextWaitTime); } - - /* Here we check if we must stop the loop gracefully. */ - - shallWeStop(onStop, onContinue); - - function onStop() { - - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Stopping the Loop Gracefully. See you next time!"); } - - bot.eventHandler.raiseEvent("Close Log File"); - callBackFunction(global.DEFAULT_OK_RESPONSE); - return; - - } - - function onContinue() { - - /* Indicator bots are going to be executed after a configured period of time after the last execution ended. This is to avoid overlapping executions. */ - - switch (nextWaitTime) { - case 'Normal': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.normalWaitTime / 1000) + " seconds."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.normalWaitTime); - } - break; - case 'Retry': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.retryWaitTime / 1000) + " seconds."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.retryWaitTime); - } - break; - case 'Sleep': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.sleepWaitTime / 60000) + " minutes."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.sleepWaitTime); - } - break; - case 'Coma': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Restarting Loop in " + (processConfig.comaWaitTime / 3600000) + " hours."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.comaWaitTime); - } - break; - } - } - } - - function shallWeStop(stopCallBack, continueCallBack) { - - try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> shallWeStop -> Entering function. "); } - - cloudStorage = BLOB_STORAGE.newBlobStorage(bot); - - cloudStorage.initialize("AAPlatform", onInizialized); - - function onInizialized(err) { - - if (FULL_LOG === true) { logger.write("[INFO] initialize -> onInizialized -> Entering function."); } - - if (err.result === global.DEFAULT_OK_RESPONSE.result) { - - let filePath; - - switch (global.CURRENT_EXECUTION_AT) { // This is what determines if the bot is loaded from the devTeam or an endUser copy. - case "Cloud": { - filePath = global.DEV_TEAM + "/" + "AACloud"; // DevTeams bots only are run at the cloud. - break; - } - case "Browser": { - if (global.SHALL_BOT_STOP === false) { - continueCallBack(); - } else { - stopCallBack(); - } - break; - } - default: { - logger.write("[ERROR] shallWeStop -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] shallWeStop -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } - - let fileName = "this.config.json"; - - cloudStorage.getTextFile(filePath, fileName, onFileReceived); - - function onFileReceived(err, text) { - - if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> onFileReceived -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - - try { - - let configRead = JSON.parse(text); - - if (configRead.stopGracefully === false && global.SHALL_BOT_STOP === false) { - continueCallBack(); - } else { - stopCallBack(); - } - - } catch (err) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> onFileReceived -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } - } - } - } - catch (err) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] run -> loop -> err = " + err.message); clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; + callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] run -> err = " + err.message); + clearInterval(intervalHandle); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/PoloniexAPIClient.js b/PoloniexAPIClient.js index 60e9889ca..b140bd44c 100644 --- a/PoloniexAPIClient.js +++ b/PoloniexAPIClient.js @@ -403,6 +403,7 @@ const FULL_LOG = false; const LOG_FILE_CONTENT = false; + const MODULE_NAME = "Poloniex API ClientS"; /* This function analizes the different situations we might encounter trying to access Poloniex and returns appropiate standard errors. */ @@ -411,8 +412,8 @@ let stringExchangeResponse = JSON.stringify(exchangeResponse); let stringExchangeErr = JSON.stringify(exchangeErr); - if (FULL_LOG === true) { logger.write("[INFO] analizeResponse -> exchangeErr = " + stringExchangeErr); } - if (LOG_FILE_CONTENT === true) { logger.write("[INFO] analizeResponse -> exchangeResponse = " + stringExchangeResponse); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] analizeResponse -> exchangeErr = " + stringExchangeErr); } + if (LOG_FILE_CONTENT === true) { logger.write(MODULE_NAME, "[INFO] analizeResponse -> exchangeResponse = " + stringExchangeResponse); } if (stringExchangeErr.indexOf("ETIMEDOUT") > 0 || stringExchangeErr.indexOf("ENOTFOUND") > 0 || @@ -425,7 +426,7 @@ stringExchangeResponse.indexOf("Bad gateway") > 0 || stringExchangeResponse.indexOf("Internal error. Please try again") > 0))) { - logger.write("[WARN] analizeResponse -> Timeout reached or connection problem while trying to access the Exchange API. Requesting new execution later."); + logger.write(MODULE_NAME, "[WARN] analizeResponse -> Timeout reached or connection problem while trying to access the Exchange API. Requesting new execution later."); notOkCallBack(global.DEFAULT_RETRY_RESPONSE); return; @@ -433,27 +434,27 @@ if (JSON.stringify(exchangeResponse).indexOf("error") > 0) { - logger.write("[ERROR] analizeResponse -> Unexpected response from the Exchange."); + logger.write(MODULE_NAME, "[ERROR] analizeResponse -> Unexpected response from the Exchange."); notOkCallBack(global.DEFAULT_FAIL_RESPONSE); return; } if (exchangeErr) { - logger.write("[ERROR] analizeResponse -> Unexpected error trying to contact the Exchange."); + logger.write(MODULE_NAME, "[ERROR] analizeResponse -> Unexpected error trying to contact the Exchange."); notOkCallBack(global.DEFAULT_FAIL_RESPONSE); return; } else { - logger.write("[INFO] analizeResponse -> No problem found."); + logger.write(MODULE_NAME, "[INFO] analizeResponse -> No problem found."); okCallBack(); return; } } } catch (err) { - logger.write("[ERROR] analizeResponse -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] analizeResponse -> err.message = " + err.message); notOkCallBack(global.DEFAULT_FAIL_RESPONSE); return; } diff --git a/Project.njsproj b/Project.njsproj index 96c0cc835..34e1c0483 100644 --- a/Project.njsproj +++ b/Project.njsproj @@ -38,7 +38,6 @@ Code - Code diff --git a/Root.js b/Root.js index df6835b50..28e1a2910 100644 --- a/Root.js +++ b/Root.js @@ -5,35 +5,35 @@ exports.newRoot = function newRoot() { /* Global constants definitions. */ global.LOG_CONTROL = { - Assistant: { + "Assistant": { logInfo: true, logWarnings: true, logErrors: true, logContent: false, intensiveLogging: false }, - ExchangeAPI: { + "Exchange API": { logInfo: true, logWarnings: true, logErrors: true, logContent: false, intensiveLogging: false }, - StatusReport: { + "Status Report": { logInfo: true, logWarnings: true, logErrors: true, logContent: false, intensiveLogging: false }, - DataSet: { + "Data Set": { logInfo: true, logWarnings: true, logErrors: true, logContent: false, intensiveLogging: false }, - Context: { + "Context": { logInfo: true, logWarnings: true, logErrors: true, @@ -200,8 +200,6 @@ exports.newRoot = function newRoot() { /* Now we will run according to what we see at the config file. */ - const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); - /* Small Function to fix numbers into strings in a cool way. */ function pad(str, max) { @@ -217,8 +215,6 @@ exports.newRoot = function newRoot() { /* Loop through all the processes configured to be run by this Node.js Instance. */ - let logger; - for (let p = 0; p < global.PLATFORM_CONFIG.executionList.length; p++) { let listItem = PLATFORM_CONFIG.executionList[p]; @@ -317,24 +313,19 @@ exports.newRoot = function newRoot() { botConfig.process = listItem.process; botConfig.debug = {}; - botConfig.sharedLogFileMap = new Map(); - - logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = botConfig; /* Loop Counter */ botConfig.loopCounter = 0; - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> Processing item from executionList -> p = " + p); } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> listItem.botPath = " + listItem.botPath); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> Processing item from executionList -> p = " + p); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> listItem.botPath = " + listItem.botPath); } /* File Path Root */ botConfig.filePathRoot = botConfig.devTeam + "/" + botConfig.codeName + "." + botConfig.version.major + "." + botConfig.version.minor + "/" + global.PLATFORM_CONFIG.codeName + "." + global.PLATFORM_CONFIG.version.major + "." + global.PLATFORM_CONFIG.version.minor + "/" + global.EXCHANGE_NAME + "/" + botConfig.dataSetVersion; - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> listItem.process = " + listItem.process); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> listItem.process = " + listItem.process); } /* Now we loop throug all the configured processes at each bots configuration until we find the one we are supposed to run at this Node.js process. */ @@ -345,7 +336,7 @@ exports.newRoot = function newRoot() { if (botConfig.processes[i].name === listItem.process) { processFound = true; - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> Process found at the bot configuration file. -> listItem.process = " + listItem.process); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> Process found at the bot configuration file. -> listItem.process = " + listItem.process); } let processConfig = botConfig.processes[i]; @@ -390,8 +381,8 @@ exports.newRoot = function newRoot() { } } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> Process found at the bot configuration file. -> Start Mode Overwritten. "); } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> Process found at the bot configuration file. -> processConfig.startMode = " + processConfig.startMode); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> Process found at the bot configuration file. -> Start Mode Overwritten. "); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> Process found at the bot configuration file. -> processConfig.startMode = " + processConfig.startMode); } } @@ -401,28 +392,27 @@ exports.newRoot = function newRoot() { if (processConfig.startMode.allMonths.run === "true") { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> allMonths start mode detected. "); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> allMonths start mode detected. "); } for (let year = processConfig.startMode.allMonths.maxYear; year >= processConfig.startMode.allMonths.minYear; year--) { for (let month = 12; month > 0; month--) { - botConfig.debug = { - month: pad(month, 2), - year: pad(year, 4) - }; - let padMonth = pad(month, 2) let newInstanceBotConfig = JSON.parse(JSON.stringify(botConfig)); - newInstanceBotConfig.sharedLogFileMap = new Map(); + + newInstanceBotConfig.debug = { + month: pad(month, 2), + year: pad(year, 4) + }; let timeDelay = Math.random() * 10 * 1000; // We introduce a short delay so as to not overload the machine. setTimeout(startProcess, timeDelay); function startProcess() { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> startProcess -> Ready to start process."); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> startProcess -> Ready to start process."); } switch (botConfig.type) { case 'Extraction': { @@ -434,7 +424,7 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> startProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> startProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } @@ -447,13 +437,13 @@ exports.newRoot = function newRoot() { if (processConfig.startMode.oneMonth.run === "true") { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> oneMonth start mode detected. "); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> oneMonth start mode detected. "); } startProcess(); function startProcess() { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> startProcess -> Ready to start process."); } + if (FULL_LOG === true) { console.log(logDisplace + "Root : [INFO] start -> findProcess -> startProcess -> Ready to start process."); } let month = pad(processConfig.startMode.oneMonth.month, 2); let year = processConfig.startMode.oneMonth.year; @@ -473,7 +463,7 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> startProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> startProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } @@ -503,7 +493,7 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } @@ -525,7 +515,7 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } @@ -552,7 +542,7 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } @@ -580,7 +570,7 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } @@ -605,31 +595,38 @@ exports.newRoot = function newRoot() { break; } default: { - logger.write("[ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> Unexpected bot type. -> botConfig.type = " + botConfig.type); } } } } } catch (err) { - logger.write("[ERROR] start -> findProcess -> Unexpected exception. -> err.message = " + err.message); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> Unexpected exception. -> err.message = " + err.message); } } } if (processFound === false) { - logger.write("[ERROR] Process listed at the configuration file of AACloud not found at the configuration file of the bot. -> listItem.process = " + listItem.process); + console.log(logDisplace + "Root : [ERROR] Process listed at the configuration file of AACloud not found at the configuration file of the bot. -> listItem.process = " + listItem.process); } function runExtractionBot(pBotConfig, pProcessConfig, pMonth, pYear) { try { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess ->runExtractionBot -> Entering function."); } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess ->runExtractionBot -> pMonth = " + pMonth); } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess ->runExtractionBot -> pYear = " + pYear); } - let extractionBotMainLoop = EXTRACTION_BOT_MAIN_LOOP_MODULE.newExtractionBotProcessMainLoop(pBotConfig); + const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); + let logger; + + logger = DEBUG_MODULE.newDebugLog(); + logger.bot = pBotConfig; + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runExtractionBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runExtractionBot -> pMonth = " + pMonth); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runExtractionBot -> pYear = " + pYear); } + + let extractionBotMainLoop = EXTRACTION_BOT_MAIN_LOOP_MODULE.newExtractionBotProcessMainLoop(pBotConfig, logger); extractionBotMainLoop.initialize(UI_COMMANDS, pProcessConfig, onInitializeReady); function onInitializeReady(err) { @@ -640,6 +637,8 @@ exports.newRoot = function newRoot() { function whenRunFinishes(err) { + pBotConfig.loopCounter = 0; + let botId; if (pYear !== undefined) { botId = pBotConfig.devTeam + "." + pBotConfig.codeName + "." + pBotConfig.process + "." + pYear + "." + pMonth; @@ -649,39 +648,55 @@ exports.newRoot = function newRoot() { if (err.result === global.DEFAULT_OK_RESPONSE.result) { - logger.write("[INFO] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); - logger.write("[INFO] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); - console.log(botId + " Bot execution finished sucessfully."); + logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); + logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); + + console.log(logDisplace + "Root : [INFO] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> botId = " + botId); + console.log(logDisplace + "Root : [INFO] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); + + logger.persist(); } else { - logger.write("[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); - logger.write("[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); - logger.write("[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bye. :-("); - logger.write("[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); - console.log(botId + " Bot execution finished with errors. Please check the logs. :-("); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bye."); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); + + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> botId = " + botId); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> whenStartFinishes -> Bot execution was aborted."); + logger.persist(); } } } else { - logger.write("[ERROR] runExtractionBot -> onInitializeReady -> err = " + err.message); - logger.write("[ERROR] runExtractionBot -> onInitializeReady -> Bot will not be started. "); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> Bot will not be started. "); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runExtractionBot -> onInitializeReady -> err = " + err.message); + + logger.persist(); } } } catch (err) { - logger.write("[ERROR] runExtractionBot -> err = " + err.message); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runExtractionBot -> err = " + err.message); } } function runIndicatorBot(pBotConfig, pProcessConfig, pMonth, pYear) { try { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> runIndicatorBot -> Entering function."); } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> runIndicatorBot -> pMonth = " + pMonth); } - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> runIndicatorBot -> pYear = " + pYear); } + const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); + let logger; - let indicatorBotMainLoop = INDICATOR_BOT_MAIN_LOOP_MODULE.newIndicatorBotProcessMainLoop(pBotConfig); + logger = DEBUG_MODULE.newDebugLog(); + logger.bot = pBotConfig; + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runIndicatorBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runIndicatorBot -> pMonth = " + pMonth); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runIndicatorBot -> pYear = " + pYear); } + + let indicatorBotMainLoop = INDICATOR_BOT_MAIN_LOOP_MODULE.newIndicatorBotProcessMainLoop(pBotConfig, logger); indicatorBotMainLoop.initialize(UI_COMMANDS, pProcessConfig, onInitializeReady); function onInitializeReady(err) { @@ -692,6 +707,8 @@ exports.newRoot = function newRoot() { function whenRunFinishes(err) { + pBotConfig.loopCounter = 0; + let botId; if (pYear !== undefined) { botId = pBotConfig.devTeam + "." + pBotConfig.codeName + "." + pBotConfig.process + "." + pYear + "." + pMonth; @@ -701,37 +718,48 @@ exports.newRoot = function newRoot() { if (err.result === global.DEFAULT_OK_RESPONSE.result) { - logger.write("[INFO] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); - logger.write("[INFO] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); - console.log(botId + " Bot execution finished sucessfully."); + logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); + logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); + logger.persist(); } else { - logger.write("[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); - logger.write("[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); - logger.write("[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bye. :-("); - logger.write("[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); - console.log(botId + " Bot execution finished with errors. Please check the logs. :-("); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bye."); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished with errors. Please check the logs."); + logger.persist(); } } } else { - logger.write("[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> err = " + err.message); - logger.write("[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> Bot will not be started. "); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> Bot will not be started. "); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runIndicatorBot -> onInitializeReady -> err = " + err.message); + logger.persist(); } } } catch (err) { - logger.write("[ERROR] runIndicatorBot -> err = " + err.message); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runIndicatorBot -> err = " + err.message); + } } function runTradingBot(pBotConfig, pProcessConfig) { try { - if (FULL_LOG === true) { logger.write("[INFO] start -> findProcess -> runTradingBot -> Entering function."); } + const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); + let logger; - let tradingBotMainLoop = TRADING_BOT_MAIN_LOOP_MODULE.newTradingBotProcessMainLoop(pBotConfig); + logger = DEBUG_MODULE.newDebugLog(); + logger.bot = pBotConfig; + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runTradingBot -> Entering function."); } + + let tradingBotMainLoop = TRADING_BOT_MAIN_LOOP_MODULE.newTradingBotProcessMainLoop(pBotConfig, logger); tradingBotMainLoop.initialize(UI_COMMANDS, pProcessConfig, onInitializeReady); function onInitializeReady(err) { @@ -742,40 +770,47 @@ exports.newRoot = function newRoot() { function whenRunFinishes(err) { + pBotConfig.loopCounter = 0; + let botId; botId = pBotConfig.devTeam + "." + pBotConfig.codeName + "." + pBotConfig.process; if (err.result === global.DEFAULT_OK_RESPONSE.result) { - logger.write("[INFO] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); - logger.write("[INFO] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); - console.log(botId + " Bot execution finished sucessfully."); + logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); + logger.write(MODULE_NAME, "[INFO] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully."); + logger.persist(); } else { - logger.write("[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); - logger.write("[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); - logger.write("[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bye. :-("); - logger.write("[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); - console.log(botId + " Bot execution finished with errors. Please check the logs. :-("); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bye."); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot Id = " + botId); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> whenStartFinishes -> Bot execution finished with errors. Please check the logs."); + logger.persist(); } } } else { - logger.write("[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> err = " + err.message); - logger.write("[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> Bot will not be started. "); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> Bot will not be started. "); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runTradingBot -> onInitializeReady -> err = " + err.message); + + logger.persist(); } } } catch (err) { - logger.write("[ERROR] start -> findProcess -> runTradingBot -> err = " + err.message); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> runTradingBot -> err = " + err.message); } } } catch (err) { - logger.write("[ERROR] start -> findProcess -> err.message = " + err.message); + console.log(logDisplace + "Root : [ERROR] start -> findProcess -> err.message = " + err.message); return; } } diff --git a/StatusDependencies.js b/StatusDependencies.js index a83700472..f3ec5ee49 100644 --- a/StatusDependencies.js +++ b/StatusDependencies.js @@ -1,9 +1,9 @@ -exports.newStatusDependencies = function newStatusDependencies(BOT, DEBUG_MODULE, STATUS_REPORT, BLOB_STORAGE, UTILITIES) { +exports.newStatusDependencies = function newStatusDependencies(BOT, logger, STATUS_REPORT, BLOB_STORAGE, UTILITIES) { const FULL_LOG = true; const LOG_FILE_CONTENT = false; - const MODULE_NAME = "StatusDependencies"; + const MODULE_NAME = "Status Dependencies"; let thisObject = { statusReports: new Map(), @@ -14,18 +14,13 @@ let bot = BOT; let ownerBot; // This is the bot owner of the Status Report. Only owners can save the report and override the existing content. - const logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.initialize(); - return thisObject; function initialize(pStatusDependenciesConfig, pMonth, pYear, callBackFunction) { try { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } /* @@ -37,14 +32,14 @@ for (let i = 0; i < pStatusDependenciesConfig.length; i++) { - let statusReportModule = STATUS_REPORT.newStatusReport(BOT, DEBUG_MODULE, BLOB_STORAGE, UTILITIES); + let statusReportModule = STATUS_REPORT.newStatusReport(BOT, logger, BLOB_STORAGE, UTILITIES); statusReportModule.initialize(pStatusDependenciesConfig[i], pMonth, pYear, onInitilized); function onInitilized(err) { if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInitilized -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> onInitilized -> err = " + err.message); alreadyCalledBack = true; callBackFunction(err); @@ -62,32 +57,32 @@ switch (err.message) { case global.DEFAULT_OK_RESPONSE.message: { - logger.write("[INFO] initialize -> onLoad -> Execution finished well. -> bot = " + pStatusDependenciesConfig[i].bot); - logger.write("[INFO] initialize -> onLoad -> Execution finished well. -> process = " + pStatusDependenciesConfig[i].process); + logger.write(MODULE_NAME, "[INFO] initialize -> onLoad -> Execution finished well. -> bot = " + pStatusDependenciesConfig[i].bot); + logger.write(MODULE_NAME, "[INFO] initialize -> onLoad -> Execution finished well. -> process = " + pStatusDependenciesConfig[i].process); addReport(); return; } case "Status Report was never created.": { - logger.write("[WARN] initialize -> onLoad -> err.message = " + err.message); - logger.write("[WARN] initialize -> onLoad -> Report Not Found. -> bot = " + pStatusDependenciesConfig[i].bot); - logger.write("[WARN] initialize -> onLoad -> Report Not Found. -> process = " + pStatusDependenciesConfig[i].process); + logger.write(MODULE_NAME, "[WARN] initialize -> onLoad -> err.message = " + err.message); + logger.write(MODULE_NAME, "[WARN] initialize -> onLoad -> Report Not Found. -> bot = " + pStatusDependenciesConfig[i].bot); + logger.write(MODULE_NAME, "[WARN] initialize -> onLoad -> Report Not Found. -> process = " + pStatusDependenciesConfig[i].process); addReport(); return; } case "Status Report is corrupt.": { - logger.write("[WARN] initialize -> onLoad -> err.message = " + err.message); - logger.write("[WARN] initialize -> onLoad -> Report Not Found. -> bot = " + pStatusDependenciesConfig[i].bot); - logger.write("[WARN] initialize -> onLoad -> Report Not Found. -> process = " + pStatusDependenciesConfig[i].process); + logger.write(MODULE_NAME, "[WARN] initialize -> onLoad -> err.message = " + err.message); + logger.write(MODULE_NAME, "[WARN] initialize -> onLoad -> Report Not Found. -> bot = " + pStatusDependenciesConfig[i].bot); + logger.write(MODULE_NAME, "[WARN] initialize -> onLoad -> Report Not Found. -> process = " + pStatusDependenciesConfig[i].process); addReport(); return; } default: { - logger.write("[ERROR] initialize -> onLoad -> Operation Failed."); + logger.write(MODULE_NAME, "[ERROR] initialize -> onLoad -> Operation Failed."); if (alreadyCalledBack === false) { alreadyCalledBack = true; @@ -98,14 +93,14 @@ } } catch (err) { - logger.write("[ERROR] initialize -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> onLoad -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } function addReport() { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> addReport -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] initialize -> addReport -> Entering function."); } loadCount++; @@ -120,7 +115,7 @@ thisObject.keys.push(key); thisObject.statusReports.set(key, statusReportModule); - if (FULL_LOG === true) { logger.write("[INFO] initialize -> addReport -> Report added to Map. -> key = " + key); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] initialize -> addReport -> Report added to Map. -> key = " + key); } if (loadCount === pStatusDependenciesConfig.length) { if (alreadyCalledBack === false) { @@ -132,7 +127,7 @@ } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } diff --git a/StatusReport.js b/StatusReport.js index 786d3636b..915c1595f 100644 --- a/StatusReport.js +++ b/StatusReport.js @@ -1,4 +1,4 @@ -exports.newStatusReport = function newStatusReport(BOT, DEBUG_MODULE, BLOB_STORAGE, UTILITIES) { +exports.newStatusReport = function newStatusReport(BOT, logger, BLOB_STORAGE, UTILITIES) { /* @@ -8,14 +8,10 @@ */ - const MODULE_NAME = "StatusReport"; + const MODULE_NAME = "Status Report"; let bot = BOT; - const logger = DEBUG_MODULE.newDebugLog(); - logger.bot = bot; - logger.initialize(); - let thisObject = { file: undefined, // Here we have the JSON object representing the file content. initialize: initialize, @@ -29,11 +25,11 @@ /* Utilities needed. */ - let utilities = UTILITIES.newCloudUtilities(bot); + let utilities = UTILITIES.newCloudUtilities(bot, logger); /* Storage account to be used here. */ - let cloudStorage = BLOB_STORAGE.newBlobStorage(bot); + let cloudStorage = BLOB_STORAGE.newBlobStorage(bot, logger); let month; let year; @@ -58,7 +54,7 @@ timePath = "/" + year + "/" + month; } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } initializeStorage(); @@ -71,17 +67,17 @@ if (err.result === global.DEFAULT_OK_RESPONSE.result) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> initializeStorage -> onInizialized -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> initializeStorage -> onInizialized -> Entering function."); } callBackFunction(global.DEFAULT_OK_RESPONSE); } else { - logger.write("[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message); callBackFunction(err); } } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -90,14 +86,14 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> load -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> load -> Entering function."); } let rootPath = owner.devTeam + "/" + owner.bot + "." + owner.botVersion.major + "." + owner.botVersion.minor + "/" + global.PLATFORM_CONFIG.codeName + "." + global.PLATFORM_CONFIG.version.major + "." + global.PLATFORM_CONFIG.version.minor + "/" + global.EXCHANGE_NAME + "/" + owner.dataSetVersion; let fileName = "Status.Report." + global.MARKET.assetA + '_' + global.MARKET.assetB + ".json"; let filePath = rootPath + "/Reports/" + owner.process + timePath; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> load -> fileName = " + fileName); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] initialize -> load -> filePath = " + filePath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> load -> fileName = " + fileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> load -> filePath = " + filePath); } cloudStorage.getTextFile(filePath, fileName, onFileReceived); @@ -107,7 +103,7 @@ err.result === global.CUSTOM_FAIL_RESPONSE.result && (err.message === 'Folder does not exist.' || err.message === 'File does not exist.') ) { - logger.write("[INFO] initialize -> load -> onFileReceived -> err = " + err.message); + logger.write(MODULE_NAME, "[INFO] initialize -> load -> onFileReceived -> err = " + err.message); /* In this case we can assume that this is the first execution ever of this bot.*/ @@ -117,19 +113,19 @@ result: global.CUSTOM_OK_RESPONSE.result, message: "Status Report was never created." }; - logger.write("[WARN] initialize -> load -> onFileReceived -> customOK = " + customOK.message); + logger.write(MODULE_NAME, "[WARN] initialize -> load -> onFileReceived -> customOK = " + customOK.message); callBackFunction(customOK); return; } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> load -> onFileReceived -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> load -> onFileReceived -> err = " + err.message); callBackFunction(err); return; } if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { - logger.write("[INFO] initialize -> load -> onFileReceived -> Content received = " + text); + logger.write(MODULE_NAME, "[INFO] initialize -> load -> onFileReceived -> Content received = " + text); } try { @@ -144,20 +140,20 @@ is being updated at the moment of the read. The bot can not run without a valid Status Report but we can request the platform to retry later. */ - logger.write("[ERROR] initialize -> load -> onFileReceived -> Error Parsing the Status report. -> Err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> load -> onFileReceived -> Error Parsing the Status report. -> Err = " + err.message); let customFail = { result: global.CUSTOM_FAIL_RESPONSE.result, message: "Status Report is corrupt." }; - logger.write("[WARN] initialize -> load -> onFileReceived -> customFail = " + customFail.message); + logger.write(MODULE_NAME, "[WARN] initialize -> load -> onFileReceived -> customFail = " + customFail.message); callBackFunction(customFail); return; } } } catch (err) { - logger.write("[ERROR] initialize -> load -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] initialize -> load -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -166,7 +162,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] save -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] save -> Entering function."); } let ownerId = owner.devTeam + "-" + owner.bot + "-" + owner.botVersion.major + "-" + owner.botVersion.minor + "-" + owner.process + "-" + owner.dataSetVersion; let botId = bot.devTeam + "-" + bot.codeName + "-" + bot.version.major + "-" + bot.version.minor + "-" + bot.process + "-" + bot.dataSetVersion; @@ -177,7 +173,7 @@ result: global.CUSTOM_FAIL_RESPONSE.result, message: "Only bots owners of a Status Report can save them." }; - logger.write("[ERROR] save -> customErr = " + customErr.message); + logger.write(MODULE_NAME, "[ERROR] save -> customErr = " + customErr.message); callBackFunction(customErr); return; } @@ -185,8 +181,8 @@ let fileName = "Status.Report." + global.MARKET.assetA + '_' + global.MARKET.assetB + ".json"; let filePath = bot.filePathRoot + "/Reports/" + owner.process + timePath; - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] save -> fileName = " + fileName); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] save -> filePath = " + filePath); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] save -> fileName = " + fileName); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] save -> filePath = " + filePath); } utilities.createFolderIfNeeded(filePath, cloudStorage, onFolderCreated); @@ -194,10 +190,10 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] save -> onFolderCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] save -> onFolderCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] save -> onFolderCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] save -> onFolderCreated -> err = " + err.message); callBackFunction(err); return; } @@ -208,16 +204,16 @@ function onFileCreated(err) { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] save -> onFolderCreated -> onFileCreated -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] save -> onFolderCreated -> onFileCreated -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] save -> onFolderCreated -> onFileCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] save -> onFolderCreated -> onFileCreated -> err = " + err.message); callBackFunction(err); return; } if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { - logger.write("[INFO] save -> onFolderCreated -> onFileCreated -> Content written = " + fileContent); + logger.write(MODULE_NAME, "[INFO] save -> onFolderCreated -> onFileCreated -> Content written = " + fileContent); } callBackFunction(global.DEFAULT_OK_RESPONSE); @@ -225,13 +221,13 @@ } } catch (err) { - logger.write("[ERROR] save -> onFolderCreated -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] save -> onFolderCreated -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } } catch (err) { - logger.write("[ERROR] save -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] save -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -250,7 +246,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> Entering function."); } let initialYear; let initialMonth; @@ -266,24 +262,24 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> onLoad -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> onLoad -> Entering function."); } if ( err.result === global.CUSTOM_FAIL_RESPONSE.result && (err.message === 'Status Report was never created.') ) { - logger.write("[INFO] verifyMarketComplete -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> onLoad -> err = " + err.message); /* The first month of the market didnt create the main report yet. Aborting verification. */ - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> onLoad -> Verification ABORTED since the main status report does not exist."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> onLoad -> Verification ABORTED since the main status report does not exist."); } callBackFunction(global.DEFAULT_OK_RESPONSE); return; } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] verifyMarketComplete -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> onLoad -> err = " + err.message); callBackFunction(err); return; } @@ -296,7 +292,7 @@ loopCycle(); } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> onLoad -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -306,7 +302,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> loopCycle -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loopCycle -> Entering function."); } /* Here we read the status report file of each month / year to verify if it is complete or not. */ @@ -320,24 +316,24 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> loopCycle -> onLoad -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loopCycle -> onLoad -> Entering function."); } if ( err.result === global.CUSTOM_FAIL_RESPONSE.result && (err.message === 'Status Report was never created.') ) { - logger.write("[INFO] verifyMarketComplete -> loopCycle -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loopCycle -> onLoad -> err = " + err.message); /* The first month of the market didnt create the main report yet. Aborting verification. */ - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> loopCycle -> onLoad -> Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " did not exist. "); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loopCycle -> onLoad -> Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " did not exist. "); } callBackFunction(global.DEFAULT_OK_RESPONSE); return; } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] verifyMarketComplete -> loopCycle -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> loopCycle -> onLoad -> err = " + err.message); callBackFunction(err); return; } @@ -350,20 +346,20 @@ /* If any of the files says that month is not checked then it is enough to know the market continuity is broken. */ - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> loopCycle -> onLoad -> Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " is not marked as complete."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loopCycle -> onLoad -> Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " is not marked as complete."); } callBackFunction(global.DEFAULT_OK_RESPONSE); return; } } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> loopCycle -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> loopCycle -> onLoad -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> loopCycle -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> loopCycle -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -373,7 +369,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> readAndWriteNewReport -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> readAndWriteNewReport -> Entering function."); } /* We will read the current file to preserve its data, and save it again with the new lastFile */ @@ -387,10 +383,10 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> err = " + err.message); callBackFunction(err); return; } @@ -407,10 +403,10 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> onSave -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> onSave -> Entering function."); } if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> onSave -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> onSave -> err = " + err.message); callBackFunction(err); return; } @@ -418,7 +414,7 @@ loop(); // Lets see the next month. } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> onSave -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> onSave -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -426,20 +422,20 @@ } else { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> Main Status Report Not Updated."); } - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> Current Trade Id (" + monthlyStatusReport.lastTrade.id + ") is <= than Id at main status report file. (" + thisObject.file.lastTrade.id + ")"); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> Main Status Report Not Updated."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> Current Trade Id (" + monthlyStatusReport.lastTrade.id + ") is <= than Id at main status report file. (" + thisObject.file.lastTrade.id + ")"); } loop(); // Lets see the next month. } } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> readAndWriteNewReport -> onLoad -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> loopCycle -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> loopCycle -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -449,7 +445,7 @@ try { - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> loop -> Entering function."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loop -> Entering function."); } initialMonth++; @@ -464,7 +460,7 @@ /* We arrived to the point where we have checked all the status reports of every month and they are all complete. */ - if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write("[INFO] verifyMarketComplete -> loop -> Verification Finished. Success."); } + if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] verifyMarketComplete -> loop -> Verification Finished. Success."); } callBackFunction(global.DEFAULT_OK_RESPONSE); return; @@ -473,7 +469,7 @@ loopCycle(); } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> loop -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> loop -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -481,7 +477,7 @@ } catch (err) { - logger.write("[ERROR] verifyMarketComplete -> err = " + err.message); + logger.write(MODULE_NAME, "[ERROR] verifyMarketComplete -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } diff --git a/TradingBotProcessMainLoop.js b/TradingBotProcessMainLoop.js index ae4cb431d..63d22b1ed 100644 --- a/TradingBotProcessMainLoop.js +++ b/TradingBotProcessMainLoop.js @@ -1,9 +1,8 @@ -exports.newTradingBotProcessMainLoop = function newTradingBotProcessMainLoop(BOT) { +exports.newTradingBotProcessMainLoop = function newTradingBotProcessMainLoop(bot, parentLogger) { - let bot = BOT; const ROOT_DIR = './'; - const MODULE_NAME = "TradingBotProcessMainLoop"; + const MODULE_NAME = "Trading Bo tProcess Main Loop"; const FULL_LOG = true; let USER_BOT_MODULE; @@ -11,18 +10,6 @@ const BLOB_STORAGE = require(ROOT_DIR + 'BlobStorage'); - const EVENT_HANDLER_MODULE = require(ROOT_DIR + 'EventHandler'); - bot.eventHandler = EVENT_HANDLER_MODULE.newEventHandler(); - - const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); - let logger; - - logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; - logger.bot = bot; - logger.forceLoopSplit = true; - logger.initialize(); - let thisObject = { initialize: initialize, run: run @@ -36,19 +23,21 @@ function initialize(pUI_COMMANDS, pProcessConfig, callBackFunction) { + /* This function is exactly the same in the 3 modules representing the 2 different bot types loops. */ + try { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); } + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); } UI_COMMANDS = pUI_COMMANDS; processConfig = pProcessConfig; - cloudStorage = BLOB_STORAGE.newBlobStorage(bot); + cloudStorage = BLOB_STORAGE.newBlobStorage(bot, parentLogger); cloudStorage.initialize("AAPlatform", onInizialized); function onInizialized(err) { - if (FULL_LOG === true) { logger.write("[INFO] initialize -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] initialize -> onInizialized -> Entering function."); } if (err.result === global.DEFAULT_OK_RESPONSE.result) { @@ -64,16 +53,15 @@ break; } default: { - logger.write("[ERROR] initialize -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] initialize -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } } const CLOUD_REQUIRE = require(ROOT_DIR + 'CloudRequire'); - let cloudRequire = CLOUD_REQUIRE.newCloudRequire(bot, DEBUG_MODULE); + let cloudRequire = CLOUD_REQUIRE.newCloudRequire(bot, parentLogger); cloudRequire.downloadBot(cloudStorage, filePath, onBotDownloaded); @@ -81,9 +69,8 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> err.message = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } @@ -99,8 +86,8 @@ break; } default: { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } @@ -112,9 +99,8 @@ if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] initialize -> onInizialized -> onBotDownloaded -> onCommonsDownloaded -> err.message = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> onInizialized -> onBotDownloaded -> onCommonsDownloaded -> err.message = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); return; } @@ -125,14 +111,12 @@ } } else { - logger.write("[ERROR] Root -> start -> getBotConfig -> onInizialized -> err = " + err.message); + parentLogger.write(MODULE_NAME, "[ERROR] Root -> start -> getBotConfig -> onInizialized -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); - bot.eventHandler.raiseEvent("Close Log File"); } } } catch (err) { - logger.write("[ERROR] initialize -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] initialize -> err = " + err.message); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } } @@ -140,9 +124,7 @@ function run(callBackFunction) { try { - if (FULL_LOG === true) { logger.write("[INFO] run -> Entering function."); } - - bot.eventHandler.raiseEvent("Close Log File"); + if (FULL_LOG === true) { parentLogger.write(MODULE_NAME, "[INFO] run -> Entering function."); } let intervalHandle; @@ -162,15 +144,16 @@ /* For each loop we want to create a new log file. */ + const DEBUG_MODULE = require(ROOT_DIR + 'DebugLog'); + let logger; + logger = DEBUG_MODULE.newDebugLog(); - logger.fileName = MODULE_NAME; logger.bot = bot; - logger.forceLoopSplit = true; logger.initialize(); bot.loopCounter++; - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Entering function."); } /* We define here all the modules that the rest of the infraestructure, including the bots themselves can consume. */ @@ -193,7 +176,7 @@ switch (bot.startMode) { case 'Live': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Live Mode detected."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Live Mode detected."); } // This will be considered the process date and time, so as to have it consistenly all over the execution. @@ -218,7 +201,7 @@ } case 'Backtest': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Backtesting Mode detected."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Backtesting Mode detected."); } let timePeriod; @@ -234,7 +217,7 @@ if (bot.hasTheBotJustStarted === true) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Setting initial datetime."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Setting initial datetime."); } if (UI_COMMANDS.beginDatetime !== undefined) { @@ -280,9 +263,9 @@ if (bot.processDatetime.valueOf() > endDatetime.valueOf()) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> End of Backtesting Period reached. Exiting Bot Process Loop."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> End of Backtesting Period reached. Exiting Bot Process Loop."); } - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } @@ -291,7 +274,7 @@ } case 'Competition': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Competition Mode detected."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Competition Mode detected."); } let localDate = new Date(); @@ -314,7 +297,7 @@ if (bot.processDatetime.valueOf() < beginDatetime.valueOf()) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Competition not started yet. Wainting for the competition to start."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Competition not started yet. Wainting for the competition to start."); } nextWaitTime = 'Normal'; loopControl(nextWaitTime); @@ -325,9 +308,9 @@ if (bot.processDatetime.valueOf() > endDatetime.valueOf()) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> End of Competition Period reached. Exiting Bot Process Loop."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> End of Competition Period reached. Exiting Bot Process Loop."); } - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_OK_RESPONSE); return; } @@ -335,19 +318,19 @@ break; } default: { - logger.write("[ERROR] run -> loop -> Unexpected bot.startMode."); - logger.write("[ERROR] run -> loop -> bot.startMode = " + bot.startMode); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> Unexpected bot.startMode."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> bot.startMode = " + bot.startMode); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> bot.processDatetime = " + bot.processDatetime); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> bot.processDatetime = " + bot.processDatetime); } if (global.AT_BREAKPOINT === true) { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> Plot Breakpoint Hit."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> Plot Breakpoint Hit."); } } @@ -366,9 +349,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeStatusDependencies -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> Entering function."); } - statusDependencies = STATUS_DEPENDENCIES.newStatusDependencies(bot, DEBUG_MODULE, STATUS_REPORT, BLOB_STORAGE, UTILITIES); + statusDependencies = STATUS_DEPENDENCIES.newStatusDependencies(bot, logger, STATUS_REPORT, BLOB_STORAGE, UTILITIES); statusDependencies.initialize(processConfig.statusDependencies, undefined, undefined, onInizialized); @@ -376,46 +359,46 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeStatusDependencies -> onInizialized -> Execution finished well."); initializeDataDependencies(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeStatusDependencies -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeStatusDependencies -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -424,9 +407,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeDataDependencies -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeDataDependencies -> Entering function."); } - dataDependencies = DATA_DEPENDENCIES.newDataDependencies(bot, DEBUG_MODULE, DATA_SET, BLOB_STORAGE, UTILITIES); + dataDependencies = DATA_DEPENDENCIES.newDataDependencies(bot, logger, DATA_SET, BLOB_STORAGE, UTILITIES); dataDependencies.initialize(processConfig.dataDependencies, onInizialized); @@ -434,46 +417,46 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeDataDependencies -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeDataDependencies -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeDataDependencies -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeDataDependencies -> onInizialized -> Execution finished well."); initializeContext(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeDataDependencies -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeDataDependencies -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeDataDependencies -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -482,55 +465,55 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeContext -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeContext -> Entering function."); } - context = CONTEXT.newContext(bot, DEBUG_MODULE, BLOB_STORAGE, UTILITIES, STATUS_REPORT); + context = CONTEXT.newContext(bot, logger, BLOB_STORAGE, UTILITIES, STATUS_REPORT); context.initialize(statusDependencies, onInizialized); function onInizialized(err) { try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeContext -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeContext -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeContext -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeContext -> onInizialized -> Execution finished well."); initializeExchangeAPI(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeContext -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeContext -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeContext -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeContext -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeContext -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeContext -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -539,9 +522,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeExchangeAPI -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeExchangeAPI -> Entering function."); } - exchangeAPI = EXCHANGE_API.newExchangeAPI(bot, DEBUG_MODULE, POLONIEX_CLIENT_MODULE); + exchangeAPI = EXCHANGE_API.newExchangeAPI(bot, logger, POLONIEX_CLIENT_MODULE); exchangeAPI.initialize(onInizialized); @@ -549,46 +532,46 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeContext -> onInizialized -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeContext -> onInizialized -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeExchangeAPI -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeExchangeAPI -> onInizialized -> Execution finished well."); initializeAssistant(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeExchangeAPI -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeContext -> onInizialized -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeContext -> onInizialized -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeExchangeAPI -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeExchangeAPI -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -597,55 +580,55 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeAssistant -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeAssistant -> Entering function."); } - assistant = ASSISTANT.newAssistant(bot, DEBUG_MODULE, UTILITIES); + assistant = ASSISTANT.newAssistant(bot, logger, UTILITIES); assistant.initialize(context, exchangeAPI, dataDependencies, onInizialized); function onInizialized(err) { try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeAssistant -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeAssistant -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeAssistant -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeAssistant -> onInizialized -> Execution finished well."); initializeUserBot(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeAssistant -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeAssistant -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeAssistant -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeAssistant -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeAssistant -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -654,9 +637,9 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeUserBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> Entering function."); } - usertBot = USER_BOT_MODULE.newUserBot(bot, DEBUG_MODULE, COMMONS_MODULE); + usertBot = USER_BOT_MODULE.newUserBot(bot, logger, COMMONS_MODULE); usertBot.initialize(assistant, onInizialized); @@ -664,46 +647,46 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> initializeUserBot -> onInizialized -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> onInizialized -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> initializeUserBot -> onInizialized -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> initializeUserBot -> onInizialized -> Execution finished well."); startUserBot(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeUserBot -> onInizialized -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> onInizialized -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> initializeUserBot -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> initializeUserBot -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -712,7 +695,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> startUserBot -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> Entering function."); } usertBot.start(onFinished); @@ -720,46 +703,46 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> startUserBot -> onFinished -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> onFinished -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> startUserBot -> onFinished -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> startUserBot -> onFinished -> Execution finished well."); saveContext(); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Retry Later. Requesting Execution Retry."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Retry Later. Requesting Execution Retry."); nextWaitTime = 'Retry'; loopControl(nextWaitTime); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> startUserBot -> onFinished -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> onFinished -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> startUserBot -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> startUserBot -> err = " + err.message); + logger.persist(); callBackFunction(err); } } @@ -768,7 +751,7 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> saveContext -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> saveContext -> Entering function."); } context.saveThemAll(onFinished); @@ -776,196 +759,199 @@ try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loop -> saveContext -> onFinished -> Entering function."); } + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> saveContext -> onFinished -> Entering function."); } switch (err.result) { case global.DEFAULT_OK_RESPONSE.result: { - logger.write("[INFO] run -> loop -> saveContext -> onFinished -> Execution finished well."); + logger.write(MODULE_NAME, "[INFO] run -> loop -> saveContext -> onFinished -> Execution finished well."); nextWaitTime = 'Normal'; loopControl(nextWaitTime); return; } case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] run -> loop -> saveContext -> onFinished -> Can not retry at this point."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> saveContext -> onFinished -> Can not retry at this point."); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. - logger.write("[ERROR] run -> loop -> saveContext -> onFinished -> Operation Failed. Aborting the process."); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> saveContext -> onFinished -> Operation Failed. Aborting the process."); + logger.persist(); callBackFunction(err); return; } default: { - logger.write("[ERROR] run -> loop -> saveContext -> onFinished -> Unhandled err.result received. -> err.result = " + err.result); - logger.write("[ERROR] run -> loop -> saveContext -> onFinished -> Unhandled err.result received. -> err.message = " + err.message); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> saveContext -> onFinished -> Unhandled err.result received. -> err.result = " + err.result); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> saveContext -> onFinished -> Unhandled err.result received. -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.persist(); callBackFunction(global.DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { - logger.write("[ERROR] run -> loop -> saveContext -> onFinished -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> saveContext -> onFinished -> err = " + err.message); + logger.persist(); callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> loop -> saveContext -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> saveContext -> err = " + err.message); + logger.persist(); callBackFunction(err); } } + function loopControl(nextWaitTime) { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> nextWaitTime = " + nextWaitTime); } + + /* Here we check if we must stop the loop gracefully. */ + + shallWeStop(onStop, onContinue); + + function onStop() { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Stopping the Loop Gracefully. See you next time!"); } + logger.persist(); + callBackFunction(global.DEFAULT_OK_RESPONSE); + return; + + } + + function onContinue() { + + /* Trading bots are going to be executed after a configured period of time after the last execution ended. This is to avoid overlapping executions. */ + + switch (nextWaitTime) { + case 'Normal': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Normal -> Restarting Loop in " + (processConfig.normalWaitTime / 1000) + " seconds."); } + logger.persist(); + setTimeout(loop, processConfig.normalWaitTime); + } + break; + case 'Retry': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Retry -> Restarting Loop in " + (processConfig.retryWaitTime / 1000) + " seconds."); } + logger.persist(); + setTimeout(loop, processConfig.retryWaitTime); + } + break; + case 'Sleep': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Sleep -> Restarting Loop in " + (processConfig.sleepWaitTime / 60000) + " minutes."); } + logger.persist(); + setTimeout(loop, processConfig.sleepWaitTime); + } + break; + case 'Coma': { + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> loopControl -> Coma -> Restarting Loop in " + (processConfig.comaWaitTime / 3600000) + " hours."); } + logger.persist(); + setTimeout(loop, processConfig.comaWaitTime); + } + break; + } + } + } + + function shallWeStop(stopCallBack, continueCallBack) { + + try { + + /* IMPORTANT: This function is exactly the same on the 3 modules. */ + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> shallWeStop -> Entering function. "); } + + cloudStorage = BLOB_STORAGE.newBlobStorage(bot, logger); + + cloudStorage.initialize("AAPlatform", onInizialized); + + function onInizialized(err) { + + if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] run -> loop -> shallWeStop -> onInizialized -> Entering function."); } + + if (err.result === global.DEFAULT_OK_RESPONSE.result) { + + let filePath; + + switch (global.CURRENT_EXECUTION_AT) { // This is what determines if the bot is loaded from the devTeam or an endUser copy. + case "Cloud": { + filePath = global.DEV_TEAM + "/" + "AACloud"; // DevTeams bots only are run at the cloud. + break; + } + case "Browser": { + if (global.SHALL_BOT_STOP === false) { + continueCallBack(); + } else { + stopCallBack(); + } + break; + } + default: { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + + let fileName = "this.config.json"; + + cloudStorage.getTextFile(filePath, fileName, onFileReceived); + + function onFileReceived(err, text) { + + if (err.result !== global.DEFAULT_OK_RESPONSE.result) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onFileReceived -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + + try { + + let configRead = JSON.parse(text); + + if (configRead.stopGracefully === false && global.SHALL_BOT_STOP === false) { + continueCallBack(); + } else { + stopCallBack(); + } + + } catch (err) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> onFileReceived -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + } + } + } + catch (err) { + logger.write(MODULE_NAME, "[ERROR] run -> loop -> shallWeStop -> err.message = " + err.message); + logger.persist(); + clearInterval(intervalHandle); + callBackFunction(global.DEFAULT_FAIL_RESPONSE); + return; + } + } + } catch (err) { - logger.write("[ERROR] run -> loop -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - callBackFunction(err); - } - } - - function loopControl(nextWaitTime) { - - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> nextWaitTime = " + nextWaitTime); } - - /* Here we check if we must stop the loop gracefully. */ - - shallWeStop(onStop, onContinue); - - function onStop() { - - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Stopping the Loop Gracefully. See you next time!"); } - bot.eventHandler.raiseEvent("Close Log File"); - callBackFunction(global.DEFAULT_OK_RESPONSE); - return; - - } - - function onContinue() { - - /* Trading bots are going to be executed after a configured period of time after the last execution ended. This is to avoid overlapping executions. */ - - switch (nextWaitTime) { - case 'Normal': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Normal -> Restarting Loop in " + (processConfig.normalWaitTime / 1000) + " seconds."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.normalWaitTime); - } - break; - case 'Retry': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Retry -> Restarting Loop in " + (processConfig.retryWaitTime / 1000) + " seconds."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.retryWaitTime); - } - break; - case 'Sleep': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Sleep -> Restarting Loop in " + (processConfig.sleepWaitTime / 60000) + " minutes."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.sleepWaitTime); - } - break; - case 'Coma': { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> Coma -> Restarting Loop in " + (processConfig.comaWaitTime / 3600000) + " hours."); } - bot.eventHandler.raiseEvent("Close Log File"); - setTimeout(loop, processConfig.comaWaitTime); - } - break; - } - } - } - - function shallWeStop(stopCallBack, continueCallBack) { - - try { - if (FULL_LOG === true) { logger.write("[INFO] run -> loopControl -> shallWeStop -> Entering function. "); } - - cloudStorage = BLOB_STORAGE.newBlobStorage(bot); - - cloudStorage.initialize("AAPlatform", onInizialized); - - function onInizialized(err) { - - if (FULL_LOG === true) { logger.write("[INFO] initialize -> onInizialized -> Entering function."); } - - if (err.result === global.DEFAULT_OK_RESPONSE.result) { - - let filePath; - - switch (global.CURRENT_EXECUTION_AT) { // This is what determines if the bot is loaded from the devTeam or an endUser copy. - case "Cloud": { - filePath = global.DEV_TEAM + "/" + "AACloud"; // DevTeams bots only are run at the cloud. - break; - } - case "Browser": { - if (global.SHALL_BOT_STOP === false) { - continueCallBack(); - } else { - stopCallBack(); - } - break; - } - default: { - logger.write("[ERROR] shallWeStop -> onInizialized -> CURRENT_EXECUTION_AT must be either 'Cloud' or 'Browser'."); - logger.write("[ERROR] shallWeStop -> onInizialized -> global.CURRENT_EXECUTION_AT = " + global.CURRENT_EXECUTION_AT); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } - - let fileName = "this.config.json"; - - cloudStorage.getTextFile(filePath, fileName, onFileReceived); - - function onFileReceived(err, text) { - - if (err.result !== global.DEFAULT_OK_RESPONSE.result) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> onFileReceived -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - - try { - - let configRead = JSON.parse(text); - - if (configRead.stopGracefully === false && global.SHALL_BOT_STOP === false) { - continueCallBack(); - } else { - stopCallBack(); - } - - } catch (err) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> onFileReceived -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); - clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; - } - } - } - } - } - catch (err) { - logger.write("[ERROR] run -> loopControl -> shallWeStop -> err.message = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] run -> loop -> err = " + err.message); clearInterval(intervalHandle); - callBackFunction(global.DEFAULT_FAIL_RESPONSE); - return; + callBackFunction(err); } } } catch (err) { - logger.write("[ERROR] run -> err = " + err.message); - bot.eventHandler.raiseEvent("Close Log File"); + parentLogger.write(MODULE_NAME, "[ERROR] run -> err = " + err.message); + clearInterval(intervalHandle); callBackFunction(global.DEFAULT_FAIL_RESPONSE); } }