@itentialopensource/adapter-dna_center 0.5.4 → 0.5.7

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 (45) hide show
  1. package/.eslintignore +1 -0
  2. package/.eslintrc.js +12 -12
  3. package/CHANGELOG.md +24 -0
  4. package/ENHANCE.md +69 -0
  5. package/PROPERTIES.md +247 -0
  6. package/README.md +151 -379
  7. package/SUMMARY.md +9 -0
  8. package/TROUBLESHOOT.md +46 -0
  9. package/adapter.js +2212 -85
  10. package/adapterBase.js +848 -50
  11. package/entities/.generic/action.json +214 -0
  12. package/entities/.generic/schema.json +28 -0
  13. package/entities/.system/action.json +1 -1
  14. package/entities/Sites/action.json +42 -0
  15. package/entities/Sites/schema.json +2 -0
  16. package/error.json +12 -0
  17. package/package.json +45 -23
  18. package/pronghorn.json +780 -0
  19. package/propertiesDecorators.json +14 -0
  20. package/propertiesSchema.json +451 -11
  21. package/refs?service=git-upload-pack +0 -0
  22. package/report/updateReport1594147160686.json +95 -0
  23. package/report/updateReport1614887797185.json +95 -0
  24. package/report/updateReport1651598418513.json +114 -0
  25. package/sampleProperties.json +20 -5
  26. package/test/integration/adapterTestBasicGet.js +85 -0
  27. package/test/integration/adapterTestConnectivity.js +93 -0
  28. package/test/integration/adapterTestIntegration.js +87 -11
  29. package/test/unit/adapterBaseTestUnit.js +947 -0
  30. package/test/unit/adapterTestUnit.js +794 -18
  31. package/utils/addAuth.js +94 -0
  32. package/utils/artifactize.js +9 -14
  33. package/utils/basicGet.js +50 -0
  34. package/utils/checkMigrate.js +63 -0
  35. package/utils/entitiesToDB.js +224 -0
  36. package/utils/findPath.js +74 -0
  37. package/utils/modify.js +154 -0
  38. package/utils/packModificationScript.js +1 -1
  39. package/utils/patches2bundledDeps.js +90 -0
  40. package/utils/pre-commit.sh +1 -1
  41. package/utils/removeHooks.js +20 -0
  42. package/utils/tbScript.js +169 -0
  43. package/utils/tbUtils.js +464 -0
  44. package/utils/troubleshootingAdapter.js +190 -0
  45. package/gl-code-quality-report.json +0 -1
package/adapterBase.js CHANGED
@@ -6,11 +6,15 @@
6
6
  /* eslint import/no-dynamic-require: warn */
7
7
  /* eslint no-loop-func: warn */
8
8
  /* eslint no-cond-assign: warn */
9
+ /* eslint global-require: warn */
10
+ /* eslint no-unused-vars: warn */
11
+ /* eslint prefer-destructuring: warn */
9
12
 
10
13
  /* Required libraries. */
11
14
  const fs = require('fs-extra');
12
15
  const path = require('path');
13
16
  const EventEmitterCl = require('events').EventEmitter;
17
+ const { execSync } = require('child_process');
14
18
 
15
19
  /* The schema validator */
16
20
  const AjvCl = require('ajv');
@@ -19,6 +23,127 @@ const AjvCl = require('ajv');
19
23
  const PropUtilCl = require('@itentialopensource/adapter-utils').PropertyUtility;
20
24
  const RequestHandlerCl = require('@itentialopensource/adapter-utils').RequestHandler;
21
25
 
26
+ const entitiesToDB = require(path.join(__dirname, 'utils/entitiesToDB'));
27
+ const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
28
+ const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
29
+
30
+ let propUtil = null;
31
+
32
+ /*
33
+ * INTERNAL FUNCTION: force fail the adapter - generally done to cause restart
34
+ */
35
+ function forceFail(packChg) {
36
+ if (packChg !== undefined && packChg !== null && packChg === true) {
37
+ execSync(`rm -rf ${__dirname}/node modules`, { encoding: 'utf-8' });
38
+ execSync(`rm -rf ${__dirname}/package-lock.json`, { encoding: 'utf-8' });
39
+ execSync('npm install', { encoding: 'utf-8' });
40
+ }
41
+ log.error('NEED TO RESTART ADAPTER - FORCE FAIL');
42
+ const errorObj = {
43
+ origin: 'adapter-forceFail',
44
+ type: 'Force Fail so adapter will restart',
45
+ vars: []
46
+ };
47
+ setTimeout(() => {
48
+ throw new Error(JSON.stringify(errorObj));
49
+ }, 1000);
50
+ }
51
+
52
+ /*
53
+ * INTERNAL FUNCTION: update the action.json
54
+ */
55
+ function updateAction(entityPath, action, changes) {
56
+ // if the action file does not exist - error
57
+ const actionFile = path.join(entityPath, '/action.json');
58
+ if (!fs.existsSync(actionFile)) {
59
+ return 'Missing Action File';
60
+ }
61
+
62
+ // read in the file as a json object
63
+ const ajson = require(path.resolve(entityPath, 'action.json'));
64
+ let chgAct = {};
65
+
66
+ // get the action we need to change
67
+ for (let a = 0; a < ajson.actions.length; a += 1) {
68
+ if (ajson.actions[a].name === action) {
69
+ chgAct = ajson.actions[a];
70
+ break;
71
+ }
72
+ }
73
+ // merge the changes into the desired action
74
+ chgAct = propUtil.mergeProperties(changes, chgAct);
75
+
76
+ fs.writeFileSync(actionFile, JSON.stringify(ajson, null, 2));
77
+ return null;
78
+ }
79
+
80
+ /*
81
+ * INTERNAL FUNCTION: update the schema file
82
+ */
83
+ function updateSchema(entityPath, configFile, changes) {
84
+ // if the schema file does not exist - error
85
+ const schemaFile = path.join(entityPath, `/${configFile}`);
86
+ if (!fs.existsSync(schemaFile)) {
87
+ return 'Missing Schema File';
88
+ }
89
+
90
+ // read in the file as a json object
91
+ let schema = require(path.resolve(entityPath, configFile));
92
+
93
+ // merge the changes into the schema file
94
+ schema = propUtil.mergeProperties(changes, schema);
95
+
96
+ fs.writeFileSync(schemaFile, JSON.stringify(schema, null, 2));
97
+ return null;
98
+ }
99
+
100
+ /*
101
+ * INTERNAL FUNCTION: update the mock data file
102
+ */
103
+ function updateMock(mockPath, configFile, changes) {
104
+ // if the mock file does not exist - create it
105
+ const mockFile = path.join(mockPath, `/${configFile}`);
106
+ if (!fs.existsSync(mockFile)) {
107
+ const newMock = {};
108
+ fs.writeFileSync(mockFile, JSON.stringify(newMock, null, 2));
109
+ }
110
+
111
+ // read in the file as a json object
112
+ let mock = require(path.resolve(mockPath, configFile));
113
+
114
+ // merge the changes into the mock file
115
+ mock = propUtil.mergeProperties(changes, mock);
116
+
117
+ fs.writeFileSync(mockFile, JSON.stringify(mock, null, 2));
118
+ return null;
119
+ }
120
+
121
+ /*
122
+ * INTERNAL FUNCTION: update the package dependencies
123
+ */
124
+ function updatePackage(changes) {
125
+ // if the schema file does not exist - error
126
+ const packFile = path.join(__dirname, '/package.json');
127
+ if (!fs.existsSync(packFile)) {
128
+ return 'Missing Pacakge File';
129
+ }
130
+
131
+ // read in the file as a json object
132
+ const pack = require(path.resolve(__dirname, 'package.json'));
133
+
134
+ // only certain changes are allowed
135
+ if (changes.dependencies) {
136
+ const keys = Object.keys(changes.dependencies);
137
+
138
+ for (let k = 0; k < keys.length; k += 1) {
139
+ pack.dependencies[keys[k]] = changes.dependencies[keys[k]];
140
+ }
141
+ }
142
+
143
+ fs.writeFileSync(packFile, JSON.stringify(pack, null, 2));
144
+ return null;
145
+ }
146
+
22
147
  /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
23
148
  /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
24
149
  class AdapterBase extends EventEmitterCl {
@@ -30,13 +155,19 @@ class AdapterBase extends EventEmitterCl {
30
155
  // Instantiate the EventEmitter super class
31
156
  super();
32
157
 
158
+ // IAP home directory injected by core when running the adapter within IAP
159
+ process.env.iap_home = process.argv[3];
160
+
33
161
  try {
34
162
  // Capture the adapter id
35
163
  this.id = prongid;
36
164
  this.propUtilInst = new PropUtilCl(prongid, __dirname);
37
-
165
+ propUtil = this.propUtilInst;
166
+ this.initProps = properties;
38
167
  this.alive = false;
39
168
  this.healthy = false;
169
+ this.suspended = false;
170
+ this.suspendMode = 'pause';
40
171
  this.caching = false;
41
172
  this.repeatCacheCount = 0;
42
173
  this.allowFailover = 'AD.300';
@@ -54,7 +185,6 @@ class AdapterBase extends EventEmitterCl {
54
185
  }
55
186
  }
56
187
 
57
-
58
188
  /**
59
189
  * @callback healthCallback
60
190
  * @param {Object} result - the result of the get request (contains an id and a status)
@@ -80,7 +210,6 @@ class AdapterBase extends EventEmitterCl {
80
210
  * @param {String} error - any error that occured
81
211
  */
82
212
 
83
-
84
213
  /**
85
214
  * refreshProperties is used to set up all of the properties for the connector.
86
215
  * It allows properties to be changed later by simply calling refreshProperties rather
@@ -110,14 +239,20 @@ class AdapterBase extends EventEmitterCl {
110
239
 
111
240
  // if invalid properties throw an error
112
241
  if (!result) {
113
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Properties', [JSON.stringify(validate.errors)], null, null, null);
114
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
115
- throw new Error(JSON.stringify(errorObj));
242
+ if (this.requestHandlerInst) {
243
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Properties', [JSON.stringify(validate.errors)], null, null, null);
244
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
245
+ throw new Error(JSON.stringify(errorObj));
246
+ } else {
247
+ log.error(`${origin}: ${JSON.stringify(validate.errors)}`);
248
+ throw new Error(`${origin}: ${JSON.stringify(validate.errors)}`);
249
+ }
116
250
  }
117
251
 
118
252
  // properties that this code cares about
119
253
  this.healthcheckType = this.allProps.healthcheck.type;
120
254
  this.healthcheckInterval = this.allProps.healthcheck.frequency;
255
+ this.healthcheckQuery = this.allProps.healthcheck.query_object;
121
256
 
122
257
  // set the failover codes from properties
123
258
  if (this.allProps.request.failover_codes) {
@@ -162,9 +297,11 @@ class AdapterBase extends EventEmitterCl {
162
297
  // if there is no healthcheck just change the emit to ONLINE
163
298
  // We do not recommend no healthcheck!!!
164
299
  if (this.healthcheckType === 'none') {
165
- // validate all of the action files - normally done in healthcheck
166
- this.emit('ONLINE', { id: this.id });
167
- this.healthy = true;
300
+ log.error(`${origin}: Waiting 1 Seconds to emit Online`);
301
+ setTimeout(() => {
302
+ this.emit('ONLINE', { id: this.id });
303
+ this.healthy = true;
304
+ }, 1000);
168
305
  }
169
306
 
170
307
  // is the healthcheck only suppose to run on startup
@@ -197,8 +334,22 @@ class AdapterBase extends EventEmitterCl {
197
334
  const origin = `${this.id}-adapterBase-healthCheck`;
198
335
  log.trace(origin);
199
336
 
337
+ // if there is healthcheck query_object property, it needs to be added to the adapter
338
+ let myRequest = reqObj;
339
+ if (this.healthcheckQuery && Object.keys(this.healthcheckQuery).length > 0) {
340
+ if (myRequest && myRequest.uriQuery) {
341
+ myRequest.uriQuery = { ...myRequest.uriQuery, ...this.healthcheckQuery };
342
+ } else if (myRequest) {
343
+ myRequest.uriQuery = this.healthcheckQuery;
344
+ } else {
345
+ myRequest = {
346
+ uriQuery: this.healthcheckQuery
347
+ };
348
+ }
349
+ }
350
+
200
351
  // call to the healthcheck in connector
201
- return this.requestHandlerInst.identifyHealthcheck(reqObj, (res, error) => {
352
+ return this.requestHandlerInst.identifyHealthcheck(myRequest, (res, error) => {
202
353
  // unhealthy
203
354
  if (error) {
204
355
  // if we were healthy, toggle health
@@ -230,6 +381,424 @@ class AdapterBase extends EventEmitterCl {
230
381
  });
231
382
  }
232
383
 
384
+ /**
385
+ * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
386
+ * @param {array} ignoreThese - additional methods to ignore (optional)
387
+ *
388
+ * @function iapGetAdapterWorkflowFunctions
389
+ */
390
+ iapGetAdapterWorkflowFunctions(ignoreThese) {
391
+ const myfunctions = this.getAllFunctions();
392
+ const wffunctions = [];
393
+
394
+ // remove the functions that should not be in a Workflow
395
+ for (let m = 0; m < myfunctions.length; m += 1) {
396
+ if (myfunctions[m] === 'addEntityCache') {
397
+ // got to the second tier (adapterBase)
398
+ break;
399
+ }
400
+ if (myfunctions[m] !== 'iapHasAdapterEntity' && myfunctions[m] !== 'iapVerifyAdapterCapability'
401
+ && myfunctions[m] !== 'iapUpdateAdapterEntityCache' && myfunctions[m] !== 'healthCheck'
402
+ && myfunctions[m] !== 'iapGetAdapterWorkflowFunctions'
403
+ && !(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
404
+ let found = false;
405
+ if (ignoreThese && Array.isArray(ignoreThese)) {
406
+ for (let i = 0; i < ignoreThese.length; i += 1) {
407
+ if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
408
+ found = true;
409
+ }
410
+ }
411
+ }
412
+ if (!found) {
413
+ wffunctions.push(myfunctions[m]);
414
+ }
415
+ }
416
+ }
417
+
418
+ return wffunctions;
419
+ }
420
+
421
+ /**
422
+ * iapUpdateAdapterConfiguration is used to update any of the adapter configuration files. This
423
+ * allows customers to make changes to adapter configuration without having to be on the
424
+ * file system.
425
+ *
426
+ * @function iapUpdateAdapterConfiguration
427
+ * @param {string} configFile - the name of the file being updated (required)
428
+ * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
429
+ * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
430
+ * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
431
+ * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
432
+ * @param {Callback} callback - The results of the call
433
+ */
434
+ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
435
+ const meth = 'adapterBase-iapUpdateAdapterConfiguration';
436
+ const origin = `${this.id}-${meth}`;
437
+ log.trace(origin);
438
+
439
+ // verify the parameters are valid
440
+ if (changes === undefined || changes === null || typeof changes !== 'object'
441
+ || Object.keys(changes).length === 0) {
442
+ const result = {
443
+ response: 'No configuration updates to make'
444
+ };
445
+ log.info(result.response);
446
+ return callback(result, null);
447
+ }
448
+ if (configFile === undefined || configFile === null || configFile === '') {
449
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
450
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
451
+ return callback(null, errorObj);
452
+ }
453
+
454
+ // take action based on configFile being changed
455
+ if (configFile === 'package.json') {
456
+ const pres = updatePackage(changes);
457
+ if (pres) {
458
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
459
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
460
+ return callback(null, errorObj);
461
+ }
462
+ const result = {
463
+ response: 'Package updates completed - restarting adapter'
464
+ };
465
+ log.info(result.response);
466
+ forceFail(true);
467
+ return callback(result, null);
468
+ }
469
+ if (entity === undefined || entity === null || entity === '') {
470
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
471
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
472
+ return callback(null, errorObj);
473
+ }
474
+
475
+ // this means we are changing an entity file so type is required
476
+ if (type === undefined || type === null || type === '') {
477
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
478
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
479
+ return callback(null, errorObj);
480
+ }
481
+
482
+ // if the entity does not exist - error
483
+ const epath = `${__dirname}/entities/${entity}`;
484
+ if (!fs.existsSync(epath)) {
485
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
486
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
487
+ return callback(null, errorObj);
488
+ }
489
+
490
+ // take action based on type of file being changed
491
+ if (type === 'action') {
492
+ // BACKUP???
493
+ const ares = updateAction(epath, action, changes);
494
+ if (ares) {
495
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
496
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
497
+ return callback(null, errorObj);
498
+ }
499
+ // AJV CHECK???
500
+ // RESTORE IF NEEDED???
501
+ const result = {
502
+ response: `Action updates completed to entity: ${entity} - ${action}`
503
+ };
504
+ log.info(result.response);
505
+ return callback(result, null);
506
+ }
507
+ if (type === 'schema') {
508
+ const sres = updateSchema(epath, configFile, changes);
509
+ if (sres) {
510
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${sres}`, [], null, null, null);
511
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
512
+ return callback(null, errorObj);
513
+ }
514
+ const result = {
515
+ response: `Schema updates completed to entity: ${entity} - ${configFile}`
516
+ };
517
+ log.info(result.response);
518
+ return callback(result, null);
519
+ }
520
+ if (type === 'mock') {
521
+ // if the mock directory does not exist - error
522
+ const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
523
+ if (!fs.existsSync(mpath)) {
524
+ fs.mkdirSync(mpath);
525
+ }
526
+
527
+ const mres = updateMock(mpath, configFile, changes);
528
+ if (mres) {
529
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
530
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
531
+ return callback(null, errorObj);
532
+ }
533
+ const result = {
534
+ response: `Mock data updates completed to entity: ${entity} - ${configFile}`
535
+ };
536
+ log.info(result.response);
537
+ return callback(result, null);
538
+ }
539
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
540
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
541
+ return callback(null, errorObj);
542
+ }
543
+
544
+ /**
545
+ * See if the API path provided is found in this adapter
546
+ *
547
+ * @function iapFindAdapterPath
548
+ * @param {string} apiPath - the api path to check on
549
+ * @param {Callback} callback - The results of the call
550
+ */
551
+ iapFindAdapterPath(apiPath, callback) {
552
+ const result = {
553
+ apiPath
554
+ };
555
+
556
+ // verify the path was provided
557
+ if (!apiPath) {
558
+ log.error('NO API PATH PROVIDED!');
559
+ result.found = false;
560
+ result.message = 'NO PATH PROVIDED!';
561
+ return callback(null, result);
562
+ }
563
+
564
+ // make sure the entities directory exists
565
+ const entitydir = path.join(__dirname, 'entities');
566
+ if (!fs.statSync(entitydir).isDirectory()) {
567
+ log.error('Could not find the entities directory');
568
+ result.found = false;
569
+ result.message = 'Could not find the entities directory';
570
+ return callback(null, result);
571
+ }
572
+
573
+ const entities = fs.readdirSync(entitydir);
574
+ const fitems = [];
575
+
576
+ // need to go through each entity in the entities directory
577
+ for (let e = 0; e < entities.length; e += 1) {
578
+ // make sure the entity is a directory - do not care about extra files
579
+ // only entities (dir)
580
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
581
+ // see if the action file exists in the entity
582
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
583
+ // Read the entity actions from the file system
584
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
585
+
586
+ // go through all of the actions set the appropriate info in the newActions
587
+ for (let a = 0; a < actions.actions.length; a += 1) {
588
+ if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
589
+ log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
590
+ log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
591
+ const fitem = {
592
+ entity: entities[e],
593
+ action: actions.actions[a].name,
594
+ method: actions.actions[a].method,
595
+ path: actions.actions[a].entitypath
596
+ };
597
+ fitems.push(fitem);
598
+ }
599
+ }
600
+ } else {
601
+ log.error(`Could not find entities ${entities[e]} action.json file`);
602
+ result.found = false;
603
+ result.message = `Could not find entities ${entities[e]} action.json file`;
604
+ return callback(null, result);
605
+ }
606
+ } else {
607
+ log.error(`Could not find entities ${entities[e]} directory`);
608
+ result.found = false;
609
+ result.message = `Could not find entities ${entities[e]} directory`;
610
+ return callback(null, result);
611
+ }
612
+ }
613
+
614
+ if (fitems.length === 0) {
615
+ log.info('PATH NOT FOUND!');
616
+ result.found = false;
617
+ result.message = 'API PATH NOT FOUND!';
618
+ return callback(null, result);
619
+ }
620
+
621
+ result.foundIn = fitems;
622
+ result.found = true;
623
+ result.message = 'API PATH FOUND!';
624
+ return callback(result, null);
625
+ }
626
+
627
+ /**
628
+ * @summary Suspends the adapter
629
+ * @param {Callback} callback - The adapater suspension status
630
+ * @function iapSuspendAdapter
631
+ */
632
+ iapSuspendAdapter(mode, callback) {
633
+ const origin = `${this.id}-adapterBase-iapSuspendAdapter`;
634
+ if (this.suspended) {
635
+ throw new Error(`${origin}: Adapter is already suspended`);
636
+ }
637
+ try {
638
+ this.suspended = true;
639
+ this.suspendMode = mode;
640
+ if (this.suspendMode === 'pause') {
641
+ const props = JSON.parse(JSON.stringify(this.initProps));
642
+ // To suspend adapter, enable throttling and set concurrent max to 0
643
+ props.throttle.throttle_enabled = true;
644
+ props.throttle.concurrent_max = 0;
645
+ this.refreshProperties(props);
646
+ }
647
+ return callback({ suspended: true });
648
+ } catch (error) {
649
+ return callback(null, error);
650
+ }
651
+ }
652
+
653
+ /**
654
+ * @summary Unsuspends the adapter
655
+ * @param {Callback} callback - The adapater suspension status
656
+ *
657
+ * @function iapUnsuspendAdapter
658
+ */
659
+ iapUnsuspendAdapter(callback) {
660
+ const origin = `${this.id}-adapterBase-iapUnsuspendAdapter`;
661
+ if (!this.suspended) {
662
+ throw new Error(`${origin}: Adapter is not suspended`);
663
+ }
664
+ if (this.suspendMode === 'pause') {
665
+ const props = JSON.parse(JSON.stringify(this.initProps));
666
+ // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
667
+ props.throttle.throttle_enabled = true;
668
+ props.throttle.concurrent_max = 1;
669
+ this.refreshProperties(props);
670
+ setTimeout(() => {
671
+ this.getQueue((q, error) => {
672
+ // console.log("Items in queue: " + String(q.length))
673
+ if (q.length === 0) {
674
+ // if queue is empty, return to initial properties state
675
+ this.refreshProperties(this.initProps);
676
+ this.suspended = false;
677
+ return callback({ suspended: false });
678
+ }
679
+ // recursive call to check queue again every second
680
+ return this.iapUnsuspendAdapter(callback);
681
+ });
682
+ }, 1000);
683
+ } else {
684
+ this.suspended = false;
685
+ callback({ suspend: false });
686
+ }
687
+ }
688
+
689
+ /**
690
+ * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
691
+ *
692
+ * @function iapGetAdapterQueue
693
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
694
+ */
695
+ iapGetAdapterQueue(callback) {
696
+ const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
697
+ log.trace(origin);
698
+
699
+ return this.requestHandlerInst.getQueue(callback);
700
+ }
701
+
702
+ /**
703
+ * @summary runs troubleshoot scripts for adapter
704
+ *
705
+ * @function iapTroubleshootAdapter
706
+ * @param {Object} props - the connection, healthcheck and authentication properties
707
+ * @param {boolean} persistFlag - whether the adapter properties should be updated
708
+ * @param {Adapter} adapter - adapter instance to troubleshoot
709
+ * @param {Callback} callback - callback function to return troubleshoot results
710
+ */
711
+ async iapTroubleshootAdapter(props, persistFlag, adapter, callback) {
712
+ try {
713
+ const result = await troubleshootingAdapter.troubleshoot(props, false, persistFlag, adapter);
714
+ if (result.healthCheck && result.connectivity.failCount === 0 && result.basicGet.failCount === 0) {
715
+ return callback(result);
716
+ }
717
+ return callback(null, result);
718
+ } catch (error) {
719
+ return callback(null, error);
720
+ }
721
+ }
722
+
723
+ /**
724
+ * @summary runs healthcheck script for adapter
725
+ *
726
+ * @function iapRunAdapterHealthcheck
727
+ * @param {Adapter} adapter - adapter instance to troubleshoot
728
+ * @param {Callback} callback - callback function to return healthcheck status
729
+ */
730
+ async iapRunAdapterHealthcheck(adapter, callback) {
731
+ try {
732
+ const result = await tbUtils.healthCheck(adapter);
733
+ if (result) {
734
+ return callback(result);
735
+ }
736
+ return callback(null, result);
737
+ } catch (error) {
738
+ return callback(null, error);
739
+ }
740
+ }
741
+
742
+ /**
743
+ * @summary runs connectivity check script for adapter
744
+ *
745
+ * @function iapRunAdapterConnectivity
746
+ * @param {Adapter} adapter - adapter instance to troubleshoot
747
+ * @param {Callback} callback - callback function to return connectivity status
748
+ */
749
+ async iapRunAdapterConnectivity(callback) {
750
+ try {
751
+ const { serviceItem } = await tbUtils.getAdapterConfig();
752
+ const { host } = serviceItem.properties.properties;
753
+ const result = tbUtils.runConnectivity(host, false);
754
+ if (result.failCount > 0) {
755
+ return callback(null, result);
756
+ }
757
+ return callback(result);
758
+ } catch (error) {
759
+ return callback(null, error);
760
+ }
761
+ }
762
+
763
+ /**
764
+ * @summary runs basicGet script for adapter
765
+ *
766
+ * @function iapRunAdapterBasicGet
767
+ * @param {Callback} callback - callback function to return basicGet result
768
+ */
769
+ iapRunAdapterBasicGet(callback) {
770
+ try {
771
+ const result = tbUtils.runBasicGet(false);
772
+ if (result.failCount > 0) {
773
+ return callback(null, result);
774
+ }
775
+ return callback(result);
776
+ } catch (error) {
777
+ return callback(null, error);
778
+ }
779
+ }
780
+
781
+ /**
782
+ * @summary moves entities to mongo database
783
+ *
784
+ * @function iapMoveAdapterEntitiesToDB
785
+ *
786
+ * @return {Callback} - containing the response from the mongo transaction
787
+ */
788
+ iapMoveAdapterEntitiesToDB(callback) {
789
+ const meth = 'adapterBase-iapMoveAdapterEntitiesToDB';
790
+ const origin = `${this.id}-${meth}`;
791
+ log.trace(origin);
792
+
793
+ try {
794
+ return callback(entitiesToDB.iapMoveAdapterEntitiesToDB(__dirname, { pronghornProps: this.allProps, id: this.id }), null);
795
+ } catch (err) {
796
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, err);
797
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
798
+ return callback(null, errorObj);
799
+ }
800
+ }
801
+
233
802
  /**
234
803
  * getAllFunctions is used to get all of the exposed function in the adapter
235
804
  *
@@ -242,7 +811,7 @@ class AdapterBase extends EventEmitterCl {
242
811
  // find the functions in this class
243
812
  do {
244
813
  const l = Object.getOwnPropertyNames(obj)
245
- .concat(Object.getOwnPropertySymbols(obj).map(s => s.toString()))
814
+ .concat(Object.getOwnPropertySymbols(obj).map((s) => s.toString()))
246
815
  .sort()
247
816
  .filter((p, i, arr) => typeof obj[p] === 'function' && p !== 'constructor' && (i === 0 || p !== arr[i - 1]) && myfunctions.indexOf(p) === -1);
248
817
  myfunctions = myfunctions.concat(l);
@@ -254,30 +823,6 @@ class AdapterBase extends EventEmitterCl {
254
823
  return myfunctions;
255
824
  }
256
825
 
257
- /**
258
- * getWorkflowFunctions is used to get all of the workflow function in the adapter
259
- *
260
- * @function getAllFunctions
261
- */
262
- getWorkflowFunctions() {
263
- const myfunctions = this.getAllFunctions();
264
- const wffunctions = [];
265
-
266
- // remove the functions that should not be in a Workflow
267
- for (let m = 0; m < myfunctions.length; m += 1) {
268
- if (myfunctions[m] === 'addEntityCache') {
269
- // got to the second tier (adapterBase)
270
- break;
271
- }
272
- if (myfunctions[m] !== 'hasEntity' && myfunctions[m] !== 'verifyCapability'
273
- && myfunctions[m] !== 'updateEntityCache') {
274
- wffunctions.push(myfunctions[m]);
275
- }
276
- }
277
-
278
- return wffunctions;
279
- }
280
-
281
826
  /**
282
827
  * checkActionFiles is used to update the validation of the action files.
283
828
  *
@@ -313,19 +858,6 @@ class AdapterBase extends EventEmitterCl {
313
858
  }
314
859
  }
315
860
 
316
- /**
317
- * getQueue is used to get information for all of the requests currently in the queue.
318
- *
319
- * @function getQueue
320
- * @param {Callback} callback - a callback function to return the result (Queue) or the error
321
- */
322
- getQueue(callback) {
323
- const origin = `${this.id}-adapterBase-getQueue`;
324
- log.trace(origin);
325
-
326
- return this.requestHandlerInst.getQueue(callback);
327
- }
328
-
329
861
  /**
330
862
  * @summary Takes in property text and an encoding/encryption and returns the resulting
331
863
  * encoded/encrypted string
@@ -406,7 +938,7 @@ class AdapterBase extends EventEmitterCl {
406
938
  const resEntity = [];
407
939
 
408
940
  for (let e = 0; e < entityId.length; e += 1) {
409
- if (data.includes(entityId)) {
941
+ if (data.includes(entityId[e])) {
410
942
  resEntity.push(true);
411
943
  } else {
412
944
  resEntity.push(false);
@@ -430,7 +962,7 @@ class AdapterBase extends EventEmitterCl {
430
962
  * desired capability or an error
431
963
  */
432
964
  capabilityResults(results, callback) {
433
- const meth = 'adapterBase-getQueue';
965
+ const meth = 'adapterBase-capabilityResults';
434
966
  const origin = `${this.id}-${meth}`;
435
967
  log.trace(origin);
436
968
  let locResults = results;
@@ -496,6 +1028,272 @@ class AdapterBase extends EventEmitterCl {
496
1028
  return [];
497
1029
  }
498
1030
  }
1031
+
1032
+ /**
1033
+ * @summary Make one of the needed Broker calls - could be one of many
1034
+ *
1035
+ * @function iapMakeBrokerCall
1036
+ * @param {string} brokCall - the name of the broker call (required)
1037
+ * @param {object} callProps - the proeprties for the broker call (required)
1038
+ * @param {object} devResp - the device details to extract needed inputs (required)
1039
+ * @param {string} filterName - any filter to search on (required)
1040
+ *
1041
+ * @param {getCallback} callback - a callback function to return the result of the call
1042
+ */
1043
+ iapMakeBrokerCall(brokCall, callProps, devResp, filterName, callback) {
1044
+ const meth = 'adapter-iapMakeBrokerCall';
1045
+ const origin = `${this.id}-${meth}`;
1046
+ log.trace(origin);
1047
+
1048
+ try {
1049
+ let uriPath = '';
1050
+ let uriMethod = 'GET';
1051
+ let callQuery = {};
1052
+ let callBody = {};
1053
+ let callHeaders = {};
1054
+ let handleFail = 'fail';
1055
+ let ostypePrefix = '';
1056
+ let statusValue = 'true';
1057
+ if (callProps.path) {
1058
+ uriPath = `${callProps.path}`;
1059
+
1060
+ // make any necessary changes to the path
1061
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1062
+ const rqKeys = Object.keys(callProps.requestFields);
1063
+
1064
+ // get the field from the provided device
1065
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1066
+ // get the request field we are retrieving
1067
+ const loopField = callProps.requestFields[rqKeys[rq]];
1068
+ const loopArray = loopField.split('.');
1069
+ let nestedValue = devResp;
1070
+
1071
+ // loops through incase the field is nested
1072
+ for (let i = 0; i < loopArray.length; i += 1) {
1073
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1074
+ nestedValue = nestedValue[loopArray[i]];
1075
+ } else {
1076
+ // failed to traverse
1077
+ nestedValue = loopField;
1078
+ break;
1079
+ }
1080
+ }
1081
+
1082
+ // put the value into the path - if it has been specified in the path
1083
+ uriPath = uriPath.replace(`{${rqKeys[rq]}}`, nestedValue);
1084
+ }
1085
+ }
1086
+ }
1087
+ if (callProps.method) {
1088
+ uriMethod = callProps.method;
1089
+ }
1090
+ if (callProps.query) {
1091
+ callQuery = callProps.query;
1092
+
1093
+ // go through the query params to check for variable values
1094
+ const cpKeys = Object.keys(callQuery);
1095
+ for (let cp = 0; cp < cpKeys.length; cp += 1) {
1096
+ if (callQuery[cpKeys[cp]].startsWith('{') && callQuery[cpKeys[cp]].endsWith('}')) {
1097
+ // make any necessary changes to the query params
1098
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1099
+ const rqKeys = Object.keys(callProps.requestFields);
1100
+
1101
+ // get the uuid from the device
1102
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1103
+ if (cpKeys[cp] === rqKeys[rq]) {
1104
+ // get the request field we are retrieving
1105
+ const loopField = callProps.requestFields[rqKeys[rq]];
1106
+ const loopArray = loopField.split('.');
1107
+ let nestedValue = devResp;
1108
+
1109
+ // loops through incase the field is nested
1110
+ for (let i = 0; i < loopArray.length; i += 1) {
1111
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1112
+ nestedValue = nestedValue[loopArray[i]];
1113
+ } else {
1114
+ // failed to traverse
1115
+ nestedValue = loopField;
1116
+ break;
1117
+ }
1118
+ }
1119
+
1120
+ // put the value into the query - if it has been specified in the query
1121
+ callQuery[cpKeys[cp]] = nestedValue;
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ if (callProps.body) {
1129
+ callBody = callProps.body;
1130
+ }
1131
+ if (callProps.headers) {
1132
+ callHeaders = callProps.headers;
1133
+ }
1134
+ if (callProps.handleFailure) {
1135
+ handleFail = callProps.handleFailure;
1136
+ }
1137
+ if (callProps.responseFields && callProps.responseFields.ostypePrefix) {
1138
+ ostypePrefix = callProps.responseFields.ostypePrefix;
1139
+ }
1140
+ if (callProps.responseFields && callProps.responseFields.statusValue) {
1141
+ statusValue = callProps.responseFields.statusValue;
1142
+ }
1143
+
1144
+ // !! using Generic makes it easier on the Adapter Builder (just need to change the path)
1145
+ // !! you can also replace with a specific call if that is easier
1146
+ return this.genericAdapterRequest(uriPath, uriMethod, callQuery, callBody, callHeaders, (result, error) => {
1147
+ // if we received an error or their is no response on the results return an error
1148
+ if (error) {
1149
+ if (handleFail === 'fail') {
1150
+ return callback(null, error);
1151
+ }
1152
+ return callback({}, null);
1153
+ }
1154
+ if (!result.response) {
1155
+ if (handleFail === 'fail') {
1156
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', [brokCall], null, null, null);
1157
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1158
+ return callback(null, errorObj);
1159
+ }
1160
+ return callback({}, null);
1161
+ }
1162
+
1163
+ // get the keys for the response fields
1164
+ let rfKeys = [];
1165
+ if (callProps.responseFields && Object.keys(callProps.responseFields).length > 0) {
1166
+ rfKeys = Object.keys(callProps.responseFields);
1167
+ }
1168
+
1169
+ // if we got an array returned (e.g. getDevicesFitered)
1170
+ if (Array.isArray(result.response)) {
1171
+ const listDevices = [];
1172
+ for (let a = 0; a < result.response.length; a += 1) {
1173
+ const thisDevice = result.response[a];
1174
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1175
+ if (rfKeys[rf] !== 'ostypePrefix') {
1176
+ // get the response field we are retrieving
1177
+ const loopField = callProps.responseFields[rfKeys[rf]];
1178
+ const loopArray = loopField.split('.');
1179
+ let nestedValue = thisDevice;
1180
+
1181
+ // loops through incase the field is nested
1182
+ for (let i = 0; i < loopArray.length; i += 1) {
1183
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1184
+ nestedValue = nestedValue[loopArray[i]];
1185
+ } else {
1186
+ // failed to traverse
1187
+ nestedValue = '';
1188
+ break;
1189
+ }
1190
+ }
1191
+ // if the field is ostype - need to add prefix
1192
+ if (rfKeys[rf] === 'ostype' && typeof nestedValue === 'string') {
1193
+ nestedValue = ostypePrefix + nestedValue;
1194
+ }
1195
+ // if there is a status to set, set it
1196
+ if (rfKeys[rf] === 'status') {
1197
+ // if really looking for just a good response
1198
+ if (loopField === 'return2xx' && result.icode === statusValue.toString()) {
1199
+ thisDevice.isAlive = true;
1200
+ } else if (nestedValue.toString() === statusValue.toString()) {
1201
+ thisDevice.isAlive = true;
1202
+ } else {
1203
+ thisDevice.isAlive = false;
1204
+ }
1205
+ }
1206
+ // if we found a good value
1207
+ thisDevice[rfKeys[rf]] = nestedValue;
1208
+ }
1209
+ }
1210
+
1211
+ // if there is no filter - add the device to the list
1212
+ if (!filterName || filterName.length === 0) {
1213
+ listDevices.push(thisDevice);
1214
+ } else {
1215
+ // if we have to match a filter
1216
+ let found = false;
1217
+ for (let f = 0; f < filterName.length; f += 1) {
1218
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1219
+ found = true;
1220
+ break;
1221
+ }
1222
+ }
1223
+ // matching device
1224
+ if (found) {
1225
+ listDevices.push(thisDevice);
1226
+ }
1227
+ }
1228
+ }
1229
+
1230
+ // return the array of devices
1231
+ return callback(listDevices, null);
1232
+ }
1233
+
1234
+ // if this is not an array - just about everything else, just handle as a single object
1235
+ let thisDevice = result.response;
1236
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1237
+ // skip ostypePrefix since it is not a field
1238
+ if (rfKeys[rf] !== 'ostypePrefix') {
1239
+ // get the response field we are retrieving
1240
+ const loopField = callProps.responseFields[rfKeys[rf]];
1241
+ const loopArray = loopField.split('.');
1242
+ let nestedValue = thisDevice;
1243
+
1244
+ // loops through incase the field is nested
1245
+ for (let i = 0; i < loopArray.length; i += 1) {
1246
+ if (Object.hasOwnProperty.call(nestedValue, loopArray[i])) {
1247
+ nestedValue = nestedValue[loopArray[i]];
1248
+ } else {
1249
+ // failed to traverse
1250
+ nestedValue = '';
1251
+ break;
1252
+ }
1253
+ }
1254
+ // if the field is ostype - need to add prefix
1255
+ if (rfKeys[rf] === 'ostype' && typeof nestedValue === 'string') {
1256
+ nestedValue = ostypePrefix + nestedValue;
1257
+ }
1258
+ // if there is a status to set, set it
1259
+ if (rfKeys[rf] === 'status') {
1260
+ // if really looking for just a good response
1261
+ if (loopField === 'return2xx' && result.icode === statusValue.toString()) {
1262
+ thisDevice.isAlive = true;
1263
+ } else if (nestedValue.toString() === statusValue.toString()) {
1264
+ thisDevice.isAlive = true;
1265
+ } else {
1266
+ thisDevice.isAlive = false;
1267
+ }
1268
+ }
1269
+ // if we found a good value
1270
+ thisDevice[rfKeys[rf]] = nestedValue;
1271
+ }
1272
+ }
1273
+
1274
+ // if there is a filter - check the device is in the list
1275
+ if (filterName && filterName.length > 0) {
1276
+ let found = false;
1277
+ for (let f = 0; f < filterName.length; f += 1) {
1278
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1279
+ found = true;
1280
+ break;
1281
+ }
1282
+ }
1283
+ // no matching device - clear the device
1284
+ if (!found) {
1285
+ thisDevice = {};
1286
+ }
1287
+ }
1288
+
1289
+ return callback(thisDevice, null);
1290
+ });
1291
+ } catch (e) {
1292
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, e);
1293
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1294
+ return callback(null, errorObj);
1295
+ }
1296
+ }
499
1297
  }
500
1298
 
501
1299
  module.exports = AdapterBase;