Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- // Licensed Materials - Property of IBM
- // (C) Copyright IBM Corp. 2017
- // All Rights Reserved
- // US Government Users Restricted Rights - Use, duplication or
- // disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
- */
- /*
- // Licensed Materials - Property of IBM
- // (C) Copyright IBM Corp. 2017
- // All Rights Reserved
- // US Government Users Restricted Rights - Use, duplication or
- // disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
- */
- var BFQuery = require('bfquery')(),
- debug = require('debug')('bf:appmonitor:debug'),
- warn = require('debug')('bf:appmonitor:warn'),
- fs = require('fs'),
- os = require('os'),
- path = require('path'),
- platform = require('./platform'),
- Q = require('q'),
- moment = require('moment'),
- envValidate = require('./env-validators'),
- _ = require('underscore');
- var DEFAULT_DEBUG_FILTER = 'bf*,-bf:database:debug',
- NEW_DEBUG_FILTER = 'bf*error,bf:bfetl:debug,bf:bfapp:debug,bf:appmonitor:debug,bf:datasync:initialize:debug',
- SERVER_INFO_PLATFORM_API = '/api/serverinfo', // used to pull dbtype
- BFENT_SUPPORTED_SINCE_PLATFORM_VERSION = '9.5.5.0', // TODO: Update this prior to release.
- NO_ETL_SUPPORTED_SINCE_PLATFORM_VERSION = '9999999', // TODO: Update this when Platform stops supporting ETL APIs
- DEPLOY_BASELINE_MIMEFIELD_SINCE_PLATFORM_VERSION = '9.5.4.25';
- /**
- * If APP_CA is not set, get it from the platform.
- */
- function initCACertificate() {
- if (process.env.APP_CA) {
- return;
- }
- debug('Requesting APP_CA from the platform.');
- function set(certificate) {
- process.env.APP_CA = certificate;
- }
- return platform.getInsecure('/api/webui-ca-certificate').then(set);
- }
- /**
- * If AUTH_KEY, AUTH_CERT, or AUTH_SERIAL are not set, get them from the
- * platform.
- */
- function initAuthCredentials() {
- if (process.env.AUTH_KEY &&
- process.env.AUTH_CERT &&
- process.env.AUTH_SERIAL) {
- return;
- }
- debug('Requesting AUTH_KEY, AUTH_CERT, and AUTH_SERIAL from the platform.');
- function set(credentials) {
- process.env.AUTH_KEY = credentials.key;
- process.env.AUTH_CERT = credentials.cert;
- process.env.AUTH_SERIAL = credentials.serial;
- }
- return platform.getWithUserPass('/api/webui-auth-credentials')
- .then(JSON.parse)
- .then(set);
- }
- /**
- * If APP_KEY or APP_CERT are not set, get them from the platform.
- */
- function initAppCredentials() {
- var body;
- if (process.env.APP_KEY && process.env.APP_CERT) {
- return;
- }
- debug('Requesting APP_KEY and APP_CERT from the platform.');
- body = JSON.stringify({
- name: 'service',
- host: 'localhost'
- });
- function set(credentials) {
- process.env.APP_KEY = credentials.key;
- process.env.APP_CERT = credentials.cert;
- }
- return platform.post('/api/webui-app-credentials', body)
- .then(JSON.parse)
- .then(set);
- }
- /**
- * If WEB_KEY or WEB_CERT are not set, either read them from disk or get them
- * from the platform.
- */
- function initWebCredentials() {
- if (process.env.WEB_KEY && process.env.WEB_CERT) {
- return;
- }
- function readKeyFile() {
- return Q.nfcall(fs.readFile, process.env.WEB_KEY_FILE);
- }
- function setKey(contents) {
- process.env.WEB_KEY = contents;
- }
- function readCertFile() {
- return Q.nfcall(fs.readFile, process.env.WEB_CERT_FILE);
- }
- function setCert(contents) {
- process.env.WEB_CERT = contents;
- }
- function set(credentials) {
- process.env.WEB_KEY = credentials.key;
- process.env.WEB_CERT = credentials.cert;
- }
- if (process.env.WEB_KEY_FILE && process.env.WEB_CERT_FILE) {
- debug('Reading WEB_KEY_FILE and WEB_CERT_FILE from disk.');
- return readKeyFile().then(setKey).then(readCertFile).then(setCert);
- }
- debug('Requesting WEB_KEY and WEB_CERT from the platform.');
- return platform.get('/api/webui-web-credentials').then(JSON.parse).then(set);
- }
- function initDatabaseConfiguration() {
- var msConfig = { 'database': 'BFEnterprise', 'parseJSON': true, 'port': 1433 },
- db2Config = { 'database': 'BFENT', 'schema': 'DBO', 'currentSchema': 'DBO', 'protocol': 'tcpip', 'port': 50000 };
- // Read in db_config.json file from WebUI root directory
- function readConfigFile() {
- return Q.nfcall(fs.readFile, path.join(process.env.WebUI_DIR, 'WebUI', 'db_config.json'))
- .then(function(configData) {
- return JSON.parse(configData);
- })
- .fail(function(err) {
- if (err && err.code === 'ENOENT') {
- throw new Error('Unable to locate db_config.json, please run BES Support Fixlet #2687');
- } else {
- throw new Error('Failed to parse db_config.json, please ensure that it has been formatted correctly. Error: ' + err.message);
- }
- });
- }
- // Set dbType according to Client Settings and Platform API availability
- function processServerInfo(serverInfo) {
- // check for servertime drift
- if (serverInfo.currentTime) {
- var currentUTCTime = moment.utc();
- var platformUTCTime = moment.utc(new Date(serverInfo.currentTime).toISOString());
- var driftMinutes = Math.abs(platformUTCTime.diff(currentUTCTime, 'minutes'));
- if (driftMinutes > process.env.SERVER_TIME_DRIFT_THRESHOLD_MINUTES ) {
- warn('*WARNING* BigFix server\'s local time (' + platformUTCTime.format('LLLL') + ' ) has drifted significantly from the WebUI server\'s local time (' + currentUTCTime.format('LLLL') + '). That\'s ' + driftMinutes + ' minutes in excess of the ' + process.env.SERVER_TIME_DRIFT_THRESHOLD_MINUTES + ' minute threshold setting SERVER_TIME_DRIFT_THRESHOLD_MINUTES.');
- }
- }
- //check platform version is compatible
- if ((process.env.USE_BFENT === '1' && serverInfo && serverInfo.version >= BFENT_SUPPORTED_SINCE_PLATFORM_VERSION) ||
- (serverInfo && serverInfo.version >= NO_ETL_SUPPORTED_SINCE_PLATFORM_VERSION)) {
- // extract dbtype from server info
- process.env.NoETL = '1';
- if (serverInfo.dbType === 'SQL Server') {
- process.env.dbtype = 'MSSQL';
- } else if (serverInfo.dbType === 'DB2') {
- process.env.dbtype = 'DB2';
- } else {
- throw new Error('OS not supported');
- }
- } else {
- process.env.NoETL = '0';
- process.env.dbtype = 'SQLITE'; // default to sqlite
- }
- if (serverInfo && serverInfo.version >= DEPLOY_BASELINE_MIMEFIELD_SINCE_PLATFORM_VERSION) {
- process.env.OkDeployBaselineWithMIMEField = true;
- } else {
- process.env.OkDeployBaselineWithMIMEField = false;
- }
- if (serverInfo) {
- if (serverInfo.version) {
- process.env.PLATFORM_VERSION = serverInfo.version;
- }
- if (serverInfo.dbSchemaVersion) {
- process.env.PLATFORM_SCHEMA = serverInfo.dbSchemaVersion;
- }
- }
- debug('dbtype set to: ', process.env.dbtype);
- }
- // Retrieve server information from platform
- function getDatabaseType() {
- return BFQuery.get(SERVER_INFO_PLATFORM_API)
- .then(JSON.parse)
- .fail(function() {
- debug('Unable to retrieve Platform server information, defaulting to SQLite');
- return false;
- })
- .then(processServerInfo);
- }
- // Set DB2 config values in process.env
- function parseDB2(config) {
- db2Config.uid = config.user;
- db2Config.pwd = config.password;
- db2Config.hostname = config.hostname;
- db2Config.database = config.database ? config.database : db2Config.database;
- db2Config.port = config.port ? config.port : db2Config.port;
- if (config.noEncrypt === true) { db2Config.noEncrypt = true; }
- process.env.DB2_CONFIG = JSON.stringify(db2Config);
- }
- // Set MSSQL config values in process.env
- function parseMSSQL(config) {
- msConfig.user = config.user;
- msConfig.password = config.password;
- msConfig.server = config.hostname;
- msConfig.database = config.database ? config.database : msConfig.database;
- msConfig.port = config.port ? config.port : msConfig.port;
- msConfig.options = {
- encrypt: true
- };
- if (config.domain) { msConfig.domain = config.domain.toUpperCase(); }
- if (config.noEncrypt === true) { msConfig.noEncrypt = true; }
- process.env.MSSQL_CONFIG = JSON.stringify(msConfig);
- }
- // Verify db_config.json has the required fields set
- //TODO: update to work with NT Auth when available
- function verifyConfig(config) {
- var required = ['user', 'password', 'hostname'];
- var missing = [];
- _.each(required, function(field) {
- if (!config[field]) {
- missing.push(field);
- }
- });
- if (missing.length > 0) {
- throw new Error('db_config.json missing the following field(s): ' + missing.join(', '));
- }
- }
- // Parse db_config.json
- function parseConfig(config) {
- verifyConfig(config);
- if (process.env.dbtype === 'MSSQL') {
- parseMSSQL(config);
- } else if (process.env.dbtype === 'DB2') {
- parseDB2(config);
- }
- }
- return getDatabaseType().then(function() {
- if (process.env.MSSQL_CONFIG || process.env.DB2_CONFIG || process.env.dbtype === 'SQLITE') {
- return; // This should only be hit when running in dev environment or when using SQLite
- } else {
- return readConfigFile().then(parseConfig);
- }
- });
- }
- /**
- * Initialize the application monitor's environment variables.
- */
- function initEnvironment() {
- var defaults = {
- APP_PORT: '5000',
- INT_PORT: '5001',
- APP_PORT_MIN: '5002',
- APP_PORT_MAX: '6000',
- APP_RESTART_DELAY_SECONDS: '1',
- APP_UPDATE_DELAY_DAYS: '0',
- APP_UPDATE_ENABLE_AUTO: '1',
- ETL_DIR: path.resolve('.'),
- LOGIN_SESSION_TIMEOUT_SECONDS: '900',
- PLATFORM_HOST: 'localhost',
- PLATFORM_PORT: '52315',
- WEB_PORT: '3000',
- WORK_DIR: path.join(os.tmpdir(), 'bfappmonitor_tmp'),
- WORK_DELAY_SECONDS: '60',
- SAML_AUTHNCONTEXT: 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport',
- CACHE_TTL: '600',
- LOGIN_CACHE_TTL_HOURS: '86400',
- SERVER_TIME_DRIFT_THRESHOLD_MINUTES: Math.min(process.env.LOGIN_SESSION_TIMEOUT_SECONDS ? Math.abs((parseInt(process.env.LOGIN_SESSION_TIMEOUT_SECONDS) / 60) - 5) : Number.MAX_SAFE_INTEGER, 5)
- };
- Object.keys(defaults).forEach(function(variable) {
- if (!process.env[variable]) {
- process.env[variable] = defaults[variable];
- } else {
- process.env[variable] = envValidate[variable] ? envValidate[variable](variable, process.env[variable], defaults[variable]) : process.env[variable];
- }
- });
- if (process.env.DEBUG === DEFAULT_DEBUG_FILTER) {
- process.env.DEBUG = NEW_DEBUG_FILTER;
- }
- return Q()
- .then(initCACertificate)
- .then(initAuthCredentials)
- .then(initAppCredentials)
- .then(initWebCredentials)
- .then(initDatabaseConfiguration);
- }
- module.exports = initEnvironment;
Add Comment
Please, Sign In to add comment