@itentialopensource/adapter-gogetssl 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.eslintignore +5 -0
  2. package/.eslintrc.js +18 -0
  3. package/.jshintrc +3 -0
  4. package/CHANGELOG.md +9 -0
  5. package/CODE_OF_CONDUCT.md +48 -0
  6. package/CONTRIBUTING.md +158 -0
  7. package/LICENSE +201 -0
  8. package/README.md +687 -0
  9. package/adapter.js +5428 -0
  10. package/adapterBase.js +1028 -0
  11. package/entities/.generic/action.json +109 -0
  12. package/entities/.generic/schema.json +23 -0
  13. package/entities/.system/action.json +50 -0
  14. package/entities/.system/mockdatafiles/getToken-default.json +3 -0
  15. package/entities/.system/mockdatafiles/healthcheck-default.json +3 -0
  16. package/entities/.system/schema.json +19 -0
  17. package/entities/.system/schemaTokenReq.json +53 -0
  18. package/entities/.system/schemaTokenResp.json +53 -0
  19. package/entities/Account/action.json +46 -0
  20. package/entities/Account/mockdatafiles/getAccountBalance-default.json +5 -0
  21. package/entities/Account/mockdatafiles/getAccountDetails-default.json +18 -0
  22. package/entities/Account/schema.json +31 -0
  23. package/entities/CSR/action.json +64 -0
  24. package/entities/CSR/mockdatafiles/decodeCSR-default.json +6 -0
  25. package/entities/CSR/mockdatafiles/generateCSR-default.json +5 -0
  26. package/entities/CSR/schema.json +98 -0
  27. package/entities/DCV/action.json +84 -0
  28. package/entities/DCV/mockdatafiles/domainGetFromWhois-default.json +5 -0
  29. package/entities/DCV/mockdatafiles/getDomainAlternative-default.json +24 -0
  30. package/entities/DCV/mockdatafiles/getDomainEmails-default.json +5 -0
  31. package/entities/DCV/mockdatafiles/getDomainEmailsForGeotrust-default.json +10 -0
  32. package/entities/DCV/schema.json +33 -0
  33. package/entities/Invoices/action.json +67 -0
  34. package/entities/Invoices/mockdatafiles/getAllInvoices-default.json +27 -0
  35. package/entities/Invoices/mockdatafiles/getOrderInvoice-default.json +13 -0
  36. package/entities/Invoices/mockdatafiles/getUnpaidInvoices-default.json +60 -0
  37. package/entities/Invoices/schema.json +43 -0
  38. package/entities/LEI/action.json +127 -0
  39. package/entities/LEI/mockdatafiles/createNewLEI-default.json +13 -0
  40. package/entities/LEI/mockdatafiles/getLeiStatus-default.json +5 -0
  41. package/entities/LEI/schema.json +46 -0
  42. package/entities/Orders/action.json +249 -0
  43. package/entities/Orders/mockdatafiles/addSSLOrder-default.json +59 -0
  44. package/entities/Orders/mockdatafiles/addSSLSANOrder-default.json +10 -0
  45. package/entities/Orders/mockdatafiles/cancelOrder-default.json +4 -0
  46. package/entities/Orders/mockdatafiles/comodoClaimFreeEV-default.json +5 -0
  47. package/entities/Orders/mockdatafiles/getAllSSLOrders-default.json +40 -0
  48. package/entities/Orders/mockdatafiles/getOrderStatus-default.json +105 -0
  49. package/entities/Orders/mockdatafiles/getOrdersStatuses-default.json +32 -0
  50. package/entities/Orders/mockdatafiles/getTotalOrders-default.json +4 -0
  51. package/entities/Orders/mockdatafiles/getUnpaidOrders-default.json +131 -0
  52. package/entities/Orders/mockdatafiles/recheckCAA-default.json +5 -0
  53. package/entities/Orders/schema.json +459 -0
  54. package/entities/Products/action.json +151 -0
  55. package/entities/Products/mockdatafiles/getAllProductPrices-default.json +10 -0
  56. package/entities/Products/mockdatafiles/getAllProducts-default.json +110 -0
  57. package/entities/Products/mockdatafiles/getProductAgreement-default.json +5 -0
  58. package/entities/Products/mockdatafiles/getProductPrice-default.json +50 -0
  59. package/entities/Products/mockdatafiles/getSslProduct-default.json +29 -0
  60. package/entities/Products/mockdatafiles/getSslProducts-default.json +325 -0
  61. package/entities/Products/schema.json +47 -0
  62. package/entities/Validation/action.json +145 -0
  63. package/entities/Validation/mockdatafiles/changeDcv-default.json +12 -0
  64. package/entities/Validation/mockdatafiles/changeDomainsValidationMethod-default.json +4 -0
  65. package/entities/Validation/mockdatafiles/resend-default.json +5 -0
  66. package/entities/Validation/mockdatafiles/resendValidationEmail-default.json +5 -0
  67. package/entities/Validation/mockdatafiles/revalidate-default.json +5 -0
  68. package/entities/Validation/schema.json +91 -0
  69. package/entities/Webservers/action.json +25 -0
  70. package/entities/Webservers/mockdatafiles/getWebServers-default.json +149 -0
  71. package/entities/Webservers/schema.json +41 -0
  72. package/error.json +184 -0
  73. package/package.json +83 -0
  74. package/pronghorn.json +8799 -0
  75. package/propertiesSchema.json +840 -0
  76. package/refs?service=git-upload-pack +0 -0
  77. package/report/creationReport.json +339 -0
  78. package/report/gogetssl_apimatic_openapi3.json +21135 -0
  79. package/sampleProperties.json +106 -0
  80. package/test/integration/adapterTestBasicGet.js +85 -0
  81. package/test/integration/adapterTestConnectivity.js +93 -0
  82. package/test/integration/adapterTestIntegration.js +1746 -0
  83. package/test/unit/adapterBaseTestUnit.js +944 -0
  84. package/test/unit/adapterTestUnit.js +4765 -0
  85. package/utils/addAuth.js +94 -0
  86. package/utils/artifactize.js +146 -0
  87. package/utils/basicGet.js +50 -0
  88. package/utils/checkMigrate.js +63 -0
  89. package/utils/entitiesToDB.js +224 -0
  90. package/utils/findPath.js +74 -0
  91. package/utils/modify.js +154 -0
  92. package/utils/packModificationScript.js +35 -0
  93. package/utils/pre-commit.sh +27 -0
  94. package/utils/removeHooks.js +20 -0
  95. package/utils/setup.js +33 -0
  96. package/utils/tbScript.js +169 -0
  97. package/utils/tbUtils.js +445 -0
  98. package/utils/testRunner.js +298 -0
  99. package/utils/troubleshootingAdapter.js +190 -0
  100. package/workflows/README.md +3 -0
package/adapterBase.js ADDED
@@ -0,0 +1,1028 @@
1
+ /* @copyright Itential, LLC 2018-9 */
2
+
3
+ // Set globals
4
+ /* global log */
5
+ /* eslint class-methods-use-this:warn */
6
+ /* eslint import/no-dynamic-require: warn */
7
+ /* eslint no-loop-func: warn */
8
+ /* eslint no-cond-assign: warn */
9
+ /* eslint global-require: warn */
10
+ /* eslint no-unused-vars: warn */
11
+
12
+ /* Required libraries. */
13
+ const fs = require('fs-extra');
14
+ const path = require('path');
15
+ const EventEmitterCl = require('events').EventEmitter;
16
+ const { execSync } = require('child_process');
17
+
18
+ /* The schema validator */
19
+ const AjvCl = require('ajv');
20
+
21
+ /* Fetch in the other needed components for the this Adaptor */
22
+ const PropUtilCl = require('@itentialopensource/adapter-utils').PropertyUtility;
23
+ const RequestHandlerCl = require('@itentialopensource/adapter-utils').RequestHandler;
24
+
25
+ const entitiesToDB = require(path.join(__dirname, 'utils/entitiesToDB'));
26
+ const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
27
+ const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
28
+
29
+ let propUtil = null;
30
+
31
+ /*
32
+ * INTERNAL FUNCTION: force fail the adapter - generally done to cause restart
33
+ */
34
+ function forceFail(packChg) {
35
+ if (packChg !== undefined && packChg !== null && packChg === true) {
36
+ execSync(`rm -rf ${__dirname}/node modules`, { encoding: 'utf-8' });
37
+ execSync(`rm -rf ${__dirname}/package-lock.json`, { encoding: 'utf-8' });
38
+ execSync('npm install', { encoding: 'utf-8' });
39
+ }
40
+ log.error('NEED TO RESTART ADAPTER - FORCE FAIL');
41
+ const errorObj = {
42
+ origin: 'adapter-forceFail',
43
+ type: 'Force Fail so adapter will restart',
44
+ vars: []
45
+ };
46
+ setTimeout(() => {
47
+ throw new Error(JSON.stringify(errorObj));
48
+ }, 1000);
49
+ }
50
+
51
+ /*
52
+ * INTERNAL FUNCTION: update the action.json
53
+ */
54
+ function updateAction(entityPath, action, changes) {
55
+ // if the action file does not exist - error
56
+ const actionFile = path.join(entityPath, '/action.json');
57
+ if (!fs.existsSync(actionFile)) {
58
+ return 'Missing Action File';
59
+ }
60
+
61
+ // read in the file as a json object
62
+ const ajson = require(path.resolve(entityPath, 'action.json'));
63
+ let chgAct = {};
64
+
65
+ // get the action we need to change
66
+ for (let a = 0; a < ajson.actions.length; a += 1) {
67
+ if (ajson.actions[a].name === action) {
68
+ chgAct = ajson.actions[a];
69
+ break;
70
+ }
71
+ }
72
+ // merge the changes into the desired action
73
+ chgAct = propUtil.mergeProperties(changes, chgAct);
74
+
75
+ fs.writeFileSync(actionFile, JSON.stringify(ajson, null, 2));
76
+ return null;
77
+ }
78
+
79
+ /*
80
+ * INTERNAL FUNCTION: update the schema file
81
+ */
82
+ function updateSchema(entityPath, configFile, changes) {
83
+ // if the schema file does not exist - error
84
+ const schemaFile = path.join(entityPath, `/${configFile}`);
85
+ if (!fs.existsSync(schemaFile)) {
86
+ return 'Missing Schema File';
87
+ }
88
+
89
+ // read in the file as a json object
90
+ let schema = require(path.resolve(entityPath, configFile));
91
+
92
+ // merge the changes into the schema file
93
+ schema = propUtil.mergeProperties(changes, schema);
94
+
95
+ fs.writeFileSync(schemaFile, JSON.stringify(schema, null, 2));
96
+ return null;
97
+ }
98
+
99
+ /*
100
+ * INTERNAL FUNCTION: update the mock data file
101
+ */
102
+ function updateMock(mockPath, configFile, changes) {
103
+ // if the mock file does not exist - create it
104
+ const mockFile = path.join(mockPath, `/${configFile}`);
105
+ if (!fs.existsSync(mockFile)) {
106
+ const newMock = {};
107
+ fs.writeFileSync(mockFile, JSON.stringify(newMock, null, 2));
108
+ }
109
+
110
+ // read in the file as a json object
111
+ let mock = require(path.resolve(mockPath, configFile));
112
+
113
+ // merge the changes into the mock file
114
+ mock = propUtil.mergeProperties(changes, mock);
115
+
116
+ fs.writeFileSync(mockFile, JSON.stringify(mock, null, 2));
117
+ return null;
118
+ }
119
+
120
+ /*
121
+ * INTERNAL FUNCTION: update the package dependencies
122
+ */
123
+ function updatePackage(changes) {
124
+ // if the schema file does not exist - error
125
+ const packFile = path.join(__dirname, '/package.json');
126
+ if (!fs.existsSync(packFile)) {
127
+ return 'Missing Pacakge File';
128
+ }
129
+
130
+ // read in the file as a json object
131
+ const pack = require(path.resolve(__dirname, 'package.json'));
132
+
133
+ // only certain changes are allowed
134
+ if (changes.dependencies) {
135
+ const keys = Object.keys(changes.dependencies);
136
+
137
+ for (let k = 0; k < keys.length; k += 1) {
138
+ pack.dependencies[keys[k]] = changes.dependencies[keys[k]];
139
+ }
140
+ }
141
+
142
+ fs.writeFileSync(packFile, JSON.stringify(pack, null, 2));
143
+ return null;
144
+ }
145
+
146
+ /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
147
+ /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
148
+ class AdapterBase extends EventEmitterCl {
149
+ /**
150
+ * [System] Adapter
151
+ * @constructor
152
+ */
153
+ constructor(prongid, properties) {
154
+ // Instantiate the EventEmitter super class
155
+ super();
156
+
157
+ try {
158
+ // Capture the adapter id
159
+ this.id = prongid;
160
+ this.propUtilInst = new PropUtilCl(prongid, __dirname);
161
+ propUtil = this.propUtilInst;
162
+ this.initProps = properties;
163
+ this.alive = false;
164
+ this.healthy = false;
165
+ this.suspended = false;
166
+ this.suspendMode = 'pause';
167
+ this.caching = false;
168
+ this.repeatCacheCount = 0;
169
+ this.allowFailover = 'AD.300';
170
+ this.noFailover = 'AD.500';
171
+
172
+ // set up the properties I care about
173
+ this.refreshProperties(properties);
174
+
175
+ // Instantiate the other components for this Adapter
176
+ this.requestHandlerInst = new RequestHandlerCl(this.id, this.allProps, __dirname);
177
+ } catch (e) {
178
+ // handle any exception
179
+ const origin = `${this.id}-adapterBase-constructor`;
180
+ log.error(`${origin}: Adapter may not have started properly. ${e}`);
181
+ }
182
+ }
183
+
184
+ /**
185
+ * @callback healthCallback
186
+ * @param {Object} result - the result of the get request (contains an id and a status)
187
+ */
188
+ /**
189
+ * @callback getCallback
190
+ * @param {Object} result - the result of the get request (entity/ies)
191
+ * @param {String} error - any error that occured
192
+ */
193
+ /**
194
+ * @callback createCallback
195
+ * @param {Object} item - the newly created entity
196
+ * @param {String} error - any error that occured
197
+ */
198
+ /**
199
+ * @callback updateCallback
200
+ * @param {String} status - the status of the update action
201
+ * @param {String} error - any error that occured
202
+ */
203
+ /**
204
+ * @callback deleteCallback
205
+ * @param {String} status - the status of the delete action
206
+ * @param {String} error - any error that occured
207
+ */
208
+
209
+ /**
210
+ * refreshProperties is used to set up all of the properties for the connector.
211
+ * It allows properties to be changed later by simply calling refreshProperties rather
212
+ * than having to restart the connector.
213
+ *
214
+ * @function refreshProperties
215
+ * @param {Object} properties - an object containing all of the properties
216
+ * @param {boolean} init - are we initializing -- is so no need to refresh throtte engine
217
+ */
218
+ refreshProperties(properties) {
219
+ const meth = 'adapterBase-refreshProperties';
220
+ const origin = `${this.id}-${meth}`;
221
+ log.trace(origin);
222
+
223
+ try {
224
+ // Read the properties schema from the file system
225
+ const propertiesSchema = JSON.parse(fs.readFileSync(path.join(__dirname, 'propertiesSchema.json'), 'utf-8'));
226
+
227
+ // add any defaults to the data
228
+ const defProps = this.propUtilInst.setDefaults(propertiesSchema);
229
+ this.allProps = this.propUtilInst.mergeProperties(properties, defProps);
230
+
231
+ // validate the entity against the schema
232
+ const ajvInst = new AjvCl();
233
+ const validate = ajvInst.compile(propertiesSchema);
234
+ const result = validate(this.allProps);
235
+
236
+ // if invalid properties throw an error
237
+ if (!result) {
238
+ if (this.requestHandlerInst) {
239
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Properties', [JSON.stringify(validate.errors)], null, null, null);
240
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
241
+ throw new Error(JSON.stringify(errorObj));
242
+ } else {
243
+ log.error(`${origin}: ${JSON.stringify(validate.errors)}`);
244
+ throw new Error(`${origin}: ${JSON.stringify(validate.errors)}`);
245
+ }
246
+ }
247
+
248
+ // properties that this code cares about
249
+ this.healthcheckType = this.allProps.healthcheck.type;
250
+ this.healthcheckInterval = this.allProps.healthcheck.frequency;
251
+ this.healthcheckQuery = this.allProps.healthcheck.query_object;
252
+
253
+ // set the failover codes from properties
254
+ if (this.allProps.request.failover_codes) {
255
+ if (Array.isArray(this.allProps.request.failover_codes)) {
256
+ this.failoverCodes = this.allProps.request.failover_codes;
257
+ } else {
258
+ this.failoverCodes = [this.allProps.request.failover_codes];
259
+ }
260
+ } else {
261
+ this.failoverCodes = [];
262
+ }
263
+
264
+ // set the caching flag from properties
265
+ if (this.allProps.cache_location) {
266
+ if (this.allProps.cache_location === 'redis' || this.allProps.cache_location === 'local') {
267
+ this.caching = true;
268
+ }
269
+ }
270
+
271
+ // if this is truly a refresh and we have a request handler, refresh it
272
+ if (this.requestHandlerInst) {
273
+ this.requestHandlerInst.refreshProperties(properties);
274
+ }
275
+ } catch (e) {
276
+ log.error(`${origin}: Properties may not have been set properly. ${e}`);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * updateAdapterConfiguration is used to update any of the adapter configuration files. This
282
+ * allows customers to make changes to adapter configuration without having to be on the
283
+ * file system.
284
+ *
285
+ * @function updateAdapterConfiguration
286
+ * @param {string} configFile - the name of the file being updated (required)
287
+ * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
288
+ * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
289
+ * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
290
+ * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
291
+ * @param {Callback} callback - The results of the call
292
+ */
293
+ updateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
294
+ const meth = 'adapterBase-updateAdapterConfiguration';
295
+ const origin = `${this.id}-${meth}`;
296
+ log.trace(origin);
297
+
298
+ // verify the parameters are valid
299
+ if (changes === undefined || changes === null || typeof changes !== 'object'
300
+ || Object.keys(changes).length === 0) {
301
+ const result = {
302
+ response: 'No configuration updates to make'
303
+ };
304
+ log.info(result.response);
305
+ return callback(result, null);
306
+ }
307
+ if (configFile === undefined || configFile === null || configFile === '') {
308
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
309
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
310
+ return callback(null, errorObj);
311
+ }
312
+
313
+ // take action based on configFile being changed
314
+ if (configFile === 'package.json') {
315
+ const pres = updatePackage(changes);
316
+ if (pres) {
317
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
318
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
319
+ return callback(null, errorObj);
320
+ }
321
+ const result = {
322
+ response: 'Package updates completed - restarting adapter'
323
+ };
324
+ log.info(result.response);
325
+ forceFail(true);
326
+ return callback(result, null);
327
+ }
328
+ if (entity === undefined || entity === null || entity === '') {
329
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
330
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
331
+ return callback(null, errorObj);
332
+ }
333
+
334
+ // this means we are changing an entity file so type is required
335
+ if (type === undefined || type === null || type === '') {
336
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
337
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
338
+ return callback(null, errorObj);
339
+ }
340
+
341
+ // if the entity does not exist - error
342
+ const epath = `${__dirname}/entities/${entity}`;
343
+ if (!fs.existsSync(epath)) {
344
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
345
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
346
+ return callback(null, errorObj);
347
+ }
348
+
349
+ // take action based on type of file being changed
350
+ if (type === 'action') {
351
+ // BACKUP???
352
+ const ares = updateAction(epath, action, changes);
353
+ if (ares) {
354
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
355
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
356
+ return callback(null, errorObj);
357
+ }
358
+ // AJV CHECK???
359
+ // RESTORE IF NEEDED???
360
+ const result = {
361
+ response: `Action updates completed to entity: ${entity} - ${action}`
362
+ };
363
+ log.info(result.response);
364
+ return callback(result, null);
365
+ }
366
+ if (type === 'schema') {
367
+ const sres = updateSchema(epath, configFile, changes);
368
+ if (sres) {
369
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${sres}`, [], null, null, null);
370
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
371
+ return callback(null, errorObj);
372
+ }
373
+ const result = {
374
+ response: `Schema updates completed to entity: ${entity} - ${configFile}`
375
+ };
376
+ log.info(result.response);
377
+ return callback(result, null);
378
+ }
379
+ if (type === 'mock') {
380
+ // if the mock directory does not exist - error
381
+ const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
382
+ if (!fs.existsSync(mpath)) {
383
+ fs.mkdirSync(mpath);
384
+ }
385
+
386
+ const mres = updateMock(mpath, configFile, changes);
387
+ if (mres) {
388
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
389
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
390
+ return callback(null, errorObj);
391
+ }
392
+ const result = {
393
+ response: `Mock data updates completed to entity: ${entity} - ${configFile}`
394
+ };
395
+ log.info(result.response);
396
+ return callback(result, null);
397
+ }
398
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
399
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
400
+ return callback(null, errorObj);
401
+ }
402
+
403
+ /**
404
+ * @summary Connect function is used during Pronghorn startup to provide instantiation feedback.
405
+ *
406
+ * @function connect
407
+ */
408
+ connect() {
409
+ const origin = `${this.id}-adapterBase-connect`;
410
+ log.trace(origin);
411
+
412
+ // initially set as off
413
+ this.emit('OFFLINE', { id: this.id });
414
+ this.alive = true;
415
+
416
+ // if there is no healthcheck just change the emit to ONLINE
417
+ // We do not recommend no healthcheck!!!
418
+ if (this.healthcheckType === 'none') {
419
+ log.error(`${origin}: Waiting 1 Seconds to emit Online`);
420
+ setTimeout(() => {
421
+ this.emit('ONLINE', { id: this.id });
422
+ this.healthy = true;
423
+ }, 1000);
424
+ }
425
+
426
+ // is the healthcheck only suppose to run on startup
427
+ // (intermittent runs on startup and after that)
428
+ if (this.healthcheckType === 'startup' || this.healthcheckType === 'intermittent') {
429
+ // run an initial healthcheck
430
+ this.healthCheck(null, (status) => {
431
+ log.spam(`${origin}: ${status}`);
432
+ });
433
+ }
434
+
435
+ // is the healthcheck suppose to run intermittently
436
+ if (this.healthcheckType === 'intermittent') {
437
+ // run the healthcheck in an interval
438
+ setInterval(() => {
439
+ // try to see if mongo is available
440
+ this.healthCheck(null, (status) => {
441
+ log.spam(`${origin}: ${status}`);
442
+ });
443
+ }, this.healthcheckInterval);
444
+ }
445
+ }
446
+
447
+ /**
448
+ * @summary HealthCheck function is used to provide Pronghorn the status of this adapter.
449
+ *
450
+ * @function healthCheck
451
+ */
452
+ healthCheck(reqObj, callback) {
453
+ const origin = `${this.id}-adapterBase-healthCheck`;
454
+ log.trace(origin);
455
+
456
+ // if there is healthcheck query_object property, it needs to be added to the adapter
457
+ let myRequest = reqObj;
458
+ if (this.healthcheckQuery && Object.keys(this.healthcheckQuery).length > 0) {
459
+ if (myRequest && myRequest.uriQuery) {
460
+ myRequest.uriQuery = { ...myRequest.uriQuery, ...this.healthcheckQuery };
461
+ } else if (myRequest) {
462
+ myRequest.uriQuery = this.healthcheckQuery;
463
+ } else {
464
+ myRequest = {
465
+ uriQuery: this.healthcheckQuery
466
+ };
467
+ }
468
+ }
469
+
470
+ // call to the healthcheck in connector
471
+ return this.requestHandlerInst.identifyHealthcheck(reqObj, (res, error) => {
472
+ // unhealthy
473
+ if (error) {
474
+ // if we were healthy, toggle health
475
+ if (this.healthy) {
476
+ this.emit('OFFLINE', { id: this.id });
477
+ this.emit('DEGRADED', { id: this.id });
478
+ this.healthy = false;
479
+ log.error(`${origin}: HEALTH CHECK - Error ${error}`);
480
+ } else {
481
+ // still log but set the level to trace
482
+ log.trace(`${origin}: HEALTH CHECK - Still Errors ${error}`);
483
+ }
484
+
485
+ return callback(false);
486
+ }
487
+
488
+ // if we were unhealthy, toggle health
489
+ if (!this.healthy) {
490
+ this.emit('FIXED', { id: this.id });
491
+ this.emit('ONLINE', { id: this.id });
492
+ this.healthy = true;
493
+ log.info(`${origin}: HEALTH CHECK SUCCESSFUL`);
494
+ } else {
495
+ // still log but set the level to trace
496
+ log.trace(`${origin}: HEALTH CHECK STILL SUCCESSFUL`);
497
+ }
498
+
499
+ return callback(true);
500
+ });
501
+ }
502
+
503
+ /**
504
+ * @summary Suspends the adapter
505
+ * @param {Callback} callback - The adapater suspension status
506
+ * @function suspend
507
+ */
508
+ suspend(mode, callback) {
509
+ const origin = `${this.id}-adapterBase-suspend`;
510
+ if (this.suspended) {
511
+ throw new Error(`${origin}: Adapter is already suspended`);
512
+ }
513
+ try {
514
+ this.suspended = true;
515
+ this.suspendMode = mode;
516
+ if (this.suspendMode === 'pause') {
517
+ const props = JSON.parse(JSON.stringify(this.initProps));
518
+ // To suspend adapter, enable throttling and set concurrent max to 0
519
+ props.throttle.throttle_enabled = true;
520
+ props.throttle.concurrent_max = 0;
521
+ this.refreshProperties(props);
522
+ }
523
+ return callback({ suspended: true });
524
+ } catch (error) {
525
+ return callback(null, error);
526
+ }
527
+ }
528
+
529
+ /**
530
+ * @summary Unsuspends the adapter
531
+ * @param {Callback} callback - The adapater suspension status
532
+ *
533
+ * @function unsuspend
534
+ */
535
+ unsuspend(callback) {
536
+ const origin = `${this.id}-adapterBase-unsuspend`;
537
+ if (!this.suspended) {
538
+ throw new Error(`${origin}: Adapter is not suspended`);
539
+ }
540
+ if (this.suspendMode === 'pause') {
541
+ const props = JSON.parse(JSON.stringify(this.initProps));
542
+ // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
543
+ props.throttle.throttle_enabled = true;
544
+ props.throttle.concurrent_max = 1;
545
+ this.refreshProperties(props);
546
+ setTimeout(() => {
547
+ this.getQueue((q, error) => {
548
+ // console.log("Items in queue: " + String(q.length))
549
+ if (q.length === 0) {
550
+ // if queue is empty, return to initial properties state
551
+ this.refreshProperties(this.initProps);
552
+ this.suspended = false;
553
+ return callback({ suspended: false });
554
+ }
555
+ // recursive call to check queue again every second
556
+ return this.unsuspend(callback);
557
+ });
558
+ }, 1000);
559
+ } else {
560
+ this.suspended = false;
561
+ callback({ suspend: false });
562
+ }
563
+ }
564
+
565
+ /**
566
+ * getAllFunctions is used to get all of the exposed function in the adapter
567
+ *
568
+ * @function getAllFunctions
569
+ */
570
+ getAllFunctions() {
571
+ let myfunctions = [];
572
+ let obj = this;
573
+
574
+ // find the functions in this class
575
+ do {
576
+ const l = Object.getOwnPropertyNames(obj)
577
+ .concat(Object.getOwnPropertySymbols(obj).map((s) => s.toString()))
578
+ .sort()
579
+ .filter((p, i, arr) => typeof obj[p] === 'function' && p !== 'constructor' && (i === 0 || p !== arr[i - 1]) && myfunctions.indexOf(p) === -1);
580
+ myfunctions = myfunctions.concat(l);
581
+ }
582
+ while (
583
+ (obj = Object.getPrototypeOf(obj)) && Object.getPrototypeOf(obj)
584
+ );
585
+
586
+ return myfunctions;
587
+ }
588
+
589
+ /**
590
+ * getWorkflowFunctions is used to get all of the workflow function in the adapter
591
+ * @param {array} ignoreThese - additional methods to ignore (optional)
592
+ *
593
+ * @function getWorkflowFunctions
594
+ */
595
+ getWorkflowFunctions(ignoreThese) {
596
+ const myfunctions = this.getAllFunctions();
597
+ const wffunctions = [];
598
+
599
+ // remove the functions that should not be in a Workflow
600
+ for (let m = 0; m < myfunctions.length; m += 1) {
601
+ if (myfunctions[m] === 'addEntityCache') {
602
+ // got to the second tier (adapterBase)
603
+ break;
604
+ }
605
+ if (myfunctions[m] !== 'hasEntity' && myfunctions[m] !== 'verifyCapability' && myfunctions[m] !== 'updateEntityCache'
606
+ && myfunctions[m] !== 'healthCheck' && myfunctions[m] !== 'getWorkflowFunctions'
607
+ && !(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
608
+ let found = false;
609
+ if (ignoreThese && Array.isArray(ignoreThese)) {
610
+ for (let i = 0; i < ignoreThese.length; i += 1) {
611
+ if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
612
+ found = true;
613
+ }
614
+ }
615
+ }
616
+ if (!found) {
617
+ wffunctions.push(myfunctions[m]);
618
+ }
619
+ }
620
+ }
621
+
622
+ return wffunctions;
623
+ }
624
+
625
+ /**
626
+ * checkActionFiles is used to update the validation of the action files.
627
+ *
628
+ * @function checkActionFiles
629
+ */
630
+ checkActionFiles() {
631
+ const origin = `${this.id}-adapterBase-checkActionFiles`;
632
+ log.trace(origin);
633
+
634
+ // validate the action files for the adapter
635
+ try {
636
+ return this.requestHandlerInst.checkActionFiles();
637
+ } catch (e) {
638
+ return ['Exception increase log level'];
639
+ }
640
+ }
641
+
642
+ /**
643
+ * See if the API path provided is found in this adapter
644
+ *
645
+ * @function findPath
646
+ * @param {string} apiPath - the api path to check on
647
+ * @param {Callback} callback - The results of the call
648
+ */
649
+ findPath(apiPath, callback) {
650
+ const result = {
651
+ apiPath
652
+ };
653
+
654
+ // verify the path was provided
655
+ if (!apiPath) {
656
+ log.error('NO API PATH PROVIDED!');
657
+ result.found = false;
658
+ result.message = 'NO PATH PROVIDED!';
659
+ return callback(null, result);
660
+ }
661
+
662
+ // make sure the entities directory exists
663
+ const entitydir = path.join(__dirname, 'entities');
664
+ if (!fs.statSync(entitydir).isDirectory()) {
665
+ log.error('Could not find the entities directory');
666
+ result.found = false;
667
+ result.message = 'Could not find the entities directory';
668
+ return callback(null, result);
669
+ }
670
+
671
+ const entities = fs.readdirSync(entitydir);
672
+ const fitems = [];
673
+
674
+ // need to go through each entity in the entities directory
675
+ for (let e = 0; e < entities.length; e += 1) {
676
+ // make sure the entity is a directory - do not care about extra files
677
+ // only entities (dir)
678
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
679
+ // see if the action file exists in the entity
680
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
681
+ // Read the entity actions from the file system
682
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
683
+
684
+ // go through all of the actions set the appropriate info in the newActions
685
+ for (let a = 0; a < actions.actions.length; a += 1) {
686
+ if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
687
+ log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
688
+ log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
689
+ const fitem = {
690
+ entity: entities[e],
691
+ action: actions.actions[a].name,
692
+ method: actions.actions[a].method,
693
+ path: actions.actions[a].entitypath
694
+ };
695
+ fitems.push(fitem);
696
+ }
697
+ }
698
+ } else {
699
+ log.error(`Could not find entities ${entities[e]} action.json file`);
700
+ result.found = false;
701
+ result.message = `Could not find entities ${entities[e]} action.json file`;
702
+ return callback(null, result);
703
+ }
704
+ } else {
705
+ log.error(`Could not find entities ${entities[e]} directory`);
706
+ result.found = false;
707
+ result.message = `Could not find entities ${entities[e]} directory`;
708
+ return callback(null, result);
709
+ }
710
+ }
711
+
712
+ if (fitems.length === 0) {
713
+ log.info('PATH NOT FOUND!');
714
+ result.found = false;
715
+ result.message = 'API PATH NOT FOUND!';
716
+ return callback(null, result);
717
+ }
718
+
719
+ result.foundIn = fitems;
720
+ result.found = true;
721
+ result.message = 'API PATH FOUND!';
722
+ return callback(result, null);
723
+ }
724
+
725
+ /**
726
+ * checkProperties is used to validate the adapter properties.
727
+ *
728
+ * @function checkProperties
729
+ * @param {Object} properties - an object containing all of the properties
730
+ */
731
+ checkProperties(properties) {
732
+ const origin = `${this.myid}-adapterBase-checkProperties`;
733
+ log.trace(origin);
734
+
735
+ // validate the properties for the adapter
736
+ try {
737
+ return this.requestHandlerInst.checkProperties(properties);
738
+ } catch (e) {
739
+ return { exception: 'Exception increase log level' };
740
+ }
741
+ }
742
+
743
+ /**
744
+ * getQueue is used to get information for all of the requests currently in the queue.
745
+ *
746
+ * @function getQueue
747
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
748
+ */
749
+ getQueue(callback) {
750
+ const origin = `${this.id}-adapterBase-getQueue`;
751
+ log.trace(origin);
752
+
753
+ return this.requestHandlerInst.getQueue(callback);
754
+ }
755
+
756
+ /**
757
+ * @summary Takes in property text and an encoding/encryption and returns the resulting
758
+ * encoded/encrypted string
759
+ *
760
+ * @function encryptProperty
761
+ * @param {String} property - the property to encrypt
762
+ * @param {String} technique - the technique to use to encrypt
763
+ *
764
+ * @param {Callback} callback - a callback function to return the result
765
+ * Encrypted String or the Error
766
+ */
767
+ encryptProperty(property, technique, callback) {
768
+ const origin = `${this.id}-adapterBase-encryptProperty`;
769
+ log.trace(origin);
770
+
771
+ // Make the call -
772
+ // encryptProperty(property, technique, callback)
773
+ return this.requestHandlerInst.encryptProperty(property, technique, callback);
774
+ }
775
+
776
+ /**
777
+ * @summary runs troubleshoot scripts for adapter
778
+ *
779
+ * @function troubleshoot
780
+ * @param {Object} props - the connection, healthcheck and authentication properties
781
+ * @param {boolean} persistFlag - whether the adapter properties should be updated
782
+ * @param {Adapter} adapter - adapter instance to troubleshoot
783
+ * @param {Callback} callback - callback function to return troubleshoot results
784
+ */
785
+ async troubleshoot(props, persistFlag, adapter, callback) {
786
+ try {
787
+ const result = await troubleshootingAdapter.troubleshoot(props, false, persistFlag, adapter);
788
+ if (result.healthCheck && result.connectivity.failCount === 0 && result.basicGet.failCount === 0) {
789
+ return callback(result);
790
+ }
791
+ return callback(null, result);
792
+ } catch (error) {
793
+ return callback(null, error);
794
+ }
795
+ }
796
+
797
+ /**
798
+ * @summary runs healthcheck script for adapter
799
+ *
800
+ * @function runHealthcheck
801
+ * @param {Adapter} adapter - adapter instance to troubleshoot
802
+ * @param {Callback} callback - callback function to return healthcheck status
803
+ */
804
+ async runHealthcheck(adapter, callback) {
805
+ try {
806
+ const result = await tbUtils.healthCheck(adapter);
807
+ if (result) {
808
+ return callback(result);
809
+ }
810
+ return callback(null, result);
811
+ } catch (error) {
812
+ return callback(null, error);
813
+ }
814
+ }
815
+
816
+ /**
817
+ * @summary runs connectivity check script for adapter
818
+ *
819
+ * @function runConnectivity
820
+ * @param {Adapter} adapter - adapter instance to troubleshoot
821
+ * @param {Callback} callback - callback function to return connectivity status
822
+ */
823
+ async runConnectivity(callback) {
824
+ try {
825
+ const { serviceItem } = await troubleshootingAdapter.getAdapterConfig();
826
+ const { host } = serviceItem.properties.properties;
827
+ const result = tbUtils.runConnectivity(host, false);
828
+ if (result.failCount > 0) {
829
+ return callback(null, result);
830
+ }
831
+ return callback(result);
832
+ } catch (error) {
833
+ return callback(null, error);
834
+ }
835
+ }
836
+
837
+ /**
838
+ * @summary runs basicGet script for adapter
839
+ *
840
+ * @function runBasicGet
841
+ * @param {Callback} callback - callback function to return basicGet result
842
+ */
843
+ runBasicGet(callback) {
844
+ try {
845
+ const result = tbUtils.runBasicGet(false);
846
+ if (result.failCount > 0) {
847
+ return callback(null, result);
848
+ }
849
+ return callback(result);
850
+ } catch (error) {
851
+ return callback(null, error);
852
+ }
853
+ }
854
+
855
+ /**
856
+ * @summary take the entities and add them to the cache
857
+ *
858
+ * @function addEntityCache
859
+ * @param {String} entityType - the type of the entities
860
+ * @param {Array} data - the list of entities
861
+ * @param {String} key - unique key for the entities
862
+ *
863
+ * @param {Callback} callback - An array of whether the adapter can has the
864
+ * desired capability or an error
865
+ */
866
+ addEntityCache(entityType, entities, key, callback) {
867
+ const meth = 'adapterBase-addEntityCache';
868
+ const origin = `${this.id}-${meth}`;
869
+ log.trace(origin);
870
+
871
+ // list containing the items to add to the cache
872
+ const entityIds = [];
873
+
874
+ if (entities && Object.hasOwnProperty.call(entities, 'response')
875
+ && Array.isArray(entities.response)) {
876
+ for (let e = 0; e < entities.response.length; e += 1) {
877
+ entityIds.push(entities.response[e][key]);
878
+ }
879
+ }
880
+
881
+ // add the entities to the cache
882
+ return this.requestHandlerInst.addEntityCache(entityType, entityIds, (loaded, error) => {
883
+ if (error) {
884
+ return callback(null, error);
885
+ }
886
+ if (!loaded) {
887
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', [entityType], null, null, null);
888
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
889
+ return callback(null, errorObj);
890
+ }
891
+
892
+ return callback(loaded);
893
+ });
894
+ }
895
+
896
+ /**
897
+ * @summary sees if the entity is in the entity list or not
898
+ *
899
+ * @function entityInList
900
+ * @param {String/Array} entityId - the specific entity we are looking for
901
+ * @param {Array} data - the list of entities
902
+ *
903
+ * @param {Callback} callback - An array of whether the adapter can has the
904
+ * desired capability or an error
905
+ */
906
+ entityInList(entityId, data) {
907
+ const origin = `${this.id}-adapterBase-entityInList`;
908
+ log.trace(origin);
909
+
910
+ // need to check on the entities that were passed in
911
+ if (Array.isArray(entityId)) {
912
+ const resEntity = [];
913
+
914
+ for (let e = 0; e < entityId.length; e += 1) {
915
+ if (data.includes(entityId[e])) {
916
+ resEntity.push(true);
917
+ } else {
918
+ resEntity.push(false);
919
+ }
920
+ }
921
+
922
+ return resEntity;
923
+ }
924
+
925
+ // does the entity list include the specific entity
926
+ return [data.includes(entityId)];
927
+ }
928
+
929
+ /**
930
+ * @summary prepare results for verify capability so they are true/false
931
+ *
932
+ * @function capabilityResults
933
+ * @param {Array} results - the results from the capability check
934
+ *
935
+ * @param {Callback} callback - An array of whether the adapter can has the
936
+ * desired capability or an error
937
+ */
938
+ capabilityResults(results, callback) {
939
+ const meth = 'adapterBase-capabilityResults';
940
+ const origin = `${this.id}-${meth}`;
941
+ log.trace(origin);
942
+ let locResults = results;
943
+
944
+ if (locResults && locResults[0] === 'needupdate') {
945
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', ['unknown'], null, null, null);
946
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
947
+ this.repeatCacheCount += 1;
948
+ return callback(null, errorObj);
949
+ }
950
+
951
+ // if an error occured, return the error
952
+ if (locResults && locResults[0] === 'error') {
953
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Error Verifying Entity Cache', null, null, null, null);
954
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
955
+ return callback(null, errorObj);
956
+ }
957
+
958
+ // go through the response and change to true/false
959
+ if (locResults) {
960
+ // if not an array, just convert the return
961
+ if (!Array.isArray(locResults)) {
962
+ if (locResults === 'found') {
963
+ locResults = [true];
964
+ } else {
965
+ locResults = [false];
966
+ }
967
+ } else {
968
+ const temp = [];
969
+
970
+ // go through each element in the array to convert
971
+ for (let r = 0; r < locResults.length; r += 1) {
972
+ if (locResults[r] === 'found') {
973
+ temp.push(true);
974
+ } else {
975
+ temp.push(false);
976
+ }
977
+ }
978
+ locResults = temp;
979
+ }
980
+ }
981
+
982
+ // return the results
983
+ return callback(locResults);
984
+ }
985
+
986
+ /**
987
+ * @summary Provides a way for the adapter to tell north bound integrations
988
+ * all of the capabilities for the current adapter
989
+ *
990
+ * @function getAllCapabilities
991
+ *
992
+ * @return {Array} - containing the entities and the actions available on each entity
993
+ */
994
+ getAllCapabilities() {
995
+ const origin = `${this.id}-adapterBase-getAllCapabilities`;
996
+ log.trace(origin);
997
+
998
+ // validate the capabilities for the adapter
999
+ try {
1000
+ return this.requestHandlerInst.getAllCapabilities();
1001
+ } catch (e) {
1002
+ return [];
1003
+ }
1004
+ }
1005
+
1006
+ /**
1007
+ * @summary moves entities to mongo database
1008
+ *
1009
+ * @function moveEntitiesToDB
1010
+ *
1011
+ * @return {Callback} - containing the response from the mongo transaction
1012
+ */
1013
+ moveEntitiesToDB(callback) {
1014
+ const meth = 'adapterBase-moveEntitiesToDB';
1015
+ const origin = `${this.id}-${meth}`;
1016
+ log.trace(origin);
1017
+
1018
+ try {
1019
+ return callback(entitiesToDB.moveEntitiesToDB(__dirname, { pronghornProps: this.allProps, id: this.id }), null);
1020
+ } catch (err) {
1021
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, err);
1022
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1023
+ return callback(null, errorObj);
1024
+ }
1025
+ }
1026
+ }
1027
+
1028
+ module.exports = AdapterBase;