@itentialopensource/adapter-gcp_compute 0.2.0 → 1.1.0

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 (123) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/README.md +85 -12
  3. package/adapter.js +11822 -9796
  4. package/adapterBase.js +40 -3
  5. package/entities/.generic/action.json +5 -5
  6. package/entities/.system/action.json +1 -1
  7. package/entities/AcceleratorTypes/action.json +3 -3
  8. package/entities/Addresses/action.json +5 -5
  9. package/entities/Autoscalers/action.json +7 -7
  10. package/entities/BackendBuckets/action.json +8 -8
  11. package/entities/BackendServices/action.json +11 -11
  12. package/entities/DiskTypes/action.json +3 -3
  13. package/entities/Disks/action.json +13 -13
  14. package/entities/ExternalVpnGateways/action.json +6 -6
  15. package/entities/FirewallPolicies/action.json +382 -0
  16. package/entities/FirewallPolicies/mockdatafiles/addFirewallPolicyAssociation-default.json +45 -0
  17. package/entities/FirewallPolicies/mockdatafiles/addFirewallPolicyRule-default.json +45 -0
  18. package/entities/FirewallPolicies/mockdatafiles/cloneFirewallPolicyRule-default.json +45 -0
  19. package/entities/FirewallPolicies/mockdatafiles/deleteFirewallPolicy-default.json +45 -0
  20. package/entities/FirewallPolicies/mockdatafiles/getFirewallPolicy-default.json +45 -0
  21. package/entities/FirewallPolicies/mockdatafiles/getFirewallPolicyAssociation-default.json +7 -0
  22. package/entities/FirewallPolicies/mockdatafiles/getFirewallPolicyIamPolicy-default.json +26 -0
  23. package/entities/FirewallPolicies/mockdatafiles/getFirewallPolicyRule-default.json +32 -0
  24. package/entities/FirewallPolicies/mockdatafiles/insertFirewallPolicy-default.json +45 -0
  25. package/entities/FirewallPolicies/mockdatafiles/listFirewallPolicy-default.json +75 -0
  26. package/entities/FirewallPolicies/mockdatafiles/listFirewallPolicyAssociations-default.json +12 -0
  27. package/entities/FirewallPolicies/mockdatafiles/moveFirewallPolicy-default.json +45 -0
  28. package/entities/FirewallPolicies/mockdatafiles/patchFirewallPolicy-default.json +57 -0
  29. package/entities/FirewallPolicies/mockdatafiles/patchFirewallPolicyRule-default.json +45 -0
  30. package/entities/FirewallPolicies/mockdatafiles/removeFirewallPolicyAssociation-default.json +45 -0
  31. package/entities/FirewallPolicies/mockdatafiles/removeFirewallPolicyRule-default.json +45 -0
  32. package/entities/FirewallPolicies/mockdatafiles/setFirewallPolicyIamPolicy-default.json +26 -0
  33. package/entities/FirewallPolicies/mockdatafiles/testFirewallPolicyIamPermissions-default.json +6 -0
  34. package/entities/FirewallPolicies/schema.json +47 -0
  35. package/entities/Firewalls/action.json +6 -6
  36. package/entities/ForwardingRules/action.json +7 -7
  37. package/entities/GlobalAddresses/action.json +4 -4
  38. package/entities/GlobalForwardingRules/action.json +6 -6
  39. package/entities/GlobalNetworkEndpointGroups/action.json +7 -7
  40. package/entities/GlobalOperations/action.json +5 -5
  41. package/entities/HealthChecks/action.json +7 -7
  42. package/entities/HttpHealthChecks/action.json +6 -6
  43. package/entities/HttpsHealthChecks/action.json +6 -6
  44. package/entities/Images/action.json +10 -10
  45. package/entities/InstanceGroupManagers/action.json +20 -20
  46. package/entities/InstanceGroups/action.json +9 -9
  47. package/entities/InstanceTemplates/action.json +7 -7
  48. package/entities/Instances/action.json +40 -40
  49. package/entities/InterconnectAttachments/action.json +6 -6
  50. package/entities/InterconnectLocations/action.json +2 -2
  51. package/entities/Interconnects/action.json +6 -6
  52. package/entities/LicenseCodes/action.json +2 -2
  53. package/entities/Licenses/action.json +7 -7
  54. package/entities/MachineTypes/action.json +3 -3
  55. package/entities/NetworkEndpointGroups/action.json +9 -9
  56. package/entities/Networks/action.json +10 -10
  57. package/entities/NodeGroups/action.json +13 -13
  58. package/entities/NodeTemplates/action.json +8 -8
  59. package/entities/NodeTypes/action.json +3 -3
  60. package/entities/PacketMirrorings/action.json +7 -7
  61. package/entities/Projects/action.json +13 -13
  62. package/entities/RegionAutoscalers/action.json +6 -6
  63. package/entities/RegionBackendServices/action.json +7 -7
  64. package/entities/RegionCommitments/action.json +4 -4
  65. package/entities/RegionDiskTypes/action.json +2 -2
  66. package/entities/RegionDisks/action.json +12 -12
  67. package/entities/RegionHealthCheckServices/action.json +5 -5
  68. package/entities/RegionHealthChecks/action.json +6 -6
  69. package/entities/RegionInstanceGroupManagers/action.json +19 -19
  70. package/entities/RegionInstanceGroups/action.json +4 -4
  71. package/entities/RegionNetworkEndpointGroups/action.json +4 -4
  72. package/entities/RegionNotificationEndpoints/action.json +4 -4
  73. package/entities/RegionOperations/action.json +4 -4
  74. package/entities/RegionSslCertificates/action.json +4 -4
  75. package/entities/RegionTargetHttpProxies/action.json +5 -5
  76. package/entities/RegionTargetHttpsProxies/action.json +6 -6
  77. package/entities/RegionUrlMaps/action.json +7 -7
  78. package/entities/Regions/action.json +2 -2
  79. package/entities/Reservations/action.json +9 -9
  80. package/entities/ResourcePolicies/action.json +8 -8
  81. package/entities/Routers/action.json +10 -10
  82. package/entities/Routes/action.json +4 -4
  83. package/entities/SecurityPolicies/action.json +10 -10
  84. package/entities/Snapshots/action.json +7 -7
  85. package/entities/SslCertificates/action.json +5 -5
  86. package/entities/SslPolicies/action.json +6 -6
  87. package/entities/Subnetworks/action.json +12 -12
  88. package/entities/TargetGrpcProxies/action.json +5 -5
  89. package/entities/TargetHttpProxies/action.json +6 -6
  90. package/entities/TargetHttpsProxies/action.json +9 -9
  91. package/entities/TargetInstances/action.json +5 -5
  92. package/entities/TargetPools/action.json +11 -11
  93. package/entities/TargetSslProxies/action.json +8 -8
  94. package/entities/TargetTcpProxies/action.json +6 -6
  95. package/entities/TargetVpnGateways/action.json +5 -5
  96. package/entities/UrlMaps/action.json +9 -9
  97. package/entities/VpnGateways/action.json +8 -8
  98. package/entities/VpnTunnels/action.json +5 -5
  99. package/entities/ZoneOperations/action.json +4 -4
  100. package/entities/Zones/action.json +2 -2
  101. package/error.json +6 -0
  102. package/package.json +19 -18
  103. package/pronghorn.json +11625 -10511
  104. package/propertiesSchema.json +65 -0
  105. package/refs?service=git-upload-pack +0 -0
  106. package/report/updateReport1615068706854.json +95 -0
  107. package/report/updateReport1642776932883.json +95 -0
  108. package/sampleProperties.json +7 -3
  109. package/test/integration/adapterTestBasicGet.js +1 -1
  110. package/test/integration/adapterTestIntegration.js +463 -4
  111. package/test/unit/adapterBaseTestUnit.js +14 -6
  112. package/test/unit/adapterTestUnit.js +1122 -6
  113. package/utils/addAuth.js +94 -0
  114. package/utils/basicGet.js +1 -14
  115. package/utils/entitiesToDB.js +224 -0
  116. package/utils/modify.js +4 -4
  117. package/utils/packModificationScript.js +1 -1
  118. package/utils/patches2bundledDeps.js +90 -0
  119. package/utils/removeHooks.js +20 -0
  120. package/utils/tbScript.js +14 -8
  121. package/utils/tbUtils.js +98 -19
  122. package/utils/troubleshootingAdapter.js +2 -26
  123. package/test/integration/adapterTestIntegration_me.js +0 -464
package/utils/tbUtils.js CHANGED
@@ -100,8 +100,8 @@ module.exports = {
100
100
  *
101
101
  * @function decryptProperties
102
102
  */
103
- decryptProperties: (props, dirname, discovery) => {
104
- const propertyEncryptionClassPath = path.join(dirname, '../../../@itential/pronghorn-core/core/PropertyEncryption.js');
103
+ decryptProperties: (props, iapDir, discovery) => {
104
+ const propertyEncryptionClassPath = path.join(iapDir, 'node_modules/@itential/pronghorn-core/core/PropertyEncryption.js');
105
105
  const isEncrypted = props.pathProps.encrypted;
106
106
  const PropertyEncryption = discovery.require(propertyEncryptionClassPath, isEncrypted);
107
107
  const propertyEncryption = new PropertyEncryption({
@@ -177,12 +177,12 @@ module.exports = {
177
177
  verifyInstallationDir: (dirname, name) => {
178
178
  const pathArray = dirname.split(path.sep);
179
179
  const expectedPath = `node_modules/${name}`;
180
- const currentPath = pathArray.slice(pathArray.length - 4, pathArray.length - 1).join('/');
181
- if (expectedPath !== currentPath) {
182
- throw new Error(`adapter should be installed under ${expectedPath}`);
180
+ const currentPath = pathArray.slice(pathArray.length - 3, pathArray.length).join('/');
181
+ if (currentPath.trim() !== expectedPath.trim()) {
182
+ throw new Error(`adapter should be installed under ${expectedPath} but is installed under ${currentPath}`);
183
183
  }
184
184
 
185
- const serverFile = path.join(dirname, '../../../..', 'server.js');
185
+ const serverFile = path.join(dirname, '../../../', 'server.js');
186
186
  if (!fs.existsSync(serverFile)) {
187
187
  throw new Error(`adapter should be installed under IAP/${expectedPath}`);
188
188
  }
@@ -304,23 +304,72 @@ module.exports = {
304
304
  * @param {Object} adapterPronghorn - ./pronghorn.json in adapter dir
305
305
  * @param {Object} sampleProperties - './sampleProperties.json' in adapter dir
306
306
  */
307
- createAdapter: (pronghornProps, profileItem, sampleProperties, adapterPronghorn) => {
308
- const adapter = {
309
- mongoProps: pronghornProps.mongoProps,
310
- isEncrypted: pronghornProps.pathProps.encrypted,
311
- model: adapterPronghorn.id,
312
- name: sampleProperties.id,
313
- type: adapterPronghorn.type,
314
- properties: sampleProperties,
315
- redisProps: profileItem.redisProps,
316
- loggerProps: profileItem.loggerProps,
317
- rabbitmq: profileItem.rabbitmq
318
- };
307
+ createAdapter: function createAdapter(pronghornProps, profileItem, sampleProperties, adapterPronghorn) {
308
+ const dirname = this.getDirname();
309
+ const packagePath = `${dirname.split('node_modules')[0]}package.json`;
310
+ const info = JSON.parse(fs.readFileSync(packagePath));
311
+ const version = parseInt(info.version.split('.')[0], 10);
312
+
313
+ let adapter = {};
314
+ if (version >= 2020) {
315
+ adapter = {
316
+ isEncrypted: pronghornProps.pathProps.encrypted,
317
+ model: adapterPronghorn.id,
318
+ name: sampleProperties.id,
319
+ type: adapterPronghorn.type,
320
+ properties: sampleProperties,
321
+ loggerProps: profileItem.loggerProps
322
+ };
323
+ } else {
324
+ adapter = {
325
+ mongoProps: pronghornProps.mongoProps,
326
+ isEncrypted: pronghornProps.pathProps.encrypted,
327
+ model: adapterPronghorn.id,
328
+ name: sampleProperties.id,
329
+ type: adapterPronghorn.type,
330
+ properties: sampleProperties,
331
+ redisProps: profileItem.redisProps,
332
+ loggerProps: profileItem.loggerProps,
333
+ rabbitmq: profileItem.rabbitmq
334
+ };
335
+ adapter.mongoProps.pdb = true;
336
+ }
337
+
319
338
  adapter.loggerProps.log_filename = `adapter-${adapter.name}.log`;
320
- adapter.mongoProps.pdb = true;
321
339
  return adapter;
322
340
  },
323
341
 
342
+ getPronghornProps: function getPronghornProps(iapDir) {
343
+ console.log('Retrieving properties.json file...');
344
+ const rawProps = require(path.join(iapDir, 'properties.json'));
345
+ console.log('Decrypting properties...');
346
+ const { Discovery } = require(path.join(iapDir, 'node_modules/@itential/itential-utils'));
347
+ const discovery = new Discovery();
348
+ const pronghornProps = this.decryptProperties(rawProps, iapDir, discovery);
349
+ console.log('Found properties.\n');
350
+ return pronghornProps;
351
+ },
352
+
353
+ // get database connection and existing adapter config
354
+ getAdapterConfig: async function getAdapterConfig() {
355
+ const newDirname = this.getDirname();
356
+ let iapDir;
357
+ if (this.withinIAP(newDirname)) { // when this script is called from IAP
358
+ iapDir = newDirname;
359
+ } else {
360
+ iapDir = path.join(this.getDirname(), 'utils', '../../../../');
361
+ }
362
+ const pronghornProps = this.getPronghornProps(iapDir);
363
+ console.log('Connecting to Database...');
364
+ const database = await this.connect(iapDir, pronghornProps);
365
+ console.log('Connection established.');
366
+ const { name } = require(path.join(__dirname, '..', 'package.json'));
367
+ const serviceItem = await database.collection(this.SERVICE_CONFIGS_COLLECTION).findOne(
368
+ { model: name }
369
+ );
370
+ return { database, serviceItem, pronghornProps };
371
+ },
372
+
324
373
  /**
325
374
  * @summary return async healthcheck result as a Promise
326
375
  *
@@ -368,5 +417,35 @@ module.exports = {
368
417
  } catch (error) {
369
418
  return false;
370
419
  }
420
+ },
421
+
422
+ /**
423
+ * @summary Used to determine the proper dirname to return in case adapter reference is
424
+ * symlinked withink IAP
425
+ * @returns the symlinked path (using pwd command) of the adapter in case properties.json
426
+ * is not found in the original path
427
+ * @function getDirname
428
+ */
429
+ getDirname: function getDirname() {
430
+ if (this.withinIAP(path.join(__dirname, '../../../../'))) {
431
+ return __dirname;
432
+ }
433
+ const { stdout } = this.systemSync('pwd', true);
434
+ return stdout.trim();
435
+ },
436
+
437
+ /**
438
+ * @summary connect to mongodb
439
+ *
440
+ * @function connect
441
+ * @param {Object} properties - pronghornProps
442
+ */
443
+ connect: async function connect(iapDir, properties) {
444
+ // Connect to Mongo
445
+ const { MongoDBConnection } = require(path.join(iapDir, 'node_modules/@itential/database'));
446
+ const connection = new MongoDBConnection(properties.mongoProps);
447
+ const database = await connection.connect(true);
448
+ return database;
371
449
  }
450
+
372
451
  };
@@ -117,30 +117,6 @@ const VerifyHealthCheckEndpoint = (serviceItem, props, scriptFlag) => {
117
117
  return { result, updatedAdapter };
118
118
  };
119
119
 
120
- const getPronghornProps = (iapDir) => {
121
- console.log('Retrieving properties.json file...');
122
- const rawProps = require(path.join(iapDir, 'properties.json'));
123
- console.log('Decrypting properties...');
124
- const { Discovery } = require('@itential/itential-utils');
125
- const discovery = new Discovery();
126
- const pronghornProps = utils.decryptProperties(rawProps, __dirname, discovery);
127
- console.log('Found properties.\n');
128
- return pronghornProps;
129
- };
130
-
131
- // get database connection and existing adapter config
132
- const getAdapterConfig = async () => {
133
- const iapDir = path.join(__dirname, '../../../../');
134
- const pronghornProps = getPronghornProps(iapDir);
135
- console.log('Connecting to Database...');
136
- const database = await basicGet.connect(pronghornProps);
137
- console.log('Connection established.');
138
- const serviceItem = await database.collection(utils.SERVICE_CONFIGS_COLLECTION).findOne(
139
- { model: name }
140
- );
141
- return { database, serviceItem, pronghornProps };
142
- };
143
-
144
120
  const offline = async () => {
145
121
  console.log('Start offline troubleshooting');
146
122
  const { updatedAdapter } = VerifyHealthCheckEndpoint({ properties: sampleProperties }, {}, true);
@@ -159,7 +135,7 @@ const offline = async () => {
159
135
 
160
136
  const troubleshoot = async (props, scriptFlag, persistFlag, adapter) => {
161
137
  // get database connection and existing adapter config
162
- const { database, serviceItem } = await getAdapterConfig();
138
+ const { database, serviceItem } = await utils.getAdapterConfig();
163
139
  // where troubleshoot should start
164
140
  if (serviceItem) {
165
141
  if (!scriptFlag || rls.keyInYN(`Start verifying the connection and authentication properties for ${name}?`)) {
@@ -211,4 +187,4 @@ const troubleshoot = async (props, scriptFlag, persistFlag, adapter) => {
211
187
  return null;
212
188
  };
213
189
 
214
- module.exports = { troubleshoot, getAdapterConfig, offline };
190
+ module.exports = { troubleshoot, offline };
@@ -1,464 +0,0 @@
1
- /* @copyright Itential, LLC 2019 (pre-modifications) */
2
-
3
- // Set globals
4
- /* global describe it log pronghornProps */
5
- /* eslint no-unused-vars: warn */
6
-
7
- // include required items for testing & logging
8
- const assert = require('assert');
9
- const fs = require('fs');
10
- const mocha = require('mocha');
11
- const path = require('path');
12
- const winston = require('winston');
13
- const { expect } = require('chai');
14
- const { use } = require('chai');
15
- const td = require('testdouble');
16
-
17
- const anything = td.matchers.anything();
18
-
19
- // stub and attemptTimeout are used throughout the code so set them here
20
- let logLevel = 'none';
21
- const stub = false;
22
- const isRapidFail = false;
23
- const isSaveMockData = false;
24
- const attemptTimeout = 5000;
25
-
26
- // these variables can be changed to run in integrated mode so easier to set them here
27
- // always check these in with bogus data!!!
28
- const host = 'compute.googleapis.com';
29
- const username = 'evenchick-compute-test@foundry-1.iam.gserviceaccount.com';
30
- const password = '-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCz+8JH+WtOGsBQ\nWVUS6tExA0DIRmltBjev370980n23UeZlJHX0paxXDPq0aN9YSh9D+3X1HaQHWAM\n+DAcFYCa64Dm4aFVum9tFUF7zJg7yACUfuHtRWt25Mk2OyJHYi9RJKGH7yehm+Zc\nrk5QVTLafhgnbeQYXBbPm0TkHmLH3V4eQXnFC4WPTx4XJiyrAvIol7b8IWaRMmid\nyfsio5aPxx5lY4jk4ECvJiZLIodBZ+1mmzGc2dh5Ro1vqDIewoFIQfWzhwWwprTE\nzdGZHQ3erQW4IHOmjxKcwnv1CBe3mSlpvFwPlkKwtcuNpCYHlsTz50iHWbHQ/CZG\nN/fBiMizAgMBAAECggEAD5oGSFjtnVKiUxS7VC14vsfqaLH515KPZzZ84A7j3Xtn\nBoAjeFLv7yXv9i3//xFaAiVMV8Y6FNoHBnjJKtYOVN+PR/RNGPJVUF5kU8fzdlMr\nAbRR/1BiNWc1rfbITOnM8jq7qd3oUJEEEgqmDT6lbt05WMmk2Ru6enqaKTAdHfgE\nEH/4YPCTCQuOWwvmk1YoXTq+wNXGF4v9+R6xTzhZbpyzjct5nnfw8vE8ncsI5KNE\nA5lcXtjrZL/mittg8ho6Fk297ZwRVQayJREL1B/aK4dORQo2c6s18ZY5kywyDp87\nNuZsx/gQRsaNrDhN+7Qt0FbzA2R3cNjvBCYbPcS5sQKBgQDuzkf7WSeUKIlRGbRb\nCaYBB2EDiPgKXzf9FNq/jJBS5AONtgeaVd+/WDVPwwlZGfkRV1bh8ea1qFKd+Jhi\nfbI1onMUzqjvzV7zZeONVsasRBLbXUDABXLHm5Im50p4Hl0gWjXsf3ObelVNVG2J\nXz+Hta/yGibZB2F/pD2WTnKYeQKBgQDA8UBte2TeLUqU8z+59jpNZnhEhmEmmfqI\nJQA/PX9uE5T2jIZFnzMAYEKldQ16ah5NtpyuG/+bgiuelr6G93xYyDLRD61UnE48\nlRJU+DlZBl7IPQVOg7Mt/leek+bvdSBf2Fb/1dqh23LQM86NskrS30e5dWDc9tR4\n4/0zt343iwKBgDasC1bEBoeo8CcdF2lwQA0kP1Wr2f2l5w+N4rbP24reoOGktwDi\ngCMycqIcKNu5Uohh0oZP913Hd4KrE1gZJt+YnXg6B/s+rWpT/VCyeTGfNCH8q4JK\nvQht2XwGn8n4SaHKhWXrl/AUhcr6dUlqAQV01x86VYKCahPq6h6rPxkhAoGAcWFT\n6wJIFAepfD41hKIdQL6mjh4pmPWDM94Kdx88cwMu1nNdtCwJXH80quZONVGG3UQi\nbm4llsy3tUoATG/Csqlys0fzI3V2xEMVsrjrelUz/ZdeNvVNpgmAk792ReEeVTRc\na5rQD61VmuPWzY2oSqLLE0DW2wJxeVkAwhNiKGECgYEAofdgg1x+5eaLj06kW7sC\ndF3NZBiSX/O5it4tO88JnY78XKwozkPzuP4WNL8waVKYfU5anTWpJ/SvZHBbl6mt\neC1GPuw/CtsF4KMxRURgLbGhSlAUNOsSwOP1DfLqpEEK5tjPDShtwb1sAmVuzgDa\nsFBtK4QXRSZ04tuMrDimfHY=\n-----END PRIVATE KEY-----\n';
31
- const protocol = 'https';
32
- const port = 443;
33
- const sslenable = true;
34
- const sslinvalid = true;
35
-
36
- // these are the adapter properties. You generally should not need to alter
37
- // any of these after they are initially set up
38
- global.pronghornProps = {
39
- pathProps: {
40
- encrypted: false
41
- },
42
- adapterProps: {
43
- adapters: [{
44
- id: 'Test-gcp_compute',
45
- type: 'GcpCompute',
46
- properties: {
47
- host,
48
- port,
49
- base_path: '/compute/v1/projects',
50
- version: '',
51
- cache_location: 'none',
52
- encode_pathvars: true,
53
- save_metric: false,
54
- stub,
55
- protocol,
56
- authentication: {
57
- auth_method: 'no_authentication',
58
- username,
59
- password,
60
- token: '',
61
- invalid_token_error: 401,
62
- token_timeout: -1,
63
- token_cache: 'local',
64
- auth_field: 'header.headers.Authorization',
65
- auth_field_format: 'Bearer {token}',
66
- configureGtoken: {
67
- keyFile: '/Users/jeff/adapter-gcp-compute-test-5dd811f77aca.json',
68
- scope: 'https://www.googleapis.com/auth/cloud-platform',
69
- eagerRefreshThresholdMillis: 300000
70
- }
71
- },
72
- healthcheck: {
73
- type: 'none',
74
- frequency: 60000
75
- },
76
- throttle: {
77
- throttle_enabled: false,
78
- number_pronghorns: 1,
79
- sync_async: 'sync',
80
- max_in_queue: 1000,
81
- concurrent_max: 1,
82
- expire_timeout: 0,
83
- avg_runtime: 200,
84
- priorities: [
85
- {
86
- value: 0,
87
- percent: 100
88
- }
89
- ]
90
- },
91
- request: {
92
- number_redirects: 0,
93
- number_retries: 3,
94
- limit_retry_error: [0],
95
- failover_codes: [],
96
- attempt_timeout: attemptTimeout,
97
- global_request: {
98
- payload: {},
99
- uriOptions: {},
100
- addlHeaders: {},
101
- authData: {}
102
- },
103
- healthcheck_on_timeout: true,
104
- return_raw: true,
105
- archiving: false
106
- },
107
- proxy: {
108
- enabled: false,
109
- host: '',
110
- port: 1,
111
- protocol: 'http'
112
- },
113
- ssl: {
114
- ecdhCurve: '',
115
- enabled: sslenable,
116
- accept_invalid_cert: sslinvalid,
117
- ca_file: '',
118
- key_file: '',
119
- cert_file: '',
120
- secure_protocol: '',
121
- ciphers: ''
122
- },
123
- mongo: {
124
- host: '',
125
- port: 0,
126
- database: '',
127
- username: '',
128
- password: '',
129
- replSet: '',
130
- db_ssl: {
131
- enabled: false,
132
- accept_invalid_cert: false,
133
- ca_file: '',
134
- key_file: '',
135
- cert_file: ''
136
- }
137
- }
138
- }
139
- }]
140
- }
141
- };
142
-
143
- global.$HOME = `${__dirname}/../..`;
144
-
145
- // set the log levels that Pronghorn uses, spam and trace are not defaulted in so without
146
- // this you may error on log.trace calls.
147
- const myCustomLevels = {
148
- levels: {
149
- spam: 6,
150
- trace: 5,
151
- debug: 4,
152
- info: 3,
153
- warn: 2,
154
- error: 1,
155
- none: 0
156
- }
157
- };
158
-
159
- // need to see if there is a log level passed in
160
- process.argv.forEach((val) => {
161
- // is there a log level defined to be passed in?
162
- if (val.indexOf('--LOG') === 0) {
163
- // get the desired log level
164
- const inputVal = val.split('=')[1];
165
-
166
- // validate the log level is supported, if so set it
167
- if (Object.hasOwnProperty.call(myCustomLevels.levels, inputVal)) {
168
- logLevel = inputVal;
169
- }
170
- }
171
- });
172
-
173
- // need to set global logging
174
- global.log = winston.createLogger({
175
- level: logLevel,
176
- levels: myCustomLevels.levels,
177
- transports: [
178
- new winston.transports.Console()
179
- ]
180
- });
181
-
182
- /**
183
- * Runs the common asserts for test
184
- */
185
- function runCommonAsserts(data, error) {
186
- assert.equal(undefined, error);
187
- assert.notEqual(undefined, data);
188
- assert.notEqual(null, data);
189
- assert.notEqual(undefined, data.response);
190
- assert.notEqual(null, data.response);
191
- }
192
-
193
- /**
194
- * Runs the error asserts for the test
195
- */
196
- function runErrorAsserts(data, error, code, origin, displayStr) {
197
- assert.equal(null, data);
198
- assert.notEqual(undefined, error);
199
- assert.notEqual(null, error);
200
- assert.notEqual(undefined, error.IAPerror);
201
- assert.notEqual(null, error.IAPerror);
202
- assert.notEqual(undefined, error.IAPerror.displayString);
203
- assert.notEqual(null, error.IAPerror.displayString);
204
- assert.equal(code, error.icode);
205
- assert.equal(origin, error.IAPerror.origin);
206
- assert.equal(displayStr, error.IAPerror.displayString);
207
- }
208
-
209
- /**
210
- * @function saveMockData
211
- * Attempts to take data from responses and place them in MockDataFiles to help create Mockdata.
212
- * Note, this was built based on entity file structure for Adapter-Engine 1.6.x
213
- * @param {string} entityName - Name of the entity saving mock data for
214
- * @param {string} actionName - Name of the action saving mock data for
215
- * @param {string} descriptor - Something to describe this test (used as a type)
216
- * @param {string or object} responseData - The data to put in the mock file.
217
- */
218
- function saveMockData(entityName, actionName, descriptor, responseData) {
219
- // do not need to save mockdata if we are running in stub mode (already has mock data) or if told not to save
220
- if (stub || !isSaveMockData) {
221
- return false;
222
- }
223
-
224
- // must have a response in order to store the response
225
- if (responseData && responseData.response) {
226
- let data = responseData.response;
227
-
228
- // if there was a raw response that one is better as it is untranslated
229
- if (responseData.raw) {
230
- data = responseData.raw;
231
-
232
- try {
233
- const temp = JSON.parse(data);
234
- data = temp;
235
- } catch (pex) {
236
- // do not care if it did not parse as we will just use data
237
- }
238
- }
239
-
240
- try {
241
- const base = path.join(__dirname, `../../entities/${entityName}/`);
242
- const mockdatafolder = 'mockdatafiles';
243
- const filename = `mockdatafiles/${actionName}-${descriptor}.json`;
244
-
245
- if (!fs.existsSync(base + mockdatafolder)) {
246
- fs.mkdirSync(base + mockdatafolder);
247
- }
248
-
249
- // write the data we retrieved
250
- fs.writeFile(base + filename, JSON.stringify(data, null, 2), 'utf8', (errWritingMock) => {
251
- if (errWritingMock) throw errWritingMock;
252
-
253
- // update the action file to reflect the changes. Note: We're replacing the default object for now!
254
- fs.readFile(`${base}action.json`, (errRead, content) => {
255
- if (errRead) throw errRead;
256
-
257
- // parse the action file into JSON
258
- const parsedJson = JSON.parse(content);
259
-
260
- // The object update we'll write in.
261
- const responseObj = {
262
- type: descriptor,
263
- key: '',
264
- mockFile: filename
265
- };
266
-
267
- // get the object for method we're trying to change.
268
- const currentMethodAction = parsedJson.actions.find((obj) => obj.name === actionName);
269
-
270
- // if the method was not found - should never happen but...
271
- if (!currentMethodAction) {
272
- throw Error('Can\'t find an action for this method in the provided entity.');
273
- }
274
-
275
- // if there is a response object, we want to replace the Response object. Otherwise we'll create one.
276
- const actionResponseObj = currentMethodAction.responseObjects.find((obj) => obj.type === descriptor);
277
-
278
- // Add the action responseObj back into the array of response objects.
279
- if (!actionResponseObj) {
280
- // if there is a default response object, we want to get the key.
281
- const defaultResponseObj = currentMethodAction.responseObjects.find((obj) => obj.type === 'default');
282
-
283
- // save the default key into the new response object
284
- if (defaultResponseObj) {
285
- responseObj.key = defaultResponseObj.key;
286
- }
287
-
288
- // save the new response object
289
- currentMethodAction.responseObjects = [responseObj];
290
- } else {
291
- // update the location of the mock data file
292
- actionResponseObj.mockFile = responseObj.mockFile;
293
- }
294
-
295
- // Save results
296
- fs.writeFile(`${base}action.json`, JSON.stringify(parsedJson, null, 2), (err) => {
297
- if (err) throw err;
298
- });
299
- });
300
- });
301
- } catch (e) {
302
- log.debug(`Failed to save mock data for ${actionName}. ${e.message}`);
303
- return false;
304
- }
305
- }
306
-
307
- // no response to save
308
- log.debug(`No data passed to save into mockdata for ${actionName}`);
309
- return false;
310
- }
311
-
312
- // require the adapter that we are going to be using
313
- const GcpCompute = require('../../adapter.js');
314
-
315
- // begin the testing - these should be pretty well defined between the describe and the it!
316
- describe('[integration] GcpCompute Adapter Test', () => {
317
- describe('GcpCompute Class Tests', () => {
318
- const a = new GcpCompute(
319
- pronghornProps.adapterProps.adapters[0].id,
320
- pronghornProps.adapterProps.adapters[0].properties
321
- );
322
-
323
- if (isRapidFail) {
324
- const state = {};
325
- state.passed = true;
326
-
327
- mocha.afterEach(function x() {
328
- state.passed = state.passed
329
- && (this.currentTest.state === 'passed');
330
- });
331
- mocha.beforeEach(function x() {
332
- if (!state.passed) {
333
- return this.currentTest.skip();
334
- }
335
- return true;
336
- });
337
- }
338
-
339
- describe('#class instance created', () => {
340
- it('should be a class with properties', (done) => {
341
- try {
342
- assert.notEqual(null, a);
343
- assert.notEqual(undefined, a);
344
- assert.notEqual(null, a.allProps);
345
- const check = global.pronghornProps.adapterProps.adapters[0].properties.healthcheck.type;
346
- log.error('CHECK');
347
- log.error(check);
348
- log.error(a.allProps.healthcheck.type);
349
- log.error(a.healthcheckType);
350
- // assert.equal(check, a.healthcheckType);
351
- assert.equal(check, a.allProps.healthcheck.type);
352
- done();
353
- } catch (error) {
354
- log.error(`Test Failure: ${error}`);
355
- done(error);
356
- }
357
- }).timeout(attemptTimeout);
358
- });
359
-
360
- describe('#connect', () => {
361
- it('should get connected - no healthcheck', (done) => {
362
- try {
363
- a.healthcheckType = 'none';
364
- a.connect();
365
-
366
- try {
367
- assert.equal(true, a.alive);
368
- done();
369
- } catch (error) {
370
- log.error(`Test Failure: ${error}`);
371
- done(error);
372
- }
373
- } catch (error) {
374
- log.error(`Adapter Exception: ${error}`);
375
- done(error);
376
- }
377
- });
378
- it('should get connected - startup healthcheck', (done) => {
379
- try {
380
- a.healthcheckType = 'startup';
381
- a.connect();
382
-
383
- try {
384
- assert.equal(true, a.alive);
385
- done();
386
- } catch (error) {
387
- log.error(`Test Failure: ${error}`);
388
- done(error);
389
- }
390
- } catch (error) {
391
- log.error(`Adapter Exception: ${error}`);
392
- done(error);
393
- }
394
- });
395
- });
396
-
397
- describe('#healthCheck', () => {
398
- it('should be healthy', (done) => {
399
- try {
400
- a.healthCheck(null, (data) => {
401
- try {
402
- assert.equal(true, a.healthy);
403
- saveMockData('system', 'healthcheck', 'default', data);
404
- done();
405
- } catch (err) {
406
- log.error(`Test Failure: ${err}`);
407
- done(err);
408
- }
409
- });
410
- } catch (error) {
411
- log.error(`Adapter Exception: ${error}`);
412
- done(error);
413
- }
414
- }).timeout(attemptTimeout);
415
- });
416
-
417
- /*
418
- -----------------------------------------------------------------------
419
- -----------------------------------------------------------------------
420
- *** All code above this comment will be replaced during a migration ***
421
- ******************* DO NOT REMOVE THIS COMMENT BLOCK ******************
422
- -----------------------------------------------------------------------
423
- -----------------------------------------------------------------------
424
- */
425
-
426
- const projectsProject = 'adapter-gcp-compute-test';
427
- describe('#getProjectGetXpnHost - errors', () => {
428
- it('should work if integrated or standalone with mockdata', (done) => {
429
- try {
430
- a.getProjectGetXpnHost(null, null, null, null, null, null, null, projectsProject, (data, error) => {
431
- try {
432
- if (stub) {
433
- runCommonAsserts(data, error);
434
- assert.equal('object', typeof data.response.commonInstanceMetadata);
435
- assert.equal('string', data.response.creationTimestamp);
436
- assert.equal('STANDARD', data.response.defaultNetworkTier);
437
- assert.equal('string', data.response.defaultServiceAccount);
438
- assert.equal('string', data.response.description);
439
- assert.equal(true, Array.isArray(data.response.enabledFeatures));
440
- assert.equal('string', data.response.id);
441
- assert.equal('compute#project', data.response.kind);
442
- assert.equal('string', data.response.name);
443
- assert.equal(true, Array.isArray(data.response.quotas));
444
- assert.equal('string', data.response.selfLink);
445
- assert.equal('object', typeof data.response.usageExportLocation);
446
- assert.equal('HOST', data.response.xpnProjectStatus);
447
- } else {
448
- runCommonAsserts(data, error);
449
- }
450
- saveMockData('Projects', 'getProjectGetXpnHost', 'default', data);
451
- done();
452
- } catch (err) {
453
- log.error(`Test Failure: ${err}`);
454
- done(err);
455
- }
456
- });
457
- } catch (error) {
458
- log.error(`Adapter Exception: ${error}`);
459
- done(error);
460
- }
461
- }).timeout(attemptTimeout);
462
- });
463
- });
464
- });