Guest User

Untitled

a guest
Mar 25th, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.43 KB | None | 0 0
  1. /*
  2. // Licensed Materials - Property of IBM
  3. // (C) Copyright IBM Corp. 2017
  4. // All Rights Reserved
  5. // US Government Users Restricted Rights - Use, duplication or
  6. // disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  7. */
  8.  
  9. /*
  10. // Licensed Materials - Property of IBM
  11. // (C) Copyright IBM Corp. 2017
  12. // All Rights Reserved
  13. // US Government Users Restricted Rights - Use, duplication or
  14. // disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  15. */
  16.  
  17. var BFQuery = require('bfquery')(),
  18. debug = require('debug')('bf:appmonitor:debug'),
  19. warn = require('debug')('bf:appmonitor:warn'),
  20. fs = require('fs'),
  21. os = require('os'),
  22. path = require('path'),
  23. platform = require('./platform'),
  24. Q = require('q'),
  25. moment = require('moment'),
  26. envValidate = require('./env-validators'),
  27. _ = require('underscore');
  28.  
  29. var DEFAULT_DEBUG_FILTER = 'bf*,-bf:database:debug',
  30. NEW_DEBUG_FILTER = 'bf*error,bf:bfetl:debug,bf:bfapp:debug,bf:appmonitor:debug,bf:datasync:initialize:debug',
  31. SERVER_INFO_PLATFORM_API = '/api/serverinfo', // used to pull dbtype
  32. BFENT_SUPPORTED_SINCE_PLATFORM_VERSION = '9.5.5.0', // TODO: Update this prior to release.
  33. NO_ETL_SUPPORTED_SINCE_PLATFORM_VERSION = '9999999', // TODO: Update this when Platform stops supporting ETL APIs
  34. DEPLOY_BASELINE_MIMEFIELD_SINCE_PLATFORM_VERSION = '9.5.4.25';
  35.  
  36. /**
  37. * If APP_CA is not set, get it from the platform.
  38. */
  39. function initCACertificate() {
  40. if (process.env.APP_CA) {
  41. return;
  42. }
  43.  
  44. debug('Requesting APP_CA from the platform.');
  45.  
  46. function set(certificate) {
  47. process.env.APP_CA = certificate;
  48. }
  49.  
  50. return platform.getInsecure('/api/webui-ca-certificate').then(set);
  51. }
  52.  
  53. /**
  54. * If AUTH_KEY, AUTH_CERT, or AUTH_SERIAL are not set, get them from the
  55. * platform.
  56. */
  57. function initAuthCredentials() {
  58. if (process.env.AUTH_KEY &&
  59. process.env.AUTH_CERT &&
  60. process.env.AUTH_SERIAL) {
  61. return;
  62. }
  63.  
  64. debug('Requesting AUTH_KEY, AUTH_CERT, and AUTH_SERIAL from the platform.');
  65.  
  66. function set(credentials) {
  67. process.env.AUTH_KEY = credentials.key;
  68. process.env.AUTH_CERT = credentials.cert;
  69. process.env.AUTH_SERIAL = credentials.serial;
  70. }
  71.  
  72. return platform.getWithUserPass('/api/webui-auth-credentials')
  73. .then(JSON.parse)
  74. .then(set);
  75. }
  76.  
  77. /**
  78. * If APP_KEY or APP_CERT are not set, get them from the platform.
  79. */
  80. function initAppCredentials() {
  81. var body;
  82.  
  83. if (process.env.APP_KEY && process.env.APP_CERT) {
  84. return;
  85. }
  86.  
  87. debug('Requesting APP_KEY and APP_CERT from the platform.');
  88.  
  89. body = JSON.stringify({
  90. name: 'service',
  91. host: 'localhost'
  92. });
  93.  
  94. function set(credentials) {
  95. process.env.APP_KEY = credentials.key;
  96. process.env.APP_CERT = credentials.cert;
  97. }
  98.  
  99. return platform.post('/api/webui-app-credentials', body)
  100. .then(JSON.parse)
  101. .then(set);
  102. }
  103.  
  104. /**
  105. * If WEB_KEY or WEB_CERT are not set, either read them from disk or get them
  106. * from the platform.
  107. */
  108. function initWebCredentials() {
  109. if (process.env.WEB_KEY && process.env.WEB_CERT) {
  110. return;
  111. }
  112.  
  113. function readKeyFile() {
  114. return Q.nfcall(fs.readFile, process.env.WEB_KEY_FILE);
  115. }
  116.  
  117. function setKey(contents) {
  118. process.env.WEB_KEY = contents;
  119. }
  120.  
  121. function readCertFile() {
  122. return Q.nfcall(fs.readFile, process.env.WEB_CERT_FILE);
  123. }
  124.  
  125. function setCert(contents) {
  126. process.env.WEB_CERT = contents;
  127. }
  128.  
  129. function set(credentials) {
  130. process.env.WEB_KEY = credentials.key;
  131. process.env.WEB_CERT = credentials.cert;
  132. }
  133.  
  134. if (process.env.WEB_KEY_FILE && process.env.WEB_CERT_FILE) {
  135. debug('Reading WEB_KEY_FILE and WEB_CERT_FILE from disk.');
  136. return readKeyFile().then(setKey).then(readCertFile).then(setCert);
  137. }
  138.  
  139. debug('Requesting WEB_KEY and WEB_CERT from the platform.');
  140. return platform.get('/api/webui-web-credentials').then(JSON.parse).then(set);
  141. }
  142.  
  143. function initDatabaseConfiguration() {
  144.  
  145. var msConfig = { 'database': 'BFEnterprise', 'parseJSON': true, 'port': 1433 },
  146. db2Config = { 'database': 'BFENT', 'schema': 'DBO', 'currentSchema': 'DBO', 'protocol': 'tcpip', 'port': 50000 };
  147.  
  148. // Read in db_config.json file from WebUI root directory
  149. function readConfigFile() {
  150. return Q.nfcall(fs.readFile, path.join(process.env.WebUI_DIR, 'WebUI', 'db_config.json'))
  151. .then(function(configData) {
  152. return JSON.parse(configData);
  153. })
  154. .fail(function(err) {
  155. if (err && err.code === 'ENOENT') {
  156. throw new Error('Unable to locate db_config.json, please run BES Support Fixlet #2687');
  157. } else {
  158. throw new Error('Failed to parse db_config.json, please ensure that it has been formatted correctly. Error: ' + err.message);
  159. }
  160. });
  161. }
  162.  
  163. // Set dbType according to Client Settings and Platform API availability
  164. function processServerInfo(serverInfo) {
  165.  
  166. // check for servertime drift
  167. if (serverInfo.currentTime) {
  168. var currentUTCTime = moment.utc();
  169. var platformUTCTime = moment.utc(new Date(serverInfo.currentTime).toISOString());
  170. var driftMinutes = Math.abs(platformUTCTime.diff(currentUTCTime, 'minutes'));
  171.  
  172. if (driftMinutes > process.env.SERVER_TIME_DRIFT_THRESHOLD_MINUTES ) {
  173. 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.');
  174. }
  175. }
  176.  
  177. //check platform version is compatible
  178. if ((process.env.USE_BFENT === '1' && serverInfo && serverInfo.version >= BFENT_SUPPORTED_SINCE_PLATFORM_VERSION) ||
  179. (serverInfo && serverInfo.version >= NO_ETL_SUPPORTED_SINCE_PLATFORM_VERSION)) {
  180. // extract dbtype from server info
  181. process.env.NoETL = '1';
  182. if (serverInfo.dbType === 'SQL Server') {
  183. process.env.dbtype = 'MSSQL';
  184. } else if (serverInfo.dbType === 'DB2') {
  185. process.env.dbtype = 'DB2';
  186. } else {
  187. throw new Error('OS not supported');
  188. }
  189. } else {
  190. process.env.NoETL = '0';
  191. process.env.dbtype = 'SQLITE'; // default to sqlite
  192. }
  193.  
  194. if (serverInfo && serverInfo.version >= DEPLOY_BASELINE_MIMEFIELD_SINCE_PLATFORM_VERSION) {
  195. process.env.OkDeployBaselineWithMIMEField = true;
  196. } else {
  197. process.env.OkDeployBaselineWithMIMEField = false;
  198. }
  199.  
  200. if (serverInfo) {
  201. if (serverInfo.version) {
  202. process.env.PLATFORM_VERSION = serverInfo.version;
  203. }
  204. if (serverInfo.dbSchemaVersion) {
  205. process.env.PLATFORM_SCHEMA = serverInfo.dbSchemaVersion;
  206. }
  207. }
  208.  
  209. debug('dbtype set to: ', process.env.dbtype);
  210. }
  211.  
  212. // Retrieve server information from platform
  213. function getDatabaseType() {
  214. return BFQuery.get(SERVER_INFO_PLATFORM_API)
  215. .then(JSON.parse)
  216. .fail(function() {
  217. debug('Unable to retrieve Platform server information, defaulting to SQLite');
  218. return false;
  219. })
  220. .then(processServerInfo);
  221. }
  222.  
  223. // Set DB2 config values in process.env
  224. function parseDB2(config) {
  225. db2Config.uid = config.user;
  226. db2Config.pwd = config.password;
  227. db2Config.hostname = config.hostname;
  228. db2Config.database = config.database ? config.database : db2Config.database;
  229. db2Config.port = config.port ? config.port : db2Config.port;
  230. if (config.noEncrypt === true) { db2Config.noEncrypt = true; }
  231. process.env.DB2_CONFIG = JSON.stringify(db2Config);
  232. }
  233.  
  234. // Set MSSQL config values in process.env
  235. function parseMSSQL(config) {
  236. msConfig.user = config.user;
  237. msConfig.password = config.password;
  238. msConfig.server = config.hostname;
  239. msConfig.database = config.database ? config.database : msConfig.database;
  240. msConfig.port = config.port ? config.port : msConfig.port;
  241. msConfig.options = {
  242. encrypt: true
  243. };
  244. if (config.domain) { msConfig.domain = config.domain.toUpperCase(); }
  245. if (config.noEncrypt === true) { msConfig.noEncrypt = true; }
  246. process.env.MSSQL_CONFIG = JSON.stringify(msConfig);
  247. }
  248.  
  249. // Verify db_config.json has the required fields set
  250. //TODO: update to work with NT Auth when available
  251. function verifyConfig(config) {
  252. var required = ['user', 'password', 'hostname'];
  253. var missing = [];
  254. _.each(required, function(field) {
  255. if (!config[field]) {
  256. missing.push(field);
  257. }
  258. });
  259. if (missing.length > 0) {
  260. throw new Error('db_config.json missing the following field(s): ' + missing.join(', '));
  261. }
  262. }
  263.  
  264. // Parse db_config.json
  265. function parseConfig(config) {
  266. verifyConfig(config);
  267. if (process.env.dbtype === 'MSSQL') {
  268. parseMSSQL(config);
  269. } else if (process.env.dbtype === 'DB2') {
  270. parseDB2(config);
  271. }
  272. }
  273.  
  274. return getDatabaseType().then(function() {
  275. if (process.env.MSSQL_CONFIG || process.env.DB2_CONFIG || process.env.dbtype === 'SQLITE') {
  276. return; // This should only be hit when running in dev environment or when using SQLite
  277. } else {
  278. return readConfigFile().then(parseConfig);
  279. }
  280. });
  281. }
  282.  
  283. /**
  284. * Initialize the application monitor's environment variables.
  285. */
  286. function initEnvironment() {
  287. var defaults = {
  288. APP_PORT: '5000',
  289. INT_PORT: '5001',
  290. APP_PORT_MIN: '5002',
  291. APP_PORT_MAX: '6000',
  292. APP_RESTART_DELAY_SECONDS: '1',
  293. APP_UPDATE_DELAY_DAYS: '0',
  294. APP_UPDATE_ENABLE_AUTO: '1',
  295. ETL_DIR: path.resolve('.'),
  296. LOGIN_SESSION_TIMEOUT_SECONDS: '900',
  297. PLATFORM_HOST: 'localhost',
  298. PLATFORM_PORT: '52315',
  299. WEB_PORT: '3000',
  300. WORK_DIR: path.join(os.tmpdir(), 'bfappmonitor_tmp'),
  301. WORK_DELAY_SECONDS: '60',
  302. SAML_AUTHNCONTEXT: 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport',
  303. CACHE_TTL: '600',
  304. LOGIN_CACHE_TTL_HOURS: '86400',
  305. 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)
  306. };
  307.  
  308. Object.keys(defaults).forEach(function(variable) {
  309. if (!process.env[variable]) {
  310. process.env[variable] = defaults[variable];
  311. } else {
  312. process.env[variable] = envValidate[variable] ? envValidate[variable](variable, process.env[variable], defaults[variable]) : process.env[variable];
  313. }
  314. });
  315.  
  316. if (process.env.DEBUG === DEFAULT_DEBUG_FILTER) {
  317. process.env.DEBUG = NEW_DEBUG_FILTER;
  318. }
  319.  
  320. return Q()
  321. .then(initCACertificate)
  322. .then(initAuthCredentials)
  323. .then(initAppCredentials)
  324. .then(initWebCredentials)
  325. .then(initDatabaseConfiguration);
  326. }
  327.  
  328. module.exports = initEnvironment;
Add Comment
Please, Sign In to add comment