@itentialopensource/adapter-netbox 0.8.0 → 0.11.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 (46) hide show
  1. package/AUTH.md +9 -15
  2. package/CALLS.md +2447 -22
  3. package/CHANGELOG.md +24 -0
  4. package/CONTRIBUTING.md +1 -160
  5. package/ENHANCE.md +2 -2
  6. package/README.md +32 -23
  7. package/SYSTEMINFO.md +12 -3
  8. package/adapter.js +2483 -1839
  9. package/adapterBase.js +549 -879
  10. package/changelogs/changelog.md +181 -0
  11. package/entities/Dcim/action.json +182 -0
  12. package/entities/Dcim/mockdatafiles/getDcimLocations-default.json +688 -0
  13. package/entities/Dcim/schema.json +82 -19
  14. package/metadata.json +69 -0
  15. package/package.json +24 -24
  16. package/pronghorn.json +15221 -12889
  17. package/propertiesSchema.json +422 -31
  18. package/refs?service=git-upload-pack +0 -0
  19. package/report/adapter-openapi.json +52536 -0
  20. package/report/adapter-openapi.yaml +37346 -0
  21. package/report/adapterInfo.json +8 -8
  22. package/report/updateReport1691508495299.json +120 -0
  23. package/report/updateReport1692202980865.json +120 -0
  24. package/report/updateReport1694466470665.json +120 -0
  25. package/sampleProperties.json +65 -4
  26. package/test/integration/adapterTestBasicGet.js +2 -4
  27. package/test/integration/adapterTestConnectivity.js +91 -42
  28. package/test/integration/adapterTestIntegration.js +383 -2
  29. package/test/unit/adapterBaseTestUnit.js +388 -313
  30. package/test/unit/adapterTestUnit.js +599 -112
  31. package/utils/adapterInfo.js +1 -1
  32. package/utils/addAuth.js +1 -1
  33. package/utils/artifactize.js +1 -1
  34. package/utils/checkMigrate.js +1 -1
  35. package/utils/entitiesToDB.js +2 -2
  36. package/utils/findPath.js +1 -1
  37. package/utils/methodDocumentor.js +260 -0
  38. package/utils/modify.js +13 -15
  39. package/utils/packModificationScript.js +1 -1
  40. package/utils/pre-commit.sh +2 -0
  41. package/utils/taskMover.js +309 -0
  42. package/utils/tbScript.js +89 -34
  43. package/utils/tbUtils.js +41 -21
  44. package/utils/testRunner.js +1 -1
  45. package/utils/troubleshootingAdapter.js +9 -6
  46. package/workflows/README.md +0 -3
@@ -4,8 +4,8 @@
4
4
  /* eslint import/no-dynamic-require:warn */
5
5
  /* eslint prefer-destructuring:warn */
6
6
 
7
- const fs = require('fs-extra');
8
7
  const path = require('path');
8
+ const fs = require('fs-extra');
9
9
 
10
10
  /**
11
11
  * This script will determine the information about the adapter and store
package/utils/addAuth.js CHANGED
@@ -2,9 +2,9 @@
2
2
  /* eslint global-require: warn */
3
3
  /* eslint import/no-dynamic-require: warn */
4
4
 
5
- const rls = require('readline-sync');
6
5
  const path = require('path');
7
6
  const fs = require('fs');
7
+ const rls = require('readline-sync');
8
8
 
9
9
  function getQuestions(props, obj) {
10
10
  const questions = props.map((p) => `${p}: ${(obj[p] !== undefined) ? `(${obj[p]})` : ''} `);
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  /* @copyright Itential, LLC 2019 */
3
3
 
4
- const fs = require('fs-extra');
5
4
  const path = require('path');
5
+ const fs = require('fs-extra');
6
6
 
7
7
  async function createBundle(adapterOldDir) {
8
8
  // set directories
@@ -1,7 +1,7 @@
1
1
  const { execSync } = require('child_process');
2
+ const fs = require('fs');
2
3
  const semver = require('semver');
3
4
  const axios = require('axios');
4
- const fs = require('fs');
5
5
  const packageJson = require('../package.json');
6
6
 
7
7
  const localEngineVer = packageJson.engineVersion;
@@ -7,6 +7,7 @@
7
7
  /* eslint global-require: warn */
8
8
  /* eslint no-unused-vars: warn */
9
9
  /* eslint import/no-unresolved: warn */
10
+ /* eslint no-promise-executor-return: warn */
10
11
 
11
12
  /**
12
13
  * This script is used to read through an adapter's entities files
@@ -164,8 +165,7 @@ const moveEntitiesToDB = async (targetPath, options) => {
164
165
  });
165
166
 
166
167
  // Upload documents to db collection
167
- const iapDir = utils.getIAPHome();
168
- const db = await utils.connect(iapDir, currentProps).catch((err) => { console.error(err); throw err; });
168
+ const db = await utils.connect(currentProps).catch((err) => { console.error(err); throw err; });
169
169
  if (!db) {
170
170
  console.error('Error occured when connectiong to database', currentProps);
171
171
  throw new Error('Database not found');
package/utils/findPath.js CHANGED
@@ -4,8 +4,8 @@
4
4
  /* eslint import/no-dynamic-require:warn */
5
5
  /* eslint prefer-destructuring:warn */
6
6
 
7
- const fs = require('fs-extra');
8
7
  const path = require('path');
8
+ const fs = require('fs-extra');
9
9
  const rls = require('readline-sync');
10
10
 
11
11
  /**
@@ -0,0 +1,260 @@
1
+ /* eslint global-require:warn */
2
+ /* eslint import/no-dynamic-require:warn */
3
+ /* eslint no-param-reassign:warn */
4
+
5
+ const fs = require('fs-extra');
6
+ const acorn = require('acorn');
7
+
8
+ // Getting the base directory:
9
+ let adaptdir = __dirname;
10
+ if (adaptdir.endsWith('/utils')) {
11
+ adaptdir = adaptdir.substring(0, adaptdir.length - 6);
12
+ }
13
+
14
+ function createObjectForFunction(
15
+ funcName,
16
+ funcArgs,
17
+ entityPath,
18
+ description,
19
+ workflow
20
+ ) {
21
+ const funcObject = {};
22
+ // if the entity path is not set, then the object is not created.
23
+ if (entityPath !== undefined) {
24
+ funcObject.method_signature = `${funcName}(${funcArgs.join(', ')})`;
25
+ funcObject.path = entityPath;
26
+ if (description === undefined) {
27
+ funcObject.description = '';
28
+ funcObject.workflow = 'No';
29
+ } else {
30
+ funcObject.description = description;
31
+ funcObject.workflow = workflow;
32
+ }
33
+ }
34
+ return funcObject;
35
+ }
36
+
37
+ function getPathFromEntity(entity, funcName) {
38
+ let epath;
39
+ if (entity === undefined || entity === '.generic') {
40
+ epath = undefined;
41
+ } else {
42
+ // Access the action.js file for the certain entity to get the path
43
+ const entityPath = `${adaptdir}/entities/${entity}/action.json`;
44
+ const actionJSON = require(entityPath);
45
+ actionJSON.actions.forEach((action) => {
46
+ if (action.name === funcName) {
47
+ if (typeof action.entitypath === 'object') {
48
+ epath = '';
49
+ const keys = Object.keys(action.entitypath);
50
+ for (let k = 0; k < keys.length; k += 1) {
51
+ epath += `${keys[k]}:${action.entitypath[keys[k]]} <br /> `;
52
+ }
53
+ epath = epath.substring(0, epath.length - 8);
54
+ } else {
55
+ epath = action.entitypath;
56
+ }
57
+ }
58
+ });
59
+ }
60
+ return epath;
61
+ }
62
+
63
+ function recurseCallExpressions(statement, callList) {
64
+ // Recursively finds all CallExpressions in the syntax tree
65
+ if (statement.type === 'CallExpression') callList.push(statement);
66
+ const keys = Object.keys(statement);
67
+ for (let k = 0; k < keys.length; k += 1) {
68
+ if (typeof statement[keys[k]] === 'object' && statement[keys[k]] !== null) {
69
+ recurseCallExpressions(statement[keys[k]], callList);
70
+ }
71
+ }
72
+ }
73
+
74
+ function readFileUsingLib(filename, descriptionObj, workflowObj, functionList) {
75
+ // read the file
76
+ const aFile = fs.readFileSync(filename, 'utf8');
77
+ // parsing the file to get the function and class declarations.
78
+ const aFileFuncArgs = acorn.parse(aFile, { ecmaVersion: 2020 });
79
+
80
+ // Looping through all the declarations parsed:
81
+ aFileFuncArgs.body.forEach((e) => {
82
+ // Getting only the class declaration as it has our required functions.
83
+ if (e.type === 'ClassDeclaration') {
84
+ const methodDefinition = e.body;
85
+ methodDefinition.body.forEach((method) => {
86
+ // Getting method name and its params in the class.
87
+ const funcName = method.key.name;
88
+ const funcArgs = [];
89
+ method.value.params.forEach((param) => {
90
+ if (param.type === 'Identifier') {
91
+ funcArgs.push(param.name);
92
+ } else {
93
+ const args = `${param.left.name} = ${param.right.value}`;
94
+ funcArgs.push(args);
95
+ }
96
+ });
97
+
98
+ // Getting the entity for the method:
99
+ const callList = [];
100
+ method.value.body.body.forEach((statement) => {
101
+ recurseCallExpressions(statement, callList);
102
+ });
103
+ const requests = [];
104
+ for (let i = 0; i < callList.length; i += 1) {
105
+ if (callList[i].callee.property && callList[i].callee.property.name === 'identifyRequest') {
106
+ requests.push(callList[i]);
107
+ }
108
+ }
109
+ if (requests.length > 0) {
110
+ const expr = requests[0];
111
+ if (expr.arguments.length < 2) {
112
+ throw new Error(`Bad inputs in method ${funcName}`);
113
+ }
114
+ const entity = expr.arguments[0].value;
115
+ const actionName = expr.arguments[1].value;
116
+ if (expr !== undefined && (expr.arguments[0].type !== 'Literal' || expr.arguments[1].type !== 'Literal')) {
117
+ throw new Error(`Bad inputs in method ${funcName}`);
118
+ }
119
+ const entityPath = getPathFromEntity(entity, actionName);
120
+
121
+ // Creating and storing the object for the method.
122
+ if (entityPath !== undefined) {
123
+ functionList.push(
124
+ createObjectForFunction(
125
+ funcName,
126
+ funcArgs,
127
+ entityPath,
128
+ descriptionObj[funcName],
129
+ workflowObj[funcName]
130
+ )
131
+ );
132
+ }
133
+ }
134
+ });
135
+ }
136
+ });
137
+ }
138
+
139
+ function readJSONFile(filename, descriptionObj, workflowObj) {
140
+ // Accessing the JSON file.
141
+ const phJSON = require(filename);
142
+ // Getting the methods array.
143
+ const methodArray = phJSON.methods;
144
+ methodArray.forEach((methodName) => {
145
+ // Getting the method description and workflow:
146
+ const funcName = methodName.name;
147
+ descriptionObj[funcName] = methodName.summary ? methodName.summary : methodName.description;
148
+ workflowObj[funcName] = methodName.task ? 'Yes' : 'No';
149
+ });
150
+ }
151
+
152
+ function readMDFile(filename, functionList) {
153
+ // Reading in the .md file and creating an array with each line as an element.
154
+ const mdFile = fs.readFileSync(filename, 'utf-8');
155
+ const fileSplit = mdFile.split('\n');
156
+ // Storing the data that should added later to the updated data.
157
+ const linesToAddLater = [];
158
+ let index = fileSplit.length - 1;
159
+
160
+ // Removing all the blank lines at the end of the file.
161
+ if (fileSplit[index] === '') {
162
+ while (fileSplit[index] === '') {
163
+ linesToAddLater.push(fileSplit.pop());
164
+ index -= 1;
165
+ }
166
+ }
167
+
168
+ // Checking if the last 2 lines are <br> and </table>. If not, the file is corrupted and the
169
+ // data at the end of the file should be fixed.
170
+ if (fileSplit[index] === '<br>' || fileSplit[index - 1] === '</table>') {
171
+ // Storing <br> and </table> to add later.
172
+ linesToAddLater.push(fileSplit.pop());
173
+ linesToAddLater.push(fileSplit.pop());
174
+ index -= 2;
175
+ } else {
176
+ console.log('The file has bad content at the end.');
177
+ return;
178
+ }
179
+ // if (fileSplit[index] !== '<br>' && fileSplit[index - 1] !== '</table>') {
180
+ // console.log('The file has bad content at the end.');
181
+ // return;
182
+ // } else {
183
+ // // Storing <br> and </table> to add later.
184
+ // linesToAddLater.push(fileSplit.pop());
185
+ // linesToAddLater.push(fileSplit.pop());
186
+ // index -= 2;
187
+ // }
188
+
189
+ // Removing all the lines until the header tags are reached.
190
+ while (!fileSplit[index].includes('<th')) {
191
+ fileSplit.pop();
192
+ index -= 1;
193
+ }
194
+ // Adding </tr> for the header row, because it got removed in the above loop.
195
+ fileSplit.push(' </tr>');
196
+
197
+ // Creating the tags for each method to be appended to the file.
198
+ const tdBeginTag = ' <td style="padding:15px">';
199
+ const tdEndTag = '</td>';
200
+ functionList.forEach((func) => {
201
+ const signCommand = `${tdBeginTag}${func.method_signature}${tdEndTag}`;
202
+ const descCommand = `${tdBeginTag}${func.description}${tdEndTag}`;
203
+ const pathCommand = `${tdBeginTag}${func.path}${tdEndTag}`;
204
+ const workflowCommand = `${tdBeginTag}${func.workflow}${tdEndTag}`;
205
+ fileSplit.push(' <tr>');
206
+ fileSplit.push(signCommand);
207
+ fileSplit.push(descCommand);
208
+ fileSplit.push(pathCommand);
209
+ fileSplit.push(workflowCommand);
210
+ fileSplit.push(' </tr>');
211
+ });
212
+
213
+ // Adding </table> and <br> at the end of the file to complete the table and the file.
214
+ while (linesToAddLater.length > 0) {
215
+ fileSplit.push(linesToAddLater.pop());
216
+ }
217
+
218
+ // Writing all the content back into the file.
219
+ fs.writeFileSync(filename, fileSplit.join('\n'), {
220
+ encoding: 'utf-8',
221
+ flag: 'w'
222
+ });
223
+ }
224
+
225
+ function getFileInfo() {
226
+ // If files don't exist:
227
+ if (!fs.existsSync(`${adaptdir}/adapter.js`)) {
228
+ console.log('Missing - utils/adapter.js');
229
+ return;
230
+ }
231
+ if (!fs.existsSync(`${adaptdir}/pronghorn.json`)) {
232
+ console.log('Missing - pronghorn.json');
233
+ return;
234
+ }
235
+ if (!fs.existsSync(`${adaptdir}/CALLS.md`)) {
236
+ console.log('Missing - CALLS.md');
237
+ return;
238
+ }
239
+
240
+ const descriptionObj = {};
241
+ const workflowObj = {};
242
+
243
+ // Get the method descriptions and the workflow values from pronghorn.json file.
244
+ readJSONFile(`${adaptdir}/pronghorn.json`, descriptionObj, workflowObj);
245
+
246
+ // Get the method signature, entity path and create an object that contains all the info regarding
247
+ // the method and push it to the functionList array.
248
+ const functionList = [];
249
+ readFileUsingLib(
250
+ `${adaptdir}/adapter.js`,
251
+ descriptionObj,
252
+ workflowObj,
253
+ functionList
254
+ );
255
+
256
+ // createMarkDown(functionList);
257
+ readMDFile(`${adaptdir}/CALLS.md`, functionList);
258
+ }
259
+
260
+ getFileInfo();
package/utils/modify.js CHANGED
@@ -1,7 +1,7 @@
1
+ const { execSync } = require('child_process');
1
2
  const fs = require('fs-extra');
2
3
  const Ajv = require('ajv');
3
4
  const rls = require('readline-sync');
4
- const { execSync } = require('child_process');
5
5
  const { existsSync } = require('fs-extra');
6
6
  const { getAdapterConfig } = require('./tbUtils');
7
7
  const { name } = require('../package.json');
@@ -21,9 +21,7 @@ async function updateServiceItem() {
21
21
  const validate = ajv.compile(propertiesSchema);
22
22
  validate(currentProps);
23
23
  console.log('Updating Properties...');
24
- await database.collection('service_configs').updateOne(
25
- { model: name }, { $set: serviceItem }
26
- );
24
+ await database.collection('service_configs').updateOne({ model: name }, { $set: serviceItem });
27
25
  console.log('Properties Updated');
28
26
  }
29
27
 
@@ -35,7 +33,7 @@ async function updateServiceItem() {
35
33
  function backup() {
36
34
  // zip all files except node_modules and package-lock
37
35
  const backupCmd = 'zip -r previousVersion.zip .';
38
- execSync(backupCmd, { encoding: 'utf-8' });
36
+ execSync(backupCmd, { encoding: 'utf-8', maxBuffer: 1024 * 1024 * 2 });
39
37
  }
40
38
 
41
39
  /**
@@ -53,9 +51,9 @@ function archiveMod(modType) {
53
51
  const archiveName = `${modType}-${now.toISOString()}`;
54
52
  execSync(`mkdir adapter_modifications/archive/${archiveName}`);
55
53
  const archiveCmd = 'mv adapter_modifications/archive .'
56
- + ` && mv adapter_modifications/* archive/${archiveName}`
57
- + ' && mv archive adapter_modifications'
58
- + ` && rm ${zipFile}`;
54
+ + ` && mv adapter_modifications/* archive/${archiveName}`
55
+ + ' && mv archive adapter_modifications'
56
+ + ` && rm ${zipFile}`;
59
57
  execSync(archiveCmd, { encoding: 'utf-8' });
60
58
  }
61
59
 
@@ -73,7 +71,7 @@ function revertMod() {
73
71
  }
74
72
  });
75
73
  // // unzip previousVersion, reinstall dependencies and delete zipfile
76
- execSync('unzip -o previousVersion.zip && rm -rf node_modules && rm package-lock.json && npm install');
74
+ execSync('unzip -o previousVersion.zip && rm -rf node_modules && rm package-lock.json && npm install', { maxBuffer: 1024 * 1024 * 2 });
77
75
  execSync('rm previousVersion.zip');
78
76
  console.log('Changes have been reverted');
79
77
  }
@@ -90,12 +88,12 @@ if (flags === '-m') {
90
88
  backup();
91
89
  console.log('Migrating adapter and running tests...');
92
90
  const migrateCmd = 'unzip -o migrationPackage.zip'
93
- + ' && cd adapter_modifications'
94
- + ' && node migrate';
91
+ + ' && cd adapter_modifications'
92
+ + ' && node migrate';
95
93
  const migrateOutput = execSync(migrateCmd, { encoding: 'utf-8' });
96
94
  console.log(migrateOutput);
97
95
  if (migrateOutput.indexOf('Lint exited with code 1') >= 0
98
- || migrateOutput.indexOf('Tests exited with code 1') >= 0) {
96
+ || migrateOutput.indexOf('Tests exited with code 1') >= 0) {
99
97
  if (rls.keyInYN('Adapter failed tests or lint after migrating. Would you like to revert the changes?')) {
100
98
  console.log('Reverting changes...');
101
99
  revertMod();
@@ -125,12 +123,12 @@ if (flags === '-u') {
125
123
  // Backup current adapter
126
124
  backup();
127
125
  const updateCmd = 'unzip -o updatePackage.zip'
128
- + ' && cd adapter_modifications'
129
- + ' && node update.js updateFiles';
126
+ + ' && cd adapter_modifications'
127
+ + ' && node update.js updateFiles';
130
128
  execSync(updateCmd, { encoding: 'utf-8' });
131
129
  const updateOutput = execSync(updateCmd, { encoding: 'utf-8' });
132
130
  if (updateOutput.indexOf('Lint exited with code 1') >= 0
133
- || updateOutput.indexOf('Tests exited with code 1') >= 0) {
131
+ || updateOutput.indexOf('Tests exited with code 1') >= 0) {
134
132
  if (rls.keyInYN('Adapter failed tests or lint after updating. Would you like to revert the changes?')) {
135
133
  console.log('Reverting changes...');
136
134
  revertMod();
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  /* @copyright Itential, LLC 2019 */
3
3
 
4
- const fs = require('fs-extra');
5
4
  const path = require('path');
6
5
  const { spawnSync } = require('child_process');
6
+ const fs = require('fs-extra');
7
7
  const { createBundle } = require('./artifactize');
8
8
 
9
9
  const nodeEntryPath = path.resolve('.');
@@ -19,6 +19,8 @@ node utils/testRunner.js -r
19
19
 
20
20
  # update the adapter information file
21
21
  node utils/adapterInfo.js
22
+ node utils/methodDocumentor.js
23
+ git add CALLS.md report/adapterInfo.json
22
24
 
23
25
  # security audit on the code
24
26
  npm audit --registry=https://registry.npmjs.org --audit-level=moderate