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