Skip to content

Commit

Permalink
[OGUI-1535] Use LogManager instead of Log (#2506)
Browse files Browse the repository at this point in the history
* [O2B-1535] Use LogManager instead of Log
  • Loading branch information
martinboulais authored Jul 27, 2024
1 parent 5036eb1 commit f2d5eb9
Show file tree
Hide file tree
Showing 41 changed files with 233 additions and 224 deletions.
21 changes: 11 additions & 10 deletions Control/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
*/

const log = new (require('@aliceo2/web-ui').Log)(`${process.env.npm_config_log_label ?? 'cog'}/api`);
const logger = (require('@aliceo2/web-ui').LogManager)
.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/api`);
const config = require('./config/configProvider.js');

// middleware
Expand Down Expand Up @@ -63,7 +64,7 @@ if (!config.apricot) {
throw new Error('Apricot gRPC Configuration is missing');
}
if (!config.grafana) {
log.error('Grafana Configuration is missing');
logger.error('Grafana Configuration is missing');
}

module.exports.setup = (http, ws) => {
Expand Down Expand Up @@ -113,7 +114,7 @@ module.exports.setup = (http, ws) => {
}

const statusService = new StatusService(
config, ctrlService, consulService, apricotService, notificationService, wsService
config, ctrlService, consulService, apricotService, notificationService, wsService,
);
const statusController = new StatusController(statusService);

Expand All @@ -127,7 +128,7 @@ module.exports.setup = (http, ws) => {
];

ctrlProxy.methods.forEach(
(method) => http.post(`/${method}`, coreMiddleware, (req, res) => ctrlService.executeCommand(req, res))
(method) => http.post(`/${method}`, coreMiddleware, (req, res) => ctrlService.executeCommand(req, res)),
);
http.post('/core/request', coreMiddleware, (req, res) => aliecsReqHandler.add(req, res));
http.get('/core/requests', coreMiddleware, (req, res) => aliecsReqHandler.getAll(req, res));
Expand All @@ -138,7 +139,7 @@ module.exports.setup = (http, ws) => {
http.get('/workflow/configuration', workflowController.getWorkflowConfiguration.bind(workflowController));

http.get('/runs/calibration/config', [
minimumRoleMiddleware(Role.GLOBAL)
minimumRoleMiddleware(Role.GLOBAL),
], runController.refreshCalibrationRunsConfigurationHandler.bind(runController));

http.get('/runs/calibration', runController.getCalibrationRunsHandler.bind(runController));
Expand All @@ -150,15 +151,15 @@ module.exports.setup = (http, ws) => {
coreMiddleware,
minimumRoleMiddleware(Role.DETECTOR),
lockOwnershipMiddleware(lockService, envService),
envCtrl.destroyEnvironmentHandler.bind(envCtrl)
envCtrl.destroyEnvironmentHandler.bind(envCtrl),
);

http.get('/core/environments', coreMiddleware, (req, res) => envCache.get(req, res), {public: true});
http.post('/core/environments/configuration/save', (req, res) => apricotService.saveCoreEnvConfig(req, res));
http.post('/core/environments/configuration/update', (req, res) => apricotService.updateCoreEnvConfig(req, res));

apricotProxy.methods.forEach(
(method) => http.post(`/${method}`, (req, res) => apricotService.executeCommand(req, res))
(method) => http.post(`/${method}`, (req, res) => apricotService.executeCommand(req, res)),
);
http.get('/core/detectors', (req, res) => apricotService.getDetectorList(req, res));
http.get('/core/hostsByDetectors', (req, res) => apricotService.getHostsByDetectorList(req, res));
Expand All @@ -182,7 +183,7 @@ module.exports.setup = (http, ws) => {
http.get('/status/core', coreMiddleware[0], statusController.getAliECSStatus.bind(statusController));
http.get('/status/system', statusController.getSystemCompatibility.bind(statusController));
http.get('/status/core/services', coreMiddleware[0],
statusController.getAliECSIntegratedServicesStatus.bind(statusController)
statusController.getAliECSIntegratedServicesStatus.bind(statusController),
);

// Consul
Expand Down Expand Up @@ -218,7 +219,7 @@ function initializeIntervals(intervalsService, statusService, runService, bkpSer
if (config.bookkeeping) {
intervalsService.register(
runService.retrieveCalibrationRunsGroupedByDetector.bind(runService),
CALIBRATION_RUNS_REFRESH_RATE
CALIBRATION_RUNS_REFRESH_RATE,
);
}
}
Expand Down
10 changes: 5 additions & 5 deletions Control/lib/config/configProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
* or submit itself to any jurisdiction.
*/

const {Log} = require('@aliceo2/web-ui');
const log = new Log(`${process.env.npm_config_log_label ?? 'cog'}/config`);
const {LogManager} = require('@aliceo2/web-ui');
const logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/config`);

const fs = require('fs');
const path = require('path');
Expand All @@ -34,12 +34,12 @@ if (process.argv.length >= 3 && /\.js$/.test(process.argv[2])) {
try {
configFile = fs.realpathSync(configFile);
} catch (err) {
log.error(`Unable to read config file: ${err.message}`);
logger.errorMessage(`Unable to read config file: ${err.message}`);
process.exit(1);
}

const config = require(configFile);
Log.configure(config.logging);
log.info(`Read config file "${configFile}"`);
LogManager.configure(config.logging);
logger.infoMessage(`Read config file "${configFile}"`);

module.exports = config;
25 changes: 13 additions & 12 deletions Control/lib/control-core/ApricotService.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
*/

const assert = require('assert');
const log = new (require('@aliceo2/web-ui').Log)(`${process.env.npm_config_log_label ?? 'cog'}/apricotservice`);
const logger = (require('@aliceo2/web-ui').LogManager)
.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/apricotservice`);
const {errorHandler, errorLogger} = require('./../utils.js');
const CoreEnvConfig = require('../dtos/CoreEnvConfig.js');
const CoreUtils = require('./CoreUtils.js');
Expand Down Expand Up @@ -45,7 +46,7 @@ class ApricotService {
async init() {
try {
this.detectors = (await this.apricotProxy['ListDetectors']()).detectors;
log.infoMessage(`Initial data retrieved from AliECS/Apricot: ${this.detectors} detectors`, {
logger.infoMessage(`Initial data retrieved from AliECS/Apricot: ${this.detectors} detectors`, {
level: 99,
system: 'GUI',
facility: 'cog/api'
Expand All @@ -56,18 +57,18 @@ class ApricotService {
const {hosts} = await this.apricotProxy['GetHostInventory']({detector});
this.hostsByDetector.set(detector, hosts);
} catch (error) {
log.error(`Unable to retrieve list of hosts for detector: ${detector}`);
logger.error(`Unable to retrieve list of hosts for detector: ${detector}`);
}
})
);
} catch (error) {
log.error('Unable to list detectors');
logger.error('Unable to list detectors');
}
}

/**
* Use Apricot defined `o2apricot.proto` `GetRuntimeEntry` to retrieve the value stored in a specified key
*
*
* Corner cases for Apricot returns:
* * if key(component) does not exist, Apricot wrongly returns code 2 instead of 5 in the gRPC error;
* * if key exists but there is no content, Apricot returns '{}'
Expand Down Expand Up @@ -124,8 +125,8 @@ class ApricotService {
const {hosts} = await this.apricotProxy['GetHostInventory']({detector});
this.hostsByDetector.set(detector, hosts);
} catch (error) {
log.error(`Unable to retrieve list of hosts for detector: ${detector}`);
log.error(error);
logger.error(`Unable to retrieve list of hosts for detector: ${detector}`);
logger.error(error);
}
})
);
Expand All @@ -138,7 +139,7 @@ class ApricotService {
}

/**
* Request a list of detectors from Apricot to confirm
* Request a list of detectors from Apricot to confirm
* connection and O2Apricot are up
* @return {Promise}
*/
Expand All @@ -150,7 +151,7 @@ class ApricotService {
throw new Error('Unable to check status of Apricot')
}
} catch (error) {
log.error(error);
logger.error(error);
throw error;
}
}
Expand All @@ -165,7 +166,7 @@ class ApricotService {
if (this.apricotProxy?.isConnectionReady && method) {
if (!method.startsWith('Get')) {
const type = req.body.type ? ` (${req.body.type})` : '';
log.info(`${req.session.personid} => ${method} ${type}`, 6);
logger.info(`${req.session.personid} => ${method} ${type}`, 6);
}
this.apricotProxy[method](req.body)
.then((response) => res.json(response))
Expand Down Expand Up @@ -198,7 +199,7 @@ class ApricotService {
errorHandler(`A configuration with name '${envConf.id}' already exists. `
+ 'Please load existing configuration and use \'Update\'', res, 409, 'apricotservice');
} else {
log.infoMessage(
logger.infoMessage(
`${req.session.username} request to save new core environment configuration "${envConf.id}"`,
{level: LOG_LEVEL.OPERATIONS, system: 'GUI', facility: LOG_FACILITY}
);
Expand Down Expand Up @@ -228,7 +229,7 @@ class ApricotService {
const envConf = CoreEnvConfig.fromJSON(data);

const envConfigToSave = await this._getUpdatedConfigIfExists(envConf, user);
log.infoMessage(
logger.infoMessage(
`${req.session.username} requested to update new core environment configuration "${envConf.id}"`,
{level: LOG_LEVEL.OPERATIONS, system: 'GUI', facility: LOG_FACILITY}
);
Expand Down
16 changes: 8 additions & 8 deletions Control/lib/control-core/ControlService.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

const assert = require('assert');
const path = require('path');
const {WebSocketMessage, Log} = require('@aliceo2/web-ui');
const log = new Log(`${process.env.npm_config_log_label ?? 'cog'}/controlservice`);
const {WebSocketMessage, LogManager} = require('@aliceo2/web-ui');
const logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/controlservice`);
const {errorHandler, errorLogger} = require('./../utils.js');
const CoreUtils = require('./CoreUtils.js');
const {LOG_LEVEL} = require('../common/logLevel.enum.js');
Expand Down Expand Up @@ -43,7 +43,7 @@ class ControlService {

/**
* Set websocket after server initialization
* @param {WebSocket} webSocket
* @param {WebSocket} webSocket
*/
setWS(webSocket) {
this.webSocket = webSocket;
Expand All @@ -60,7 +60,7 @@ class ControlService {
await this.ctrlProx['GetEnvironments']({}, {deadline: Date.now() + 9000});
} catch (err) {
const stateCode = this.ctrlProx.client.getChannel().getConnectivityState();
log.errorMessage(`Unable to reach AliECS (state: ${stateCode}), attempting reconnection`, {
logger.errorMessage(`Unable to reach AliECS (state: ${stateCode}), attempting reconnection`, {
level: 20,
system: 'GUI',
facility: 'cog/controlservice'
Expand All @@ -78,7 +78,7 @@ class ControlService {
* Current supported auto environments:
* * resources-cleanup: will execute for all existing hosts
* * o2-roc-config: will execute only for passed hosts
* *
* *
* @param {Request} req
* @param {Response} res
*/
Expand Down Expand Up @@ -126,7 +126,7 @@ class ControlService {
vars,
workflowTemplate: path.join(repositoryName, `workflows/${operation}@${defaultRevision}`),
};
log.infoMessage(`Request of user: ${req.session.username} to "${operation}" for ${channelId}`, {
logger.infoMessage(`Request of user: ${req.session.username} to "${operation}" for ${channelId}`, {
level: LOG_LEVEL.OPERATIONS, system: 'GUI', facility: 'cog/controlservice'
});
await this.ctrlProx[method](coreConf);
Expand Down Expand Up @@ -221,7 +221,7 @@ class ControlService {
const personid = req?.session?.personid ?? '';
if (method.startsWith('New') || method.startsWith('CleanupTasks')) {
const operation = req.body.operation ? ` (${req.body.operation})` : '';
log.infoMessage(`${username}(${personid}) => ${method} ${operation}`, {
logger.infoMessage(`${username}(${personid}) => ${method} ${operation}`, {
level: 1, facility: 'cog/controlservice'
});
} else if (method.startsWith('Control') || method.startsWith('Destroy')) {
Expand All @@ -230,7 +230,7 @@ class ControlService {
const run = req.body.runNumber;
delete req.body.runNumber;

log.infoMessage(`${username}(${personid}) => ${method} ${type}`, {
logger.infoMessage(`${username}(${personid}) => ${method} ${type}`, {
level: 1, facility: 'cog/controlservice', partition, run
});
}
Expand Down
10 changes: 5 additions & 5 deletions Control/lib/control-core/EnvCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
* or submit itself to any jurisdiction.
*/

const {WebSocketMessage, Log} = require('@aliceo2/web-ui');
const log = new Log(`${process.env.npm_config_log_label ?? 'cog'}/envcache`);
const {WebSocketMessage, LogManager} = require('@aliceo2/web-ui');
const logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/envcache`);
const assert = require('assert');

/**
Expand Down Expand Up @@ -43,7 +43,7 @@ class EnvCache {
if (new Date() - this.cacheEvictionLast > this.cacheEvictionTimeout) {
this.cache = {};
this.cacheEvictionLast = new Date();
log.info('Cache evicted');
logger.info('Cache evicted');
}
}

Expand Down Expand Up @@ -96,7 +96,7 @@ class EnvCache {
}
this._updateCache(envs);
} catch (error) {
log.debug(error);
logger.debug(error);
}
this.evictCache();
}
Expand All @@ -110,7 +110,7 @@ class EnvCache {
if (!this._cacheInSync(envs)) {
this.cache = envs;
this.webSocket?.broadcast(new WebSocketMessage().setCommand('environments').setPayload(this.cache));
log.debug('Updated cache');
logger.debug('Updated cache');
}
this.cacheEvictionLast = new Date();
}
Expand Down
25 changes: 13 additions & 12 deletions Control/lib/control-core/GrpcProxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ const path = require('path');
const {grpcErrorToNativeError} = require('./../errors/grpcErrorToNativeError.js');
const {Status} = require(path.join(__dirname, './../../protobuf/status_pb.js'));
const {EnvironmentInfo} = require(path.join(__dirname, './../../protobuf/environmentinfo_pb.js'));
const log = new (require('@aliceo2/web-ui').Log)(`${process.env.npm_config_log_label ?? 'cog'}/grpcproxy`);
const logger = (require('@aliceo2/web-ui').LogManager)
.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/grpcproxy`);

/**
* Encapsulate gRPC calls
Expand Down Expand Up @@ -63,7 +64,7 @@ class GrpcProxy {
* Definition of each call that can be made based on the proto file definition
* @param {JSON} args - arguments to be passed to gRPC Server
* @param {JSON} options - metadata for gRPC call such as deadline
* @returns
* @returns
*/
this[methodName] = (args = {}, options = {deadline: Date.now() + this._timeout}) => {
return new Promise((resolve, reject) => {
Expand All @@ -81,7 +82,7 @@ class GrpcProxy {
}
reject(error);
} catch (exception) {
log.debug('Failed new env details error' + exception);
logger.debug('Failed new env details error' + exception);
reject(exception);
}
reject(grpcErrorToNativeError(error));
Expand All @@ -102,23 +103,23 @@ class GrpcProxy {
_isConfigurationValid(config, path) {
let isValid = true;
if (!config.hostname) {
log.error('Missing configuration: hostname');
logger.error('Missing configuration: hostname');
isValid = false;
}
if (!config.port) {
log.error('Missing configuration: port');
logger.error('Missing configuration: port');
isValid = false;
}
if (!path) {
log.error('Missing path for gRPC API declaration');
logger.error('Missing path for gRPC API declaration');
isValid = false;
}
if (!config.label) {
log.error('Missing service label for gRPC API');
logger.error('Missing service label for gRPC API');
isValid = false;
}
if (!config.package) {
log.error('Missing service label for gRPC API');
logger.error('Missing service label for gRPC API');
isValid = false;
}
this._label = config.label;
Expand All @@ -134,19 +135,19 @@ class GrpcProxy {
}

/**
*
*
* @param {Error} error - error following attempt to connect to gRPC server
* @param {string} address - address on which connection was attempted
*/
_logConnectionResponse(error, address) {
if (error) {
log.error(`Connection to ${this._label} server (${address}) timeout`);
log.error(error.message);
logger.error(`Connection to ${this._label} server (${address}) timeout`);
logger.error(error.message);

this.connectionError = error;
this.isConnectionReady = false;
} else {
log.info(`${this._label} gRPC connected to ${address}`);
logger.info(`${this._label} gRPC connected to ${address}`);
this.connectionError = null;
this.isConnectionReady = true;
}
Expand Down
Loading

0 comments on commit f2d5eb9

Please sign in to comment.