@itentialopensource/adapter-openstack_cinder 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 (130) hide show
  1. package/.eslintignore +5 -0
  2. package/.eslintrc.js +18 -0
  3. package/.jshintrc +3 -0
  4. package/AUTH.md +43 -0
  5. package/BROKER.md +199 -0
  6. package/CALLS.md +1118 -0
  7. package/CHANGELOG.md +9 -0
  8. package/CODE_OF_CONDUCT.md +43 -0
  9. package/CONTRIBUTING.md +172 -0
  10. package/ENHANCE.md +69 -0
  11. package/LICENSE +201 -0
  12. package/PROPERTIES.md +641 -0
  13. package/README.md +337 -0
  14. package/SUMMARY.md +9 -0
  15. package/SYSTEMINFO.md +11 -0
  16. package/TROUBLESHOOT.md +47 -0
  17. package/adapter.js +20288 -0
  18. package/adapterBase.js +1788 -0
  19. package/entities/.generic/action.json +214 -0
  20. package/entities/.generic/schema.json +28 -0
  21. package/entities/.system/action.json +50 -0
  22. package/entities/.system/mockdatafiles/getToken-default.json +242 -0
  23. package/entities/.system/mockdatafiles/healthcheck-default.json +3 -0
  24. package/entities/.system/schema.json +19 -0
  25. package/entities/.system/schemaTokenReq.json +53 -0
  26. package/entities/.system/schemaTokenResp.json +49 -0
  27. package/entities/APIExtensionsExtensions/action.json +25 -0
  28. package/entities/APIExtensionsExtensions/schema.json +30 -0
  29. package/entities/APIVersionDetails/action.json +25 -0
  30. package/entities/APIVersionDetails/schema.json +19 -0
  31. package/entities/APIVersions/action.json +25 -0
  32. package/entities/APIVersions/schema.json +19 -0
  33. package/entities/AttachmentsAttachments/action.json +147 -0
  34. package/entities/AttachmentsAttachments/schema.json +58 -0
  35. package/entities/BackEndStoragePools/action.json +25 -0
  36. package/entities/BackEndStoragePools/schema.json +30 -0
  37. package/entities/BackupActionsBackupsAction/action.json +24 -0
  38. package/entities/BackupActionsBackupsAction/schema.json +41 -0
  39. package/entities/BackupsBackups/action.json +188 -0
  40. package/entities/BackupsBackups/schema.json +71 -0
  41. package/entities/CapabilitiesForStorageBackEndsCapabilities/action.json +25 -0
  42. package/entities/CapabilitiesForStorageBackEndsCapabilities/schema.json +30 -0
  43. package/entities/ConsistencyGroupSnapshotsDEPRECATED/action.json +107 -0
  44. package/entities/ConsistencyGroupSnapshotsDEPRECATED/schema.json +56 -0
  45. package/entities/ConsistencyGroupsDEPRECATED/action.json +147 -0
  46. package/entities/ConsistencyGroupsDEPRECATED/schema.json +58 -0
  47. package/entities/DefaultVolumeTypesDefaultTypes/action.json +86 -0
  48. package/entities/DefaultVolumeTypesDefaultTypes/schema.json +33 -0
  49. package/entities/GenericVolumeGroupsGroups/action.json +147 -0
  50. package/entities/GenericVolumeGroupsGroups/schema.json +69 -0
  51. package/entities/GroupSnapshotsGroupSnapshots/action.json +127 -0
  52. package/entities/GroupSnapshotsGroupSnapshots/schema.json +79 -0
  53. package/entities/GroupTypeSpecsGroupTypesGroupSpecs/action.json +106 -0
  54. package/entities/GroupTypeSpecsGroupTypesGroupSpecs/schema.json +56 -0
  55. package/entities/GroupTypesGroupTypes/action.json +127 -0
  56. package/entities/GroupTypesGroupTypes/schema.json +46 -0
  57. package/entities/HostsExtensionOsHosts/action.json +46 -0
  58. package/entities/HostsExtensionOsHosts/schema.json +42 -0
  59. package/entities/LimitsLimits/action.json +25 -0
  60. package/entities/LimitsLimits/schema.json +30 -0
  61. package/entities/MessagesMessages/action.json +66 -0
  62. package/entities/MessagesMessages/schema.json +43 -0
  63. package/entities/QualityOfServiceQoSSpecificationsQosSpecs/action.json +210 -0
  64. package/entities/QualityOfServiceQoSSpecificationsQosSpecs/schema.json +61 -0
  65. package/entities/QuotaClassSetExtensionOsQuotaClassSets/action.json +45 -0
  66. package/entities/QuotaClassSetExtensionOsQuotaClassSets/schema.json +42 -0
  67. package/entities/QuotaSetsExtensionOsQuotaSets/action.json +86 -0
  68. package/entities/QuotaSetsExtensionOsQuotaSets/schema.json +44 -0
  69. package/entities/ResourceFiltersResourceFilters/action.json +25 -0
  70. package/entities/ResourceFiltersResourceFilters/schema.json +30 -0
  71. package/entities/ServicesOsServices/action.json +185 -0
  72. package/entities/ServicesOsServices/schema.json +38 -0
  73. package/entities/SnapshotActionsSnapshotsAction/action.json +24 -0
  74. package/entities/SnapshotActionsSnapshotsAction/schema.json +41 -0
  75. package/entities/SnapshotManageExtensionManageableSnapshots/action.json +66 -0
  76. package/entities/SnapshotManageExtensionManageableSnapshots/schema.json +32 -0
  77. package/entities/VolumeActionsVolumesAction/action.json +24 -0
  78. package/entities/VolumeActionsVolumesAction/schema.json +41 -0
  79. package/entities/VolumeManageExtensionManageableVolumes/action.json +66 -0
  80. package/entities/VolumeManageExtensionManageableVolumes/schema.json +32 -0
  81. package/entities/VolumeSnapshotsSnapshots/action.json +249 -0
  82. package/entities/VolumeSnapshotsSnapshots/schema.json +85 -0
  83. package/entities/VolumeTransfer/action.json +127 -0
  84. package/entities/VolumeTransfer/schema.json +57 -0
  85. package/entities/VolumeTransfersVolumeTransfers355OrLater/action.json +127 -0
  86. package/entities/VolumeTransfersVolumeTransfers355OrLater/schema.json +79 -0
  87. package/entities/VolumeTypeAccessTypesActionTypesOsVolumeTypeAccess/action.json +45 -0
  88. package/entities/VolumeTypeAccessTypesActionTypesOsVolumeTypeAccess/schema.json +42 -0
  89. package/entities/VolumeTypesTypes/action.json +331 -0
  90. package/entities/VolumeTypesTypes/schema.json +78 -0
  91. package/entities/VolumesVolumes/action.json +270 -0
  92. package/entities/VolumesVolumes/schema.json +108 -0
  93. package/entities/WorkersWorkers/action.json +24 -0
  94. package/entities/WorkersWorkers/schema.json +30 -0
  95. package/error.json +190 -0
  96. package/package.json +87 -0
  97. package/pronghorn.json +10093 -0
  98. package/propertiesDecorators.json +14 -0
  99. package/propertiesSchema.json +1284 -0
  100. package/refs?service=git-upload-pack +0 -0
  101. package/report/adapterInfo.json +10 -0
  102. package/report/cinder-openapi.json +8589 -0
  103. package/report/creationReport.json +1495 -0
  104. package/sampleProperties.json +198 -0
  105. package/swagger/openstack_API_docs/BlockStorageAPIV3-cinder-documentation.html +32674 -0
  106. package/swagger/openstack_api_cinder.js +602 -0
  107. package/test/integration/adapterTestBasicGet.js +85 -0
  108. package/test/integration/adapterTestConnectivity.js +93 -0
  109. package/test/integration/adapterTestIntegration.js +4799 -0
  110. package/test/unit/adapterBaseTestUnit.js +952 -0
  111. package/test/unit/adapterTestUnit.js +7633 -0
  112. package/utils/adapterInfo.js +206 -0
  113. package/utils/addAuth.js +94 -0
  114. package/utils/artifactize.js +146 -0
  115. package/utils/basicGet.js +50 -0
  116. package/utils/checkMigrate.js +63 -0
  117. package/utils/entitiesToDB.js +179 -0
  118. package/utils/findPath.js +74 -0
  119. package/utils/methodDocumentor.js +225 -0
  120. package/utils/modify.js +154 -0
  121. package/utils/packModificationScript.js +35 -0
  122. package/utils/patches2bundledDeps.js +90 -0
  123. package/utils/pre-commit.sh +32 -0
  124. package/utils/removeHooks.js +20 -0
  125. package/utils/setup.js +33 -0
  126. package/utils/tbScript.js +184 -0
  127. package/utils/tbUtils.js +469 -0
  128. package/utils/testRunner.js +298 -0
  129. package/utils/troubleshootingAdapter.js +190 -0
  130. package/workflows/README.md +3 -0
package/adapterBase.js ADDED
@@ -0,0 +1,1788 @@
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
+ /* eslint prefer-destructuring: warn */
12
+
13
+ /* Required libraries. */
14
+ const fs = require('fs-extra');
15
+ const path = require('path');
16
+ const jsonQuery = require('json-query');
17
+ const EventEmitterCl = require('events').EventEmitter;
18
+ const { execSync } = require('child_process');
19
+
20
+ /* The schema validator */
21
+ const AjvCl = require('ajv');
22
+
23
+ /* Fetch in the other needed components for the this Adaptor */
24
+ const PropUtilCl = require('@itentialopensource/adapter-utils').PropertyUtility;
25
+ const RequestHandlerCl = require('@itentialopensource/adapter-utils').RequestHandler;
26
+
27
+ const entitiesToDB = require(path.join(__dirname, 'utils/entitiesToDB'));
28
+ const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
29
+ const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
30
+
31
+ let propUtil = null;
32
+
33
+ /*
34
+ * INTERNAL FUNCTION: force fail the adapter - generally done to cause restart
35
+ */
36
+ function forceFail(packChg) {
37
+ if (packChg !== undefined && packChg !== null && packChg === true) {
38
+ execSync(`rm -rf ${__dirname}/node modules`, { encoding: 'utf-8' });
39
+ execSync(`rm -rf ${__dirname}/package-lock.json`, { encoding: 'utf-8' });
40
+ execSync('npm install', { encoding: 'utf-8' });
41
+ }
42
+ log.error('NEED TO RESTART ADAPTER - FORCE FAIL');
43
+ const errorObj = {
44
+ origin: 'adapter-forceFail',
45
+ type: 'Force Fail so adapter will restart',
46
+ vars: []
47
+ };
48
+ setTimeout(() => {
49
+ throw new Error(JSON.stringify(errorObj));
50
+ }, 1000);
51
+ }
52
+
53
+ /*
54
+ * INTERNAL FUNCTION: update the action.json
55
+ */
56
+ function updateAction(entityPath, action, changes) {
57
+ // if the action file does not exist - error
58
+ const actionFile = path.join(entityPath, '/action.json');
59
+ if (!fs.existsSync(actionFile)) {
60
+ return 'Missing Action File';
61
+ }
62
+
63
+ // read in the file as a json object
64
+ const ajson = require(path.resolve(entityPath, 'action.json'));
65
+ let chgAct = {};
66
+
67
+ // get the action we need to change
68
+ for (let a = 0; a < ajson.actions.length; a += 1) {
69
+ if (ajson.actions[a].name === action) {
70
+ chgAct = ajson.actions[a];
71
+ break;
72
+ }
73
+ }
74
+ // merge the changes into the desired action
75
+ chgAct = propUtil.mergeProperties(changes, chgAct);
76
+
77
+ fs.writeFileSync(actionFile, JSON.stringify(ajson, null, 2));
78
+ return null;
79
+ }
80
+
81
+ /*
82
+ * INTERNAL FUNCTION: update the schema file
83
+ */
84
+ function updateSchema(entityPath, configFile, changes) {
85
+ // if the schema file does not exist - error
86
+ const schemaFile = path.join(entityPath, `/${configFile}`);
87
+ if (!fs.existsSync(schemaFile)) {
88
+ return 'Missing Schema File';
89
+ }
90
+
91
+ // read in the file as a json object
92
+ let schema = require(path.resolve(entityPath, configFile));
93
+
94
+ // merge the changes into the schema file
95
+ schema = propUtil.mergeProperties(changes, schema);
96
+
97
+ fs.writeFileSync(schemaFile, JSON.stringify(schema, null, 2));
98
+ return null;
99
+ }
100
+
101
+ /*
102
+ * INTERNAL FUNCTION: update the mock data file
103
+ */
104
+ function updateMock(mockPath, configFile, changes) {
105
+ // if the mock file does not exist - create it
106
+ const mockFile = path.join(mockPath, `/${configFile}`);
107
+ if (!fs.existsSync(mockFile)) {
108
+ const newMock = {};
109
+ fs.writeFileSync(mockFile, JSON.stringify(newMock, null, 2));
110
+ }
111
+
112
+ // read in the file as a json object
113
+ let mock = require(path.resolve(mockPath, configFile));
114
+
115
+ // merge the changes into the mock file
116
+ mock = propUtil.mergeProperties(changes, mock);
117
+
118
+ fs.writeFileSync(mockFile, JSON.stringify(mock, null, 2));
119
+ return null;
120
+ }
121
+
122
+ /*
123
+ * INTERNAL FUNCTION: update the package dependencies
124
+ */
125
+ function updatePackage(changes) {
126
+ // if the schema file does not exist - error
127
+ const packFile = path.join(__dirname, '/package.json');
128
+ if (!fs.existsSync(packFile)) {
129
+ return 'Missing Pacakge File';
130
+ }
131
+
132
+ // read in the file as a json object
133
+ const pack = require(path.resolve(__dirname, 'package.json'));
134
+
135
+ // only certain changes are allowed
136
+ if (changes.dependencies) {
137
+ const keys = Object.keys(changes.dependencies);
138
+
139
+ for (let k = 0; k < keys.length; k += 1) {
140
+ pack.dependencies[keys[k]] = changes.dependencies[keys[k]];
141
+ }
142
+ }
143
+
144
+ fs.writeFileSync(packFile, JSON.stringify(pack, null, 2));
145
+ return null;
146
+ }
147
+
148
+ /*
149
+ * INTERNAL FUNCTION: get data from source(s) - nested
150
+ */
151
+ function getDataFromSources(loopField, sources) {
152
+ let fieldValue = loopField;
153
+
154
+ // go through the sources to find the field
155
+ for (let s = 0; s < sources.length; s += 1) {
156
+ // find the field value using jsonquery
157
+ const nestedValue = jsonQuery(loopField, { data: sources[s] }).value;
158
+
159
+ // if we found in source - set and no need to check other sources
160
+ if (nestedValue) {
161
+ fieldValue = nestedValue;
162
+ break;
163
+ }
164
+ }
165
+
166
+ return fieldValue;
167
+ }
168
+
169
+ /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
170
+ /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
171
+ class AdapterBase extends EventEmitterCl {
172
+ /**
173
+ * [System] Adapter
174
+ * @constructor
175
+ */
176
+ constructor(prongid, properties) {
177
+ // Instantiate the EventEmitter super class
178
+ super();
179
+
180
+ // IAP home directory injected by core when running the adapter within IAP
181
+ [, , , process.env.iap_home] = process.argv;
182
+
183
+ try {
184
+ // Capture the adapter id
185
+ this.id = prongid;
186
+ this.propUtilInst = new PropUtilCl(prongid, __dirname);
187
+ propUtil = this.propUtilInst;
188
+ this.initProps = properties;
189
+ this.alive = false;
190
+ this.healthy = false;
191
+ this.suspended = false;
192
+ this.suspendMode = 'pause';
193
+ this.caching = false;
194
+ this.repeatCacheCount = 0;
195
+ this.allowFailover = 'AD.300';
196
+ this.noFailover = 'AD.500';
197
+
198
+ // set up the properties I care about
199
+ this.refreshProperties(properties);
200
+
201
+ // Instantiate the other components for this Adapter
202
+ this.requestHandlerInst = new RequestHandlerCl(this.id, this.allProps, __dirname);
203
+ } catch (e) {
204
+ // handle any exception
205
+ const origin = `${this.id}-adapterBase-constructor`;
206
+ log.error(`${origin}: Adapter may not have started properly. ${e}`);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * @callback healthCallback
212
+ * @param {Object} result - the result of the get request (contains an id and a status)
213
+ */
214
+ /**
215
+ * @callback getCallback
216
+ * @param {Object} result - the result of the get request (entity/ies)
217
+ * @param {String} error - any error that occured
218
+ */
219
+ /**
220
+ * @callback createCallback
221
+ * @param {Object} item - the newly created entity
222
+ * @param {String} error - any error that occured
223
+ */
224
+ /**
225
+ * @callback updateCallback
226
+ * @param {String} status - the status of the update action
227
+ * @param {String} error - any error that occured
228
+ */
229
+ /**
230
+ * @callback deleteCallback
231
+ * @param {String} status - the status of the delete action
232
+ * @param {String} error - any error that occured
233
+ */
234
+
235
+ /**
236
+ * refreshProperties is used to set up all of the properties for the connector.
237
+ * It allows properties to be changed later by simply calling refreshProperties rather
238
+ * than having to restart the connector.
239
+ *
240
+ * @function refreshProperties
241
+ * @param {Object} properties - an object containing all of the properties
242
+ * @param {boolean} init - are we initializing -- is so no need to refresh throtte engine
243
+ */
244
+ refreshProperties(properties) {
245
+ const meth = 'adapterBase-refreshProperties';
246
+ const origin = `${this.id}-${meth}`;
247
+ log.trace(origin);
248
+
249
+ try {
250
+ // Read the properties schema from the file system
251
+ const propertiesSchema = JSON.parse(fs.readFileSync(path.join(__dirname, 'propertiesSchema.json'), 'utf-8'));
252
+
253
+ // add any defaults to the data
254
+ const defProps = this.propUtilInst.setDefaults(propertiesSchema);
255
+ this.allProps = this.propUtilInst.mergeProperties(properties, defProps);
256
+
257
+ // validate the entity against the schema
258
+ const ajvInst = new AjvCl();
259
+ const validate = ajvInst.compile(propertiesSchema);
260
+ const result = validate(this.allProps);
261
+
262
+ // if invalid properties throw an error
263
+ if (!result) {
264
+ if (this.requestHandlerInst) {
265
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Properties', [JSON.stringify(validate.errors)], null, null, null);
266
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
267
+ throw new Error(JSON.stringify(errorObj));
268
+ } else {
269
+ log.error(`${origin}: ${JSON.stringify(validate.errors)}`);
270
+ throw new Error(`${origin}: ${JSON.stringify(validate.errors)}`);
271
+ }
272
+ }
273
+
274
+ // properties that this code cares about
275
+ this.healthcheckType = this.allProps.healthcheck.type;
276
+ this.healthcheckInterval = this.allProps.healthcheck.frequency;
277
+ this.healthcheckQuery = this.allProps.healthcheck.query_object;
278
+
279
+ // set the failover codes from properties
280
+ if (this.allProps.request.failover_codes) {
281
+ if (Array.isArray(this.allProps.request.failover_codes)) {
282
+ this.failoverCodes = this.allProps.request.failover_codes;
283
+ } else {
284
+ this.failoverCodes = [this.allProps.request.failover_codes];
285
+ }
286
+ } else {
287
+ this.failoverCodes = [];
288
+ }
289
+
290
+ // set the caching flag from properties
291
+ if (this.allProps.cache_location) {
292
+ if (this.allProps.cache_location === 'redis' || this.allProps.cache_location === 'local') {
293
+ this.caching = true;
294
+ }
295
+ }
296
+
297
+ // if this is truly a refresh and we have a request handler, refresh it
298
+ if (this.requestHandlerInst) {
299
+ this.requestHandlerInst.refreshProperties(properties);
300
+ }
301
+ } catch (e) {
302
+ log.error(`${origin}: Properties may not have been set properly. ${e}`);
303
+ }
304
+ }
305
+
306
+ /**
307
+ * @summary Connect function is used during Pronghorn startup to provide instantiation feedback.
308
+ *
309
+ * @function connect
310
+ */
311
+ connect() {
312
+ const origin = `${this.id}-adapterBase-connect`;
313
+ log.trace(origin);
314
+
315
+ // initially set as off
316
+ this.emit('OFFLINE', { id: this.id });
317
+ this.alive = true;
318
+
319
+ // if there is no healthcheck just change the emit to ONLINE
320
+ // We do not recommend no healthcheck!!!
321
+ if (this.healthcheckType === 'none') {
322
+ log.error(`${origin}: Waiting 1 Seconds to emit Online`);
323
+ setTimeout(() => {
324
+ this.emit('ONLINE', { id: this.id });
325
+ this.healthy = true;
326
+ }, 1000);
327
+ }
328
+
329
+ // is the healthcheck only suppose to run on startup
330
+ // (intermittent runs on startup and after that)
331
+ if (this.healthcheckType === 'startup' || this.healthcheckType === 'intermittent') {
332
+ // run an initial healthcheck
333
+ this.healthCheck(null, (status) => {
334
+ log.spam(`${origin}: ${status}`);
335
+ });
336
+ }
337
+
338
+ // is the healthcheck suppose to run intermittently
339
+ if (this.healthcheckType === 'intermittent') {
340
+ // run the healthcheck in an interval
341
+ setInterval(() => {
342
+ // try to see if mongo is available
343
+ this.healthCheck(null, (status) => {
344
+ log.spam(`${origin}: ${status}`);
345
+ });
346
+ }, this.healthcheckInterval);
347
+ }
348
+ }
349
+
350
+ /**
351
+ * @summary HealthCheck function is used to provide Pronghorn the status of this adapter.
352
+ *
353
+ * @function healthCheck
354
+ */
355
+ healthCheck(reqObj, callback) {
356
+ const origin = `${this.id}-adapterBase-healthCheck`;
357
+ log.trace(origin);
358
+
359
+ // if there is healthcheck query_object property, it needs to be added to the adapter
360
+ let myRequest = reqObj;
361
+ if (this.healthcheckQuery && Object.keys(this.healthcheckQuery).length > 0) {
362
+ if (myRequest && myRequest.uriQuery) {
363
+ myRequest.uriQuery = { ...myRequest.uriQuery, ...this.healthcheckQuery };
364
+ } else if (myRequest) {
365
+ myRequest.uriQuery = this.healthcheckQuery;
366
+ } else {
367
+ myRequest = {
368
+ uriQuery: this.healthcheckQuery
369
+ };
370
+ }
371
+ }
372
+
373
+ // call to the healthcheck in connector
374
+ return this.requestHandlerInst.identifyHealthcheck(myRequest, (res, error) => {
375
+ // unhealthy
376
+ if (error) {
377
+ // if we were healthy, toggle health
378
+ if (this.healthy) {
379
+ this.emit('OFFLINE', { id: this.id });
380
+ this.emit('DEGRADED', { id: this.id });
381
+ this.healthy = false;
382
+ if (typeof error === 'object') {
383
+ log.error(`${origin}: HEALTH CHECK - Error ${JSON.stringify(error)}`);
384
+ } else {
385
+ log.error(`${origin}: HEALTH CHECK - Error ${error}`);
386
+ }
387
+ } else if (typeof error === 'object') {
388
+ // still log but set the level to trace
389
+ log.trace(`${origin}: HEALTH CHECK - Still Errors ${JSON.stringify(error)}`);
390
+ } else {
391
+ log.trace(`${origin}: HEALTH CHECK - Still Errors ${error}`);
392
+ }
393
+
394
+ return callback(false);
395
+ }
396
+
397
+ // if we were unhealthy, toggle health
398
+ if (!this.healthy) {
399
+ this.emit('FIXED', { id: this.id });
400
+ this.emit('ONLINE', { id: this.id });
401
+ this.healthy = true;
402
+ log.info(`${origin}: HEALTH CHECK SUCCESSFUL`);
403
+ } else {
404
+ // still log but set the level to trace
405
+ log.trace(`${origin}: HEALTH CHECK STILL SUCCESSFUL`);
406
+ }
407
+
408
+ return callback(true);
409
+ });
410
+ }
411
+
412
+ /**
413
+ * getAllFunctions is used to get all of the exposed function in the adapter
414
+ *
415
+ * @function getAllFunctions
416
+ */
417
+ getAllFunctions() {
418
+ let myfunctions = [];
419
+ let obj = this;
420
+
421
+ // find the functions in this class
422
+ do {
423
+ const l = Object.getOwnPropertyNames(obj)
424
+ .concat(Object.getOwnPropertySymbols(obj).map((s) => s.toString()))
425
+ .sort()
426
+ .filter((p, i, arr) => typeof obj[p] === 'function' && p !== 'constructor' && (i === 0 || p !== arr[i - 1]) && myfunctions.indexOf(p) === -1);
427
+ myfunctions = myfunctions.concat(l);
428
+ }
429
+ while (
430
+ (obj = Object.getPrototypeOf(obj)) && Object.getPrototypeOf(obj)
431
+ );
432
+
433
+ return myfunctions;
434
+ }
435
+
436
+ /**
437
+ * checkActionFiles is used to update the validation of the action files.
438
+ *
439
+ * @function checkActionFiles
440
+ */
441
+ checkActionFiles() {
442
+ const origin = `${this.id}-adapterBase-checkActionFiles`;
443
+ log.trace(origin);
444
+
445
+ // validate the action files for the adapter
446
+ try {
447
+ return this.requestHandlerInst.checkActionFiles();
448
+ } catch (e) {
449
+ return ['Exception increase log level'];
450
+ }
451
+ }
452
+
453
+ /**
454
+ * checkProperties is used to validate the adapter properties.
455
+ *
456
+ * @function checkProperties
457
+ * @param {Object} properties - an object containing all of the properties
458
+ */
459
+ checkProperties(properties) {
460
+ const origin = `${this.myid}-adapterBase-checkProperties`;
461
+ log.trace(origin);
462
+
463
+ // validate the properties for the adapter
464
+ try {
465
+ return this.requestHandlerInst.checkProperties(properties);
466
+ } catch (e) {
467
+ return { exception: 'Exception increase log level' };
468
+ }
469
+ }
470
+
471
+ /**
472
+ * @summary Takes in property text and an encoding/encryption and returns the resulting
473
+ * encoded/encrypted string
474
+ *
475
+ * @function encryptProperty
476
+ * @param {String} property - the property to encrypt
477
+ * @param {String} technique - the technique to use to encrypt
478
+ *
479
+ * @param {Callback} callback - a callback function to return the result
480
+ * Encrypted String or the Error
481
+ */
482
+ encryptProperty(property, technique, callback) {
483
+ const origin = `${this.id}-adapterBase-encryptProperty`;
484
+ log.trace(origin);
485
+
486
+ // Make the call -
487
+ // encryptProperty(property, technique, callback)
488
+ return this.requestHandlerInst.encryptProperty(property, technique, callback);
489
+ }
490
+
491
+ /**
492
+ * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
493
+ * @param {array} ignoreThese - additional methods to ignore (optional)
494
+ *
495
+ * @function iapGetAdapterWorkflowFunctions
496
+ */
497
+ iapGetAdapterWorkflowFunctions(ignoreThese) {
498
+ const myfunctions = this.getAllFunctions();
499
+ const wffunctions = [];
500
+
501
+ // remove the functions that should not be in a Workflow
502
+ for (let m = 0; m < myfunctions.length; m += 1) {
503
+ if (myfunctions[m] === 'addEntityCache') {
504
+ // got to the second tier (adapterBase)
505
+ break;
506
+ }
507
+ if (!(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
508
+ let found = false;
509
+ if (ignoreThese && Array.isArray(ignoreThese)) {
510
+ for (let i = 0; i < ignoreThese.length; i += 1) {
511
+ if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
512
+ found = true;
513
+ }
514
+ }
515
+ }
516
+ if (!found) {
517
+ wffunctions.push(myfunctions[m]);
518
+ }
519
+ }
520
+ }
521
+
522
+ return wffunctions;
523
+ }
524
+
525
+ /**
526
+ * iapUpdateAdapterConfiguration is used to update any of the adapter configuration files. This
527
+ * allows customers to make changes to adapter configuration without having to be on the
528
+ * file system.
529
+ *
530
+ * @function iapUpdateAdapterConfiguration
531
+ * @param {string} configFile - the name of the file being updated (required)
532
+ * @param {Object} changes - an object containing all of the changes = formatted like the configuration file (required)
533
+ * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
534
+ * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
535
+ * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
536
+ * @param {Callback} callback - The results of the call
537
+ */
538
+ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
539
+ const meth = 'adapterBase-iapUpdateAdapterConfiguration';
540
+ const origin = `${this.id}-${meth}`;
541
+ log.trace(origin);
542
+
543
+ // verify the parameters are valid
544
+ if (changes === undefined || changes === null || typeof changes !== 'object'
545
+ || Object.keys(changes).length === 0) {
546
+ const result = {
547
+ response: 'No configuration updates to make'
548
+ };
549
+ log.info(result.response);
550
+ return callback(result, null);
551
+ }
552
+ if (configFile === undefined || configFile === null || configFile === '') {
553
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['configFile'], null, null, null);
554
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
555
+ return callback(null, errorObj);
556
+ }
557
+
558
+ // take action based on configFile being changed
559
+ if (configFile === 'package.json') {
560
+ const pres = updatePackage(changes);
561
+ if (pres) {
562
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${pres}`, [], null, null, null);
563
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
564
+ return callback(null, errorObj);
565
+ }
566
+ const result = {
567
+ response: 'Package updates completed - restarting adapter'
568
+ };
569
+ log.info(result.response);
570
+ forceFail(true);
571
+ return callback(result, null);
572
+ }
573
+ if (entity === undefined || entity === null || entity === '') {
574
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Unsupported Configuration Change or Missing Entity', [], null, null, null);
575
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
576
+ return callback(null, errorObj);
577
+ }
578
+
579
+ // this means we are changing an entity file so type is required
580
+ if (type === undefined || type === null || type === '') {
581
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['type'], null, null, null);
582
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
583
+ return callback(null, errorObj);
584
+ }
585
+
586
+ // if the entity does not exist - error
587
+ const epath = `${__dirname}/entities/${entity}`;
588
+ if (!fs.existsSync(epath)) {
589
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Invalid Entity - ${entity}`, [], null, null, null);
590
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
591
+ return callback(null, errorObj);
592
+ }
593
+
594
+ // take action based on type of file being changed
595
+ if (type === 'action') {
596
+ // BACKUP???
597
+ const ares = updateAction(epath, action, changes);
598
+ if (ares) {
599
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${ares}`, [], null, null, null);
600
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
601
+ return callback(null, errorObj);
602
+ }
603
+ // AJV CHECK???
604
+ // RESTORE IF NEEDED???
605
+ const result = {
606
+ response: `Action updates completed to entity: ${entity} - ${action}`
607
+ };
608
+ log.info(result.response);
609
+ return callback(result, null);
610
+ }
611
+ if (type === 'schema') {
612
+ const sres = updateSchema(epath, configFile, changes);
613
+ if (sres) {
614
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${sres}`, [], null, null, null);
615
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
616
+ return callback(null, errorObj);
617
+ }
618
+ const result = {
619
+ response: `Schema updates completed to entity: ${entity} - ${configFile}`
620
+ };
621
+ log.info(result.response);
622
+ return callback(result, null);
623
+ }
624
+ if (type === 'mock') {
625
+ // if the mock directory does not exist - error
626
+ const mpath = `${__dirname}/entities/${entity}/mockdatafiles`;
627
+ if (!fs.existsSync(mpath)) {
628
+ fs.mkdirSync(mpath);
629
+ }
630
+
631
+ const mres = updateMock(mpath, configFile, changes);
632
+ if (mres) {
633
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
634
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
635
+ return callback(null, errorObj);
636
+ }
637
+ const result = {
638
+ response: `Mock data updates completed to entity: ${entity} - ${configFile}`
639
+ };
640
+ log.info(result.response);
641
+ return callback(result, null);
642
+ }
643
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: Unsupported Type - ${type}`, [], null, null, null);
644
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
645
+ return callback(null, errorObj);
646
+ }
647
+
648
+ /**
649
+ * See if the API path provided is found in this adapter
650
+ *
651
+ * @function iapFindAdapterPath
652
+ * @param {string} apiPath - the api path to check on
653
+ * @param {Callback} callback - The results of the call
654
+ */
655
+ iapFindAdapterPath(apiPath, callback) {
656
+ const result = {
657
+ apiPath
658
+ };
659
+
660
+ // verify the path was provided
661
+ if (!apiPath) {
662
+ log.error('NO API PATH PROVIDED!');
663
+ result.found = false;
664
+ result.message = 'NO PATH PROVIDED!';
665
+ return callback(null, result);
666
+ }
667
+
668
+ // make sure the entities directory exists
669
+ const entitydir = path.join(__dirname, 'entities');
670
+ if (!fs.statSync(entitydir).isDirectory()) {
671
+ log.error('Could not find the entities directory');
672
+ result.found = false;
673
+ result.message = 'Could not find the entities directory';
674
+ return callback(null, result);
675
+ }
676
+
677
+ const entities = fs.readdirSync(entitydir);
678
+ const fitems = [];
679
+
680
+ // need to go through each entity in the entities directory
681
+ for (let e = 0; e < entities.length; e += 1) {
682
+ // make sure the entity is a directory - do not care about extra files
683
+ // only entities (dir)
684
+ if (fs.statSync(`${entitydir}/${entities[e]}`).isDirectory()) {
685
+ // see if the action file exists in the entity
686
+ if (fs.existsSync(`${entitydir}/${entities[e]}/action.json`)) {
687
+ // Read the entity actions from the file system
688
+ const actions = require(`${entitydir}/${entities[e]}/action.json`);
689
+
690
+ // go through all of the actions set the appropriate info in the newActions
691
+ for (let a = 0; a < actions.actions.length; a += 1) {
692
+ if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
693
+ log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
694
+ log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
695
+ const fitem = {
696
+ entity: entities[e],
697
+ action: actions.actions[a].name,
698
+ method: actions.actions[a].method,
699
+ path: actions.actions[a].entitypath
700
+ };
701
+ fitems.push(fitem);
702
+ }
703
+ }
704
+ } else {
705
+ log.error(`Could not find entities ${entities[e]} action.json file`);
706
+ result.found = false;
707
+ result.message = `Could not find entities ${entities[e]} action.json file`;
708
+ return callback(null, result);
709
+ }
710
+ } else {
711
+ log.error(`Could not find entities ${entities[e]} directory`);
712
+ result.found = false;
713
+ result.message = `Could not find entities ${entities[e]} directory`;
714
+ return callback(null, result);
715
+ }
716
+ }
717
+
718
+ if (fitems.length === 0) {
719
+ log.info('PATH NOT FOUND!');
720
+ result.found = false;
721
+ result.message = 'API PATH NOT FOUND!';
722
+ return callback(null, result);
723
+ }
724
+
725
+ result.foundIn = fitems;
726
+ result.found = true;
727
+ result.message = 'API PATH FOUND!';
728
+ return callback(result, null);
729
+ }
730
+
731
+ /**
732
+ * @summary Suspends the adapter
733
+ * @param {Callback} callback - The adapater suspension status
734
+ * @function iapSuspendAdapter
735
+ */
736
+ iapSuspendAdapter(mode, callback) {
737
+ const origin = `${this.id}-adapterBase-iapSuspendAdapter`;
738
+ if (this.suspended) {
739
+ throw new Error(`${origin}: Adapter is already suspended`);
740
+ }
741
+ try {
742
+ this.suspended = true;
743
+ this.suspendMode = mode;
744
+ if (this.suspendMode === 'pause') {
745
+ const props = JSON.parse(JSON.stringify(this.initProps));
746
+ // To suspend adapter, enable throttling and set concurrent max to 0
747
+ props.throttle.throttle_enabled = true;
748
+ props.throttle.concurrent_max = 0;
749
+ this.refreshProperties(props);
750
+ }
751
+ return callback({ suspended: true });
752
+ } catch (error) {
753
+ return callback(null, error);
754
+ }
755
+ }
756
+
757
+ /**
758
+ * @summary Unsuspends the adapter
759
+ * @param {Callback} callback - The adapater suspension status
760
+ *
761
+ * @function iapUnsuspendAdapter
762
+ */
763
+ iapUnsuspendAdapter(callback) {
764
+ const origin = `${this.id}-adapterBase-iapUnsuspendAdapter`;
765
+ if (!this.suspended) {
766
+ throw new Error(`${origin}: Adapter is not suspended`);
767
+ }
768
+ if (this.suspendMode === 'pause') {
769
+ const props = JSON.parse(JSON.stringify(this.initProps));
770
+ // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
771
+ props.throttle.throttle_enabled = true;
772
+ props.throttle.concurrent_max = 1;
773
+ this.refreshProperties(props);
774
+ setTimeout(() => {
775
+ this.getQueue((q, error) => {
776
+ // console.log("Items in queue: " + String(q.length))
777
+ if (q.length === 0) {
778
+ // if queue is empty, return to initial properties state
779
+ this.refreshProperties(this.initProps);
780
+ this.suspended = false;
781
+ return callback({ suspended: false });
782
+ }
783
+ // recursive call to check queue again every second
784
+ return this.iapUnsuspendAdapter(callback);
785
+ });
786
+ }, 1000);
787
+ } else {
788
+ this.suspended = false;
789
+ callback({ suspend: false });
790
+ }
791
+ }
792
+
793
+ /**
794
+ * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
795
+ *
796
+ * @function iapGetAdapterQueue
797
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
798
+ */
799
+ iapGetAdapterQueue(callback) {
800
+ const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
801
+ log.trace(origin);
802
+
803
+ return this.requestHandlerInst.getQueue(callback);
804
+ }
805
+
806
+ /**
807
+ * @summary runs troubleshoot scripts for adapter
808
+ *
809
+ * @function iapTroubleshootAdapter
810
+ * @param {Object} props - the connection, healthcheck and authentication properties
811
+ * @param {boolean} persistFlag - whether the adapter properties should be updated
812
+ * @param {Adapter} adapter - adapter instance to troubleshoot
813
+ * @param {Callback} callback - callback function to return troubleshoot results
814
+ */
815
+ async iapTroubleshootAdapter(props, persistFlag, adapter, callback) {
816
+ try {
817
+ const result = await troubleshootingAdapter.troubleshoot(props, false, persistFlag, adapter);
818
+ if (result.healthCheck && result.connectivity.failCount === 0 && result.basicGet.failCount === 0) {
819
+ return callback(result);
820
+ }
821
+ return callback(null, result);
822
+ } catch (error) {
823
+ return callback(null, error);
824
+ }
825
+ }
826
+
827
+ /**
828
+ * @summary runs healthcheck script for adapter
829
+ *
830
+ * @function iapRunAdapterHealthcheck
831
+ * @param {Adapter} adapter - adapter instance to troubleshoot
832
+ * @param {Callback} callback - callback function to return healthcheck status
833
+ */
834
+ async iapRunAdapterHealthcheck(adapter, callback) {
835
+ try {
836
+ const result = await tbUtils.healthCheck(adapter);
837
+ if (result) {
838
+ return callback(result);
839
+ }
840
+ return callback(null, result);
841
+ } catch (error) {
842
+ return callback(null, error);
843
+ }
844
+ }
845
+
846
+ /**
847
+ * @summary runs connectivity check script for adapter
848
+ *
849
+ * @function iapRunAdapterConnectivity
850
+ * @param {Adapter} adapter - adapter instance to troubleshoot
851
+ * @param {Callback} callback - callback function to return connectivity status
852
+ */
853
+ async iapRunAdapterConnectivity(callback) {
854
+ try {
855
+ const { serviceItem } = await tbUtils.getAdapterConfig();
856
+ const { host } = serviceItem.properties.properties;
857
+ const result = tbUtils.runConnectivity(host, false);
858
+ if (result.failCount > 0) {
859
+ return callback(null, result);
860
+ }
861
+ return callback(result);
862
+ } catch (error) {
863
+ return callback(null, error);
864
+ }
865
+ }
866
+
867
+ /**
868
+ * @summary runs basicGet script for adapter
869
+ *
870
+ * @function iapRunAdapterBasicGet
871
+ * @param {Callback} callback - callback function to return basicGet result
872
+ */
873
+ iapRunAdapterBasicGet(callback) {
874
+ try {
875
+ const result = tbUtils.runBasicGet(false);
876
+ if (result.failCount > 0) {
877
+ return callback(null, result);
878
+ }
879
+ return callback(result);
880
+ } catch (error) {
881
+ return callback(null, error);
882
+ }
883
+ }
884
+
885
+ /**
886
+ * @summary moves entities to mongo database
887
+ *
888
+ * @function iapMoveAdapterEntitiesToDB
889
+ *
890
+ * @return {Callback} - containing the response from the mongo transaction
891
+ */
892
+ async iapMoveAdapterEntitiesToDB(callback) {
893
+ const meth = 'adapterBase-iapMoveAdapterEntitiesToDB';
894
+ const origin = `${this.id}-${meth}`;
895
+ log.trace(origin);
896
+
897
+ try {
898
+ const result = await entitiesToDB.moveEntitiesToDB(__dirname, { pronghornProps: this.allProps, id: this.id });
899
+ return callback(result, null);
900
+ } catch (err) {
901
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, err);
902
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
903
+ return callback(null, err.message);
904
+ }
905
+ }
906
+
907
+ /**
908
+ * @summary take the entities and add them to the cache
909
+ *
910
+ * @function addEntityCache
911
+ * @param {String} entityType - the type of the entities
912
+ * @param {Array} data - the list of entities
913
+ * @param {String} key - unique key for the entities
914
+ *
915
+ * @param {Callback} callback - An array of whether the adapter can has the
916
+ * desired capability or an error
917
+ */
918
+ addEntityCache(entityType, entities, key, callback) {
919
+ const meth = 'adapterBase-addEntityCache';
920
+ const origin = `${this.id}-${meth}`;
921
+ log.trace(origin);
922
+
923
+ // list containing the items to add to the cache
924
+ const entityIds = [];
925
+
926
+ if (entities && Object.hasOwnProperty.call(entities, 'response')
927
+ && Array.isArray(entities.response)) {
928
+ for (let e = 0; e < entities.response.length; e += 1) {
929
+ entityIds.push(entities.response[e][key]);
930
+ }
931
+ }
932
+
933
+ // add the entities to the cache
934
+ return this.requestHandlerInst.addEntityCache(entityType, entityIds, (loaded, error) => {
935
+ if (error) {
936
+ return callback(null, error);
937
+ }
938
+ if (!loaded) {
939
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', [entityType], null, null, null);
940
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
941
+ return callback(null, errorObj);
942
+ }
943
+
944
+ return callback(loaded);
945
+ });
946
+ }
947
+
948
+ /**
949
+ * @summary sees if the entity is in the entity list or not
950
+ *
951
+ * @function entityInList
952
+ * @param {String/Array} entityId - the specific entity we are looking for
953
+ * @param {Array} data - the list of entities
954
+ *
955
+ * @param {Callback} callback - An array of whether the adapter can has the
956
+ * desired capability or an error
957
+ */
958
+ entityInList(entityId, data) {
959
+ const origin = `${this.id}-adapterBase-entityInList`;
960
+ log.trace(origin);
961
+
962
+ // need to check on the entities that were passed in
963
+ if (Array.isArray(entityId)) {
964
+ const resEntity = [];
965
+
966
+ for (let e = 0; e < entityId.length; e += 1) {
967
+ if (data.includes(entityId[e])) {
968
+ resEntity.push(true);
969
+ } else {
970
+ resEntity.push(false);
971
+ }
972
+ }
973
+
974
+ return resEntity;
975
+ }
976
+
977
+ // does the entity list include the specific entity
978
+ return [data.includes(entityId)];
979
+ }
980
+
981
+ /**
982
+ * @summary prepare results for verify capability so they are true/false
983
+ *
984
+ * @function capabilityResults
985
+ * @param {Array} results - the results from the capability check
986
+ *
987
+ * @param {Callback} callback - An array of whether the adapter can has the
988
+ * desired capability or an error
989
+ */
990
+ capabilityResults(results, callback) {
991
+ const meth = 'adapterBase-capabilityResults';
992
+ const origin = `${this.id}-${meth}`;
993
+ log.trace(origin);
994
+ let locResults = results;
995
+
996
+ if (locResults && locResults[0] === 'needupdate') {
997
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', ['unknown'], null, null, null);
998
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
999
+ this.repeatCacheCount += 1;
1000
+ return callback(null, errorObj);
1001
+ }
1002
+
1003
+ // if an error occured, return the error
1004
+ if (locResults && locResults[0] === 'error') {
1005
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Error Verifying Entity Cache', null, null, null, null);
1006
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1007
+ return callback(null, errorObj);
1008
+ }
1009
+
1010
+ // go through the response and change to true/false
1011
+ if (locResults) {
1012
+ // if not an array, just convert the return
1013
+ if (!Array.isArray(locResults)) {
1014
+ if (locResults === 'found') {
1015
+ locResults = [true];
1016
+ } else {
1017
+ locResults = [false];
1018
+ }
1019
+ } else {
1020
+ const temp = [];
1021
+
1022
+ // go through each element in the array to convert
1023
+ for (let r = 0; r < locResults.length; r += 1) {
1024
+ if (locResults[r] === 'found') {
1025
+ temp.push(true);
1026
+ } else {
1027
+ temp.push(false);
1028
+ }
1029
+ }
1030
+ locResults = temp;
1031
+ }
1032
+ }
1033
+
1034
+ // return the results
1035
+ return callback(locResults);
1036
+ }
1037
+
1038
+ /**
1039
+ * @summary Provides a way for the adapter to tell north bound integrations
1040
+ * all of the capabilities for the current adapter
1041
+ *
1042
+ * @function getAllCapabilities
1043
+ *
1044
+ * @return {Array} - containing the entities and the actions available on each entity
1045
+ */
1046
+ getAllCapabilities() {
1047
+ const origin = `${this.id}-adapterBase-getAllCapabilities`;
1048
+ log.trace(origin);
1049
+
1050
+ // validate the capabilities for the adapter
1051
+ try {
1052
+ return this.requestHandlerInst.getAllCapabilities();
1053
+ } catch (e) {
1054
+ return [];
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * @summary Determines if this adapter supports any in a list of entities
1060
+ *
1061
+ * @function hasEntities
1062
+ * @param {String} entityType - the entity type to check for
1063
+ * @param {Array} entityList - the list of entities we are looking for
1064
+ *
1065
+ * @param {Callback} callback - A map where the entity is the key and the
1066
+ * value is true or false
1067
+ */
1068
+ hasEntities(entityType, entityList, callback) {
1069
+ const origin = `${this.id}-adapter-hasEntities`;
1070
+ log.trace(origin);
1071
+
1072
+ switch (entityType) {
1073
+ case 'Device':
1074
+ return this.hasDevices(entityList, callback);
1075
+ default:
1076
+ return callback(null, `${this.id} does not support entity ${entityType}`);
1077
+ }
1078
+ }
1079
+
1080
+ /**
1081
+ * @summary Helper method for hasEntities for the specific device case
1082
+ *
1083
+ * @param {Array} deviceList - array of unique device identifiers
1084
+ * @param {Callback} callback - A map where the device is the key and the
1085
+ * value is true or false
1086
+ */
1087
+ hasDevices(deviceList, callback) {
1088
+ const origin = `${this.id}-adapter-hasDevices`;
1089
+ log.trace(origin);
1090
+
1091
+ const findings = deviceList.reduce((map, device) => {
1092
+ // eslint-disable-next-line no-param-reassign
1093
+ map[device] = false;
1094
+ log.debug(`In reduce: ${JSON.stringify(map)}`);
1095
+ return map;
1096
+ }, {});
1097
+ const apiCalls = deviceList.map((device) => new Promise((resolve) => {
1098
+ this.getDevice(device, (result, error) => {
1099
+ if (error) {
1100
+ log.debug(`In map error: ${JSON.stringify(device)}`);
1101
+ return resolve({ name: device, found: false });
1102
+ }
1103
+ log.debug(`In map: ${JSON.stringify(device)}`);
1104
+ return resolve({ name: device, found: true });
1105
+ });
1106
+ }));
1107
+ Promise.all(apiCalls).then((results) => {
1108
+ results.forEach((device) => {
1109
+ findings[device.name] = device.found;
1110
+ });
1111
+ log.debug(`FINDINGS: ${JSON.stringify(findings)}`);
1112
+ return callback(findings);
1113
+ }).catch((errors) => {
1114
+ log.error('Unable to do device lookup.');
1115
+ return callback(null, { code: 503, message: 'Unable to do device lookup.', error: errors });
1116
+ });
1117
+ }
1118
+
1119
+ /**
1120
+ * @summary Make one of the needed Broker calls - could be one of many
1121
+ *
1122
+ * @function iapMakeBrokerCall
1123
+ * @param {string} brokCall - the name of the broker call (required)
1124
+ * @param {object} callProps - the proeprties for the broker call (required)
1125
+ * @param {object} devResp - the device details to extract needed inputs (required)
1126
+ * @param {string} filterName - any filter to search on (required)
1127
+ *
1128
+ * @param {getCallback} callback - a callback function to return the result of the call
1129
+ */
1130
+ iapMakeBrokerCall(brokCall, callProps, devResp, filterName, callback) {
1131
+ const meth = 'adapterBase-iapMakeBrokerCall';
1132
+ const origin = `${this.id}-${meth}`;
1133
+ log.trace(origin);
1134
+
1135
+ try {
1136
+ let uriPath = '';
1137
+ let uriMethod = 'GET';
1138
+ let callQuery = {};
1139
+ let callBody = {};
1140
+ let callHeaders = {};
1141
+ let handleFail = 'fail';
1142
+ let ostypePrefix = '';
1143
+ let statusValue = 'true';
1144
+ if (callProps.path) {
1145
+ uriPath = `${callProps.path}`;
1146
+
1147
+ // make any necessary changes to the path
1148
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1149
+ const rqKeys = Object.keys(callProps.requestFields);
1150
+
1151
+ // get the field from the provided device
1152
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1153
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1154
+
1155
+ // put the value into the path - if it has been specified in the path
1156
+ uriPath = uriPath.replace(`{${rqKeys[rq]}}`, fieldValue);
1157
+ }
1158
+ }
1159
+ }
1160
+ if (callProps.method) {
1161
+ uriMethod = callProps.method;
1162
+ }
1163
+ if (callProps.query) {
1164
+ callQuery = callProps.query;
1165
+
1166
+ // go through the query params to check for variable values
1167
+ const cpKeys = Object.keys(callQuery);
1168
+ for (let cp = 0; cp < cpKeys.length; cp += 1) {
1169
+ if (callQuery[cpKeys[cp]].startsWith('{') && callQuery[cpKeys[cp]].endsWith('}')) {
1170
+ // make any necessary changes to the query params
1171
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1172
+ const rqKeys = Object.keys(callProps.requestFields);
1173
+
1174
+ // get the field from the provided device
1175
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1176
+ if (cpKeys[cp] === rqKeys[rq]) {
1177
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1178
+
1179
+ // put the value into the query - if it has been specified in the query
1180
+ callQuery[cpKeys[cp]] = fieldValue;
1181
+ }
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+ if (callProps.body) {
1188
+ callBody = callProps.body;
1189
+
1190
+ // go through the body fields to check for variable values
1191
+ const cbKeys = Object.keys(callBody);
1192
+ for (let cb = 0; cb < cbKeys.length; cb += 1) {
1193
+ if (callBody[cbKeys[cb]].startsWith('{') && callBody[cbKeys[cb]].endsWith('}')) {
1194
+ // make any necessary changes to the query params
1195
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1196
+ const rqKeys = Object.keys(callProps.requestFields);
1197
+
1198
+ // get the field from the provided device
1199
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1200
+ if (cbKeys[cb] === rqKeys[rq]) {
1201
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1202
+
1203
+ // put the value into the query - if it has been specified in the query
1204
+ callBody[cbKeys[cb]] = fieldValue;
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ }
1210
+ }
1211
+ if (callProps.headers) {
1212
+ callHeaders = callProps.headers;
1213
+
1214
+ // go through the body fields to check for variable values
1215
+ const chKeys = Object.keys(callHeaders);
1216
+ for (let ch = 0; ch < chKeys.length; ch += 1) {
1217
+ if (callHeaders[chKeys[ch]].startsWith('{') && callHeaders[chKeys[ch]].endsWith('}')) {
1218
+ // make any necessary changes to the query params
1219
+ if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1220
+ const rqKeys = Object.keys(callProps.requestFields);
1221
+
1222
+ // get the field from the provided device
1223
+ for (let rq = 0; rq < rqKeys.length; rq += 1) {
1224
+ if (chKeys[ch] === rqKeys[rq]) {
1225
+ const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1226
+
1227
+ // put the value into the query - if it has been specified in the query
1228
+ callHeaders[chKeys[ch]] = fieldValue;
1229
+ }
1230
+ }
1231
+ }
1232
+ }
1233
+ }
1234
+ }
1235
+ if (callProps.handleFailure) {
1236
+ handleFail = callProps.handleFailure;
1237
+ }
1238
+ if (callProps.responseFields && callProps.responseFields.ostypePrefix) {
1239
+ ostypePrefix = callProps.responseFields.ostypePrefix;
1240
+ }
1241
+ if (callProps.responseFields && callProps.responseFields.statusValue) {
1242
+ statusValue = callProps.responseFields.statusValue;
1243
+ }
1244
+
1245
+ // !! using Generic makes it easier on the Adapter Builder (just need to change the path)
1246
+ // !! you can also replace with a specific call if that is easier
1247
+ return this.genericAdapterRequest(uriPath, uriMethod, callQuery, callBody, callHeaders, (result, error) => {
1248
+ // if we received an error or their is no response on the results return an error
1249
+ if (error) {
1250
+ if (handleFail === 'fail') {
1251
+ return callback(null, error);
1252
+ }
1253
+ return callback({}, null);
1254
+ }
1255
+ if (!result.response) {
1256
+ if (handleFail === 'fail') {
1257
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', [brokCall], null, null, null);
1258
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1259
+ return callback(null, errorObj);
1260
+ }
1261
+ return callback({}, null);
1262
+ }
1263
+
1264
+ // get the response piece we care about from the response
1265
+ const myResult = result;
1266
+ if (callProps.responseDatakey) {
1267
+ myResult.response = jsonQuery(callProps.responseDatakey, { data: myResult.response }).value;
1268
+ }
1269
+
1270
+ // get the keys for the response fields
1271
+ let rfKeys = [];
1272
+ if (callProps.responseFields && Object.keys(callProps.responseFields).length > 0) {
1273
+ rfKeys = Object.keys(callProps.responseFields);
1274
+ }
1275
+
1276
+ // if we got an array returned (e.g. getDevicesFitered)
1277
+ if (Array.isArray(myResult.response)) {
1278
+ const listDevices = [];
1279
+ for (let a = 0; a < myResult.response.length; a += 1) {
1280
+ const thisDevice = myResult.response[a];
1281
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1282
+ if (rfKeys[rf] !== 'ostypePrefix') {
1283
+ let fieldValue = getDataFromSources(callProps.responseFields[rfKeys[rf]], [thisDevice, devResp, callProps.requestFields]);
1284
+
1285
+ // if the field is ostype - need to add prefix
1286
+ if (rfKeys[rf] === 'ostype' && typeof fieldValue === 'string') {
1287
+ fieldValue = ostypePrefix + fieldValue;
1288
+ }
1289
+ // if there is a status to set, set it
1290
+ if (rfKeys[rf] === 'status') {
1291
+ // if really looking for just a good response
1292
+ if (callProps.responseFields[rfKeys[rf]] === 'return2xx' && myResult.icode === statusValue.toString()) {
1293
+ thisDevice.isAlive = true;
1294
+ } else if (fieldValue.toString() === statusValue.toString()) {
1295
+ thisDevice.isAlive = true;
1296
+ } else {
1297
+ thisDevice.isAlive = false;
1298
+ }
1299
+ }
1300
+ // if we found a good value
1301
+ thisDevice[rfKeys[rf]] = fieldValue;
1302
+ }
1303
+ }
1304
+
1305
+ // if there is no filter - add the device to the list
1306
+ if (!filterName || filterName.length === 0) {
1307
+ listDevices.push(thisDevice);
1308
+ } else {
1309
+ // if we have to match a filter
1310
+ let found = false;
1311
+ for (let f = 0; f < filterName.length; f += 1) {
1312
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1313
+ found = true;
1314
+ break;
1315
+ }
1316
+ }
1317
+ // matching device
1318
+ if (found) {
1319
+ listDevices.push(thisDevice);
1320
+ }
1321
+ }
1322
+ }
1323
+
1324
+ // return the array of devices
1325
+ return callback(listDevices, null);
1326
+ }
1327
+
1328
+ // if this is not an array - just about everything else, just handle as a single object
1329
+ let thisDevice = myResult.response;
1330
+ for (let rf = 0; rf < rfKeys.length; rf += 1) {
1331
+ // skip ostypePrefix since it is not a field
1332
+ if (rfKeys[rf] !== 'ostypePrefix') {
1333
+ let fieldValue = getDataFromSources(callProps.responseFields[rfKeys[rf]], [thisDevice, devResp, callProps.requestFields]);
1334
+
1335
+ // if the field is ostype - need to add prefix
1336
+ if (rfKeys[rf] === 'ostype' && typeof fieldValue === 'string') {
1337
+ fieldValue = ostypePrefix + fieldValue;
1338
+ }
1339
+ // if there is a status to set, set it
1340
+ if (rfKeys[rf] === 'status') {
1341
+ // if really looking for just a good response
1342
+ if (callProps.responseFields[rfKeys[rf]] === 'return2xx' && myResult.icode === statusValue.toString()) {
1343
+ thisDevice.isAlive = true;
1344
+ } else if (fieldValue.toString() === statusValue.toString()) {
1345
+ thisDevice.isAlive = true;
1346
+ } else {
1347
+ thisDevice.isAlive = false;
1348
+ }
1349
+ }
1350
+ // if we found a good value
1351
+ thisDevice[rfKeys[rf]] = fieldValue;
1352
+ }
1353
+ }
1354
+
1355
+ // if there is a filter - check the device is in the list
1356
+ if (filterName && filterName.length > 0) {
1357
+ let found = false;
1358
+ for (let f = 0; f < filterName.length; f += 1) {
1359
+ if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1360
+ found = true;
1361
+ break;
1362
+ }
1363
+ }
1364
+ // no matching device - clear the device
1365
+ if (!found) {
1366
+ thisDevice = {};
1367
+ }
1368
+ }
1369
+
1370
+ return callback(thisDevice, null);
1371
+ });
1372
+ } catch (e) {
1373
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, e);
1374
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1375
+ return callback(null, errorObj);
1376
+ }
1377
+ }
1378
+
1379
+ /**
1380
+ * @summary Get Appliance that match the deviceName
1381
+ *
1382
+ * @function getDevice
1383
+ * @param {String} deviceName - the deviceName to find (required)
1384
+ *
1385
+ * @param {getCallback} callback - a callback function to return the result
1386
+ * (appliance) or the error
1387
+ */
1388
+ getDevice(deviceName, callback) {
1389
+ const meth = 'adapterBase-getDevice';
1390
+ const origin = `${this.id}-${meth}`;
1391
+ log.trace(origin);
1392
+
1393
+ // make sure we are set up for device broker getDevice
1394
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getDevice || this.allProps.devicebroker.getDevice.length === 0 || !this.allProps.devicebroker.getDevice[0].path) {
1395
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getDevice.path'], null, null, null);
1396
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1397
+ return callback(null, errorObj);
1398
+ }
1399
+
1400
+ /* HERE IS WHERE YOU VALIDATE DATA */
1401
+ if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1402
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1403
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1404
+ return callback(null, errorObj);
1405
+ }
1406
+
1407
+ try {
1408
+ // need to get the device so we can convert the deviceName to an id
1409
+ // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1410
+ const opts = {
1411
+ filter: {
1412
+ name: deviceName
1413
+ }
1414
+ };
1415
+ return this.getDevicesFiltered(opts, (devs, ferr) => {
1416
+ // if we received an error or their is no response on the results return an error
1417
+ if (ferr) {
1418
+ return callback(null, ferr);
1419
+ }
1420
+ if (devs.list.length < 1) {
1421
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1422
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1423
+ return callback(null, errorObj);
1424
+ }
1425
+
1426
+ const callPromises = [];
1427
+ for (let i = 0; i < this.allProps.devicebroker.getDevice.length; i += 1) {
1428
+ // Perform component calls here.
1429
+ callPromises.push(
1430
+ new Promise((resolve, reject) => {
1431
+ this.iapMakeBrokerCall('getDevice', this.allProps.devicebroker.getDevice[i], [devs.list[0]], null, (callRet, callErr) => {
1432
+ // return an error
1433
+ if (callErr) {
1434
+ reject(callErr);
1435
+ } else {
1436
+ // return the data
1437
+ resolve(callRet);
1438
+ }
1439
+ });
1440
+ })
1441
+ );
1442
+ }
1443
+
1444
+ // return an array of repsonses
1445
+ return Promise.all(callPromises).then((results) => {
1446
+ let myResult = {};
1447
+ results.forEach((result) => {
1448
+ myResult = { ...myResult, ...result };
1449
+ });
1450
+
1451
+ return callback(myResult, null);
1452
+ });
1453
+ });
1454
+ } catch (ex) {
1455
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1456
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1457
+ return callback(null, errorObj);
1458
+ }
1459
+ }
1460
+
1461
+ /**
1462
+ * @summary Get Appliances that match the filter
1463
+ *
1464
+ * @function getDevicesFiltered
1465
+ * @param {Object} options - the data to use to filter the appliances (optional)
1466
+ *
1467
+ * @param {getCallback} callback - a callback function to return the result
1468
+ * (appliances) or the error
1469
+ */
1470
+ getDevicesFiltered(options, callback) {
1471
+ const meth = 'adapterBase-getDevicesFiltered';
1472
+ const origin = `${this.id}-${meth}`;
1473
+ log.trace(origin);
1474
+
1475
+ // make sure we are set up for device broker getDevicesFiltered
1476
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getDevicesFiltered || this.allProps.devicebroker.getDevicesFiltered.length === 0 || !this.allProps.devicebroker.getDevicesFiltered[0].path) {
1477
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getDevicesFiltered.path'], null, null, null);
1478
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1479
+ return callback(null, errorObj);
1480
+ }
1481
+
1482
+ // verify the required fields have been provided
1483
+ if (options === undefined || options === null || options === '' || options.length === 0) {
1484
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['options'], null, null, null);
1485
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1486
+ return callback(null, errorObj);
1487
+ }
1488
+ log.debug(`Device Filter Options: ${JSON.stringify(options)}`);
1489
+
1490
+ try {
1491
+ // TODO - get pagination working
1492
+ // const nextToken = options.start;
1493
+ // const maxResults = options.limit;
1494
+
1495
+ // set up the filter of Device Names
1496
+ let filterName = [];
1497
+ if (options && options.filter && options.filter.name) {
1498
+ // when this hack is removed, remove the lint ignore above
1499
+ if (Array.isArray(options.filter.name)) {
1500
+ // eslint-disable-next-line prefer-destructuring
1501
+ filterName = options.filter.name;
1502
+ } else {
1503
+ filterName = [options.filter.name];
1504
+ }
1505
+ }
1506
+
1507
+ // TODO - get sort and order working
1508
+ /*
1509
+ if (options && options.sort) {
1510
+ reqObj.uriOptions.sort = JSON.stringify(options.sort);
1511
+ }
1512
+ if (options && options.order) {
1513
+ reqObj.uriOptions.order = options.order;
1514
+ }
1515
+ */
1516
+ const callPromises = [];
1517
+ for (let i = 0; i < this.allProps.devicebroker.getDevicesFiltered.length; i += 1) {
1518
+ // Perform component calls here.
1519
+ callPromises.push(
1520
+ new Promise((resolve, reject) => {
1521
+ this.iapMakeBrokerCall('getDevicesFiltered', this.allProps.devicebroker.getDevicesFiltered[i], [{ fake: 'fakedata' }], filterName, (callRet, callErr) => {
1522
+ // return an error
1523
+ if (callErr) {
1524
+ reject(callErr);
1525
+ } else {
1526
+ // return the data
1527
+ resolve(callRet);
1528
+ }
1529
+ });
1530
+ })
1531
+ );
1532
+ }
1533
+
1534
+ // return an array of repsonses
1535
+ return Promise.all(callPromises).then((results) => {
1536
+ let myResult = [];
1537
+ results.forEach((result) => {
1538
+ if (Array.isArray(result)) {
1539
+ myResult = [...myResult, ...result];
1540
+ } else if (Object.keys(result).length > 0) {
1541
+ myResult.push(result);
1542
+ }
1543
+ });
1544
+
1545
+ log.debug(`${origin}: Found #${myResult.length} devices.`);
1546
+ log.debug(`Devices: ${JSON.stringify(myResult)}`);
1547
+ return callback({ total: myResult.length, list: myResult });
1548
+ });
1549
+ } catch (ex) {
1550
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1551
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1552
+ return callback(null, errorObj);
1553
+ }
1554
+ }
1555
+
1556
+ /**
1557
+ * @summary Gets the status for the provided appliance
1558
+ *
1559
+ * @function isAlive
1560
+ * @param {String} deviceName - the deviceName of the appliance. (required)
1561
+ *
1562
+ * @param {configCallback} callback - callback function to return the result
1563
+ * (appliance isAlive) or the error
1564
+ */
1565
+ isAlive(deviceName, callback) {
1566
+ const meth = 'adapterBase-isAlive';
1567
+ const origin = `${this.id}-${meth}`;
1568
+ log.trace(origin);
1569
+
1570
+ // make sure we are set up for device broker isAlive
1571
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.isAlive || this.allProps.devicebroker.isAlive.length === 0 || !this.allProps.devicebroker.isAlive[0].path) {
1572
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.isAlive.path'], null, null, null);
1573
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1574
+ return callback(null, errorObj);
1575
+ }
1576
+
1577
+ // verify the required fields have been provided
1578
+ if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1579
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1580
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1581
+ return callback(null, errorObj);
1582
+ }
1583
+
1584
+ try {
1585
+ // need to get the device so we can convert the deviceName to an id
1586
+ // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1587
+ const opts = {
1588
+ filter: {
1589
+ name: deviceName
1590
+ }
1591
+ };
1592
+ return this.getDevicesFiltered(opts, (devs, ferr) => {
1593
+ // if we received an error or their is no response on the results return an error
1594
+ if (ferr) {
1595
+ return callback(null, ferr);
1596
+ }
1597
+ if (devs.list.length < 1) {
1598
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1599
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1600
+ return callback(null, errorObj);
1601
+ }
1602
+
1603
+ const callPromises = [];
1604
+ for (let i = 0; i < this.allProps.devicebroker.isAlive.length; i += 1) {
1605
+ // Perform component calls here.
1606
+ callPromises.push(
1607
+ new Promise((resolve, reject) => {
1608
+ this.iapMakeBrokerCall('isAlive', this.allProps.devicebroker.isAlive[i], [devs.list[0]], null, (callRet, callErr) => {
1609
+ // return an error
1610
+ if (callErr) {
1611
+ reject(callErr);
1612
+ } else {
1613
+ // return the data
1614
+ resolve(callRet);
1615
+ }
1616
+ });
1617
+ })
1618
+ );
1619
+ }
1620
+
1621
+ // return an array of repsonses
1622
+ return Promise.all(callPromises).then((results) => {
1623
+ let myResult = {};
1624
+ results.forEach((result) => {
1625
+ myResult = { ...myResult, ...result };
1626
+ });
1627
+
1628
+ let response = true;
1629
+ if (myResult.isAlive !== null && myResult.isAlive !== undefined && myResult.isAlive === false) {
1630
+ response = false;
1631
+ }
1632
+ return callback(response);
1633
+ });
1634
+ });
1635
+ } catch (ex) {
1636
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1637
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1638
+ return callback(null, errorObj);
1639
+ }
1640
+ }
1641
+
1642
+ /**
1643
+ * @summary Gets a config for the provided Appliance
1644
+ *
1645
+ * @function getConfig
1646
+ * @param {String} deviceName - the deviceName of the appliance. (required)
1647
+ * @param {String} format - the desired format of the config. (optional)
1648
+ *
1649
+ * @param {configCallback} callback - callback function to return the result
1650
+ * (appliance config) or the error
1651
+ */
1652
+ getConfig(deviceName, format, callback) {
1653
+ const meth = 'adapterBase-getConfig';
1654
+ const origin = `${this.id}-${meth}`;
1655
+ log.trace(origin);
1656
+
1657
+ // make sure we are set up for device broker getConfig
1658
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getConfig || this.allProps.devicebroker.getConfig.length === 0 || !this.allProps.devicebroker.getConfig[0].path) {
1659
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getConfig.path'], null, null, null);
1660
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1661
+ return callback(null, errorObj);
1662
+ }
1663
+
1664
+ // verify the required fields have been provided
1665
+ if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1666
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1667
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1668
+ return callback(null, errorObj);
1669
+ }
1670
+
1671
+ try {
1672
+ // need to get the device so we can convert the deviceName to an id
1673
+ // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1674
+ const opts = {
1675
+ filter: {
1676
+ name: deviceName
1677
+ }
1678
+ };
1679
+ return this.getDevicesFiltered(opts, (devs, ferr) => {
1680
+ // if we received an error or their is no response on the results return an error
1681
+ if (ferr) {
1682
+ return callback(null, ferr);
1683
+ }
1684
+ if (devs.list.length < 1) {
1685
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1686
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1687
+ return callback(null, errorObj);
1688
+ }
1689
+
1690
+ const callPromises = [];
1691
+ for (let i = 0; i < this.allProps.devicebroker.getConfig.length; i += 1) {
1692
+ // Perform component calls here.
1693
+ callPromises.push(
1694
+ new Promise((resolve, reject) => {
1695
+ this.iapMakeBrokerCall('getConfig', this.allProps.devicebroker.getConfig[i], [devs.list[0]], null, (callRet, callErr) => {
1696
+ // return an error
1697
+ if (callErr) {
1698
+ reject(callErr);
1699
+ } else {
1700
+ // return the data
1701
+ resolve(callRet);
1702
+ }
1703
+ });
1704
+ })
1705
+ );
1706
+ }
1707
+
1708
+ // return an array of repsonses
1709
+ return Promise.all(callPromises).then((results) => {
1710
+ let myResult = {};
1711
+ results.forEach((result) => {
1712
+ myResult = { ...myResult, ...result };
1713
+ });
1714
+
1715
+ // return the result
1716
+ const newResponse = {
1717
+ response: JSON.stringify(myResult, null, 2)
1718
+ };
1719
+ return callback(newResponse, null);
1720
+ });
1721
+ });
1722
+ } catch (ex) {
1723
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1724
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1725
+ return callback(null, errorObj);
1726
+ }
1727
+ }
1728
+
1729
+ /**
1730
+ * @summary Gets the device count from the system
1731
+ *
1732
+ * @function iapGetDeviceCount
1733
+ *
1734
+ * @param {getCallback} callback - callback function to return the result
1735
+ * (count) or the error
1736
+ */
1737
+ iapGetDeviceCount(callback) {
1738
+ const meth = 'adapterBase-iapGetDeviceCount';
1739
+ const origin = `${this.id}-${meth}`;
1740
+ log.trace(origin);
1741
+
1742
+ // make sure we are set up for device broker getCount
1743
+ if (!this.allProps.devicebroker || !this.allProps.devicebroker.getCount || this.allProps.devicebroker.getCount.length === 0 || !this.allProps.devicebroker.getCount[0].path) {
1744
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getCount.path'], null, null, null);
1745
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1746
+ return callback(null, errorObj);
1747
+ }
1748
+
1749
+ // verify the required fields have been provided
1750
+
1751
+ try {
1752
+ const callPromises = [];
1753
+ for (let i = 0; i < this.allProps.devicebroker.getCount.length; i += 1) {
1754
+ // Perform component calls here.
1755
+ callPromises.push(
1756
+ new Promise((resolve, reject) => {
1757
+ this.iapMakeBrokerCall('getCount', this.allProps.devicebroker.getCount[i], null, null, (callRet, callErr) => {
1758
+ // return an error
1759
+ if (callErr) {
1760
+ reject(callErr);
1761
+ } else {
1762
+ // return the data
1763
+ resolve(callRet);
1764
+ }
1765
+ });
1766
+ })
1767
+ );
1768
+ }
1769
+
1770
+ // return an array of repsonses
1771
+ return Promise.all(callPromises).then((results) => {
1772
+ let myResult = {};
1773
+ results.forEach((result) => {
1774
+ myResult = { ...myResult, ...result };
1775
+ });
1776
+
1777
+ // return the result
1778
+ return callback({ count: myResult.length });
1779
+ });
1780
+ } catch (ex) {
1781
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1782
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1783
+ return callback(null, errorObj);
1784
+ }
1785
+ }
1786
+ }
1787
+
1788
+ module.exports = AdapterBase;