@opscompass/opscompass-cli 1.0.9 → 1.0.10

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.
package/colors.js ADDED
@@ -0,0 +1,11 @@
1
+ /* Global color variables for console output. Note %s is where in the string (the second argument) gets injected. \x1b[0m resets the terminal color so it doesn't continue to be the chosen color anymore after this point.
2
+ Colors are coded with ANSI Escape Codes - Select Graphic Rendition subset. */
3
+
4
+ global.yellowText = "\x1b[33m%s\x1b[0m";
5
+ global.greenText = "\x1b[32m%s\x1b[0m";
6
+
7
+
8
+ module.exports = {
9
+ yellowText,
10
+ greenText
11
+ };
package/credentials.js CHANGED
@@ -2,51 +2,29 @@ const fs = require("fs");
2
2
  const path = require("path");
3
3
  const { redeemRefreshToken } = require("./oauth");
4
4
  const { opscompassHome } = require("./environment/current.js");
5
+ const {
6
+ writeFileToHome
7
+ } = require("./lib/homeInteraction.js");
8
+ const {
9
+ canReadFile, FilePermissions
10
+ } = require("./lib/cliHelpers.js");
5
11
 
6
12
  function canReadStoredCredentials() {
7
- try {
8
- fs.accessSync(
9
- path.join(
10
- opscompassHome,
11
- "tokens.json"
12
- )
13
- );
14
- return true;
15
- } catch {
16
- return false;
17
- }
13
+ return canReadFile(
14
+ path.join(
15
+ opscompassHome,
16
+ "tokens.json"
17
+ )
18
+ );
18
19
  }
19
20
 
20
21
  async function storeCredentials(data) {
21
- // see if the .opscompass directory exists; if not, try to create it
22
- try {
23
- fs.accessSync(opscompassHome);
24
- } catch {
25
- // mode 700: only the user can interact with the directory
26
- // and can do everything in that directory (read, write, list)
27
- fs.mkdirSync(opscompassHome, { mode: "700" });
22
+ // calculate the expires_at from the expires_in
23
+ if (data.expires_in) {
24
+ data.expires_at = new Date(Date.now() + (data.expires_in * 1000));
28
25
  }
29
26
 
30
- // promisify the callback of fs.writeFile
31
- return new Promise((resolve, reject) => {
32
- try {
33
- // calculate the expires_at from the expires_in
34
- if (data.expires_in) {
35
- data.expires_at = new Date(Date.now() + (data.expires_in * 1000));
36
- }
37
-
38
- // write the token data to the file
39
- fs.writeFile(
40
- path.join(opscompassHome, 'tokens.json'),
41
- JSON.stringify(data),
42
- // mode 600: the user can read/write (and not execute)
43
- // but only the user can interact with the file
44
- { mode: "600" },
45
- () => resolve());
46
- } catch (ex) {
47
- reject(ex);
48
- }
49
- });
27
+ return writeFileToHome('tokens.json', data);
50
28
  }
51
29
 
52
30
  async function getCredentials() {
@@ -1,21 +1,28 @@
1
1
  // production: OpsCompassClient is referenced from npm package
2
2
 
3
+
3
4
  const {
4
5
  OpsCompassClient,
6
+ ScriptType,
5
7
  OAuthHandler
6
8
  } = require("@opscompass/opscompass-api");
7
9
 
8
10
  const path = require("path");
9
11
  const { homedir } = require("os");
10
12
  const opscompassHome = path.join(homedir(), '.opscompass');
13
+ const cliCommand = "opscompass";
11
14
 
12
15
  const clientId = "vOakDaOv4L26f3uuI4sp3KC1Sov3nsW2";
13
16
  // default authDomain
14
17
  // default audience
15
18
  const oAuthClient = new OAuthHandler(clientId);
19
+ const isLocal = false
16
20
 
17
21
  module.exports = {
18
22
  OpsCompassClient,
23
+ ScriptType,
19
24
  oAuthClient,
20
25
  opscompassHome,
26
+ isLocal,
27
+ cliCommand
21
28
  };
@@ -2,20 +2,26 @@
2
2
 
3
3
  const {
4
4
  OpsCompassClient,
5
+ ScriptType,
5
6
  OAuthHandler
6
7
  } = require("@opscompass/opscompass-api-demo");
7
8
 
8
9
  const path = require("path");
9
10
  const { homedir } = require("os");
10
11
  const opscompassHome = path.join(homedir(), '.opscompassdemo');
12
+ const cliCommand = "opscompassdemo";
11
13
 
12
14
  const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
13
15
  const authDomain = "auth-dev.opscompass.com";
14
16
  const audience = "https://opscompass-api-demo.azure-api.net";
15
17
  const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
18
+ const isLocal = false
16
19
 
17
20
  module.exports = {
18
21
  OpsCompassClient,
22
+ ScriptType,
19
23
  oAuthClient,
20
24
  opscompassHome,
25
+ isLocal,
26
+ cliCommand
21
27
  };
@@ -2,20 +2,26 @@
2
2
 
3
3
  const {
4
4
  OpsCompassClient,
5
+ ScriptType,
5
6
  OAuthHandler
6
7
  } = require("@opscompass/opscompass-api-dev");
7
8
 
8
9
  const path = require("path");
9
10
  const { homedir } = require("os");
10
11
  const opscompassHome = path.join(homedir(), '.opscompassdev');
12
+ const cliCommand = "opscompassdev";
11
13
 
12
14
  const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
13
15
  const authDomain = "auth-dev.opscompass.com";
14
16
  const audience = "https://fa-sampleapi-cus-dev.azurewebsites.net";
15
17
  const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
18
+ const isLocal = false;
16
19
 
17
20
  module.exports = {
18
21
  OpsCompassClient,
22
+ ScriptType,
19
23
  oAuthClient,
20
24
  opscompassHome,
25
+ isLocal,
26
+ cliCommand
21
27
  };
@@ -3,20 +3,26 @@
3
3
 
4
4
  const {
5
5
  OpsCompassClient,
6
+ ScriptType,
6
7
  OAuthHandler
7
8
  } = require("@opscompass/opscompass-api");
8
9
 
9
10
  const path = require("path");
10
11
  const { homedir } = require("os");
11
12
  const opscompassHome = path.join(homedir(), '.opscompassdev');
13
+ const cliCommand = "opscompassdev";
12
14
 
13
15
  const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
14
16
  const authDomain = "auth-dev.opscompass.com";
15
17
  const audience = "https://fa-sampleapi-cus-dev.azurewebsites.net";
16
18
  const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
19
+ const isLocal = true
17
20
 
18
21
  module.exports = {
19
22
  OpsCompassClient,
23
+ ScriptType,
20
24
  oAuthClient,
21
25
  opscompassHome,
26
+ isLocal,
27
+ cliCommand
22
28
  };
@@ -1,21 +1,28 @@
1
1
  // production: OpsCompassClient is referenced from npm package
2
2
 
3
+
3
4
  const {
4
5
  OpsCompassClient,
6
+ ScriptType,
5
7
  OAuthHandler
6
8
  } = require("@opscompass/opscompass-api");
7
9
 
8
10
  const path = require("path");
9
11
  const { homedir } = require("os");
10
12
  const opscompassHome = path.join(homedir(), '.opscompass');
13
+ const cliCommand = "opscompass";
11
14
 
12
15
  const clientId = "vOakDaOv4L26f3uuI4sp3KC1Sov3nsW2";
13
16
  // default authDomain
14
17
  // default audience
15
18
  const oAuthClient = new OAuthHandler(clientId);
19
+ const isLocal = false
16
20
 
17
21
  module.exports = {
18
22
  OpsCompassClient,
23
+ ScriptType,
19
24
  oAuthClient,
20
25
  opscompassHome,
26
+ isLocal,
27
+ cliCommand
21
28
  };
package/index.js CHANGED
@@ -3,6 +3,8 @@
3
3
  const modules = require("./modules.js");
4
4
  const handleError = require('./error.js');
5
5
  const { canReadStoredCredentials } = require("./credentials.js");
6
+ const { versionCheck } = require("./updates.js");
7
+ const { isLocal } = require("./environment/current.js");
6
8
 
7
9
  function requiresLogin() {
8
10
  console.log("You aren't logged in. Please run `opscompass login` to log in.");
@@ -28,6 +30,9 @@ function help() {
28
30
  }
29
31
 
30
32
  (async function() {
33
+ if (!isLocal) {
34
+ versionCheck();
35
+ }
31
36
  const [proc, command, commandModule, ...args] = process.argv;
32
37
  const moduleName = commandModule?.toLowerCase() ?? "";
33
38
  if (moduleName === "" || moduleName === "help") {
package/lib/cliHelpers.js CHANGED
@@ -1,3 +1,8 @@
1
+ const fs = require('fs-extra');
2
+ const https = require('https');
3
+ const path = require("path");
4
+ const AdmZip = require('adm-zip');
5
+
1
6
  /**
2
7
  * Users need to be able to enter array data into the CLI. They do this by submitting identical argument names with each element value.
3
8
  * This method consolidates all data associated with the specified argument names, and creates an array object.
@@ -45,6 +50,156 @@ function setArgumentArrays(argumentNames, args) {
45
50
  return args;
46
51
  }
47
52
 
53
+ /**
54
+ * Writes provided data to the specified file.
55
+ * @param {string} newFilePath the path of the new file
56
+ * @param {Object} data the data to write to the file
57
+ * @param {number} mode sets the file permissions
58
+ * @returns when the file write is complete
59
+ */
60
+ async function writeFile(newFilePath, data, mode) {
61
+ try {
62
+ await fs.writeFile(newFilePath, JSON.stringify(data), { mode });
63
+ } catch (err) {
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Deletes a file based on the passed parameters.
70
+ * @param {string} parentDirectoryPath the path to the parent directory of the file to delete
71
+ * @param {string} deleteFileName the name of the file to delete
72
+ */
73
+ function deleteFile(deleteFilePath) {
74
+ try {
75
+ fs.unlinkSync(deleteFilePath);
76
+ } catch (err) {
77
+ console.log(`Something went wrong during deletion. ${err}`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Deletes a directory based on the passed parameters.
83
+ * Recursively force deletes contents.
84
+ * @param {string} directoryPath the path to the directory to delete
85
+ */
86
+ function deleteDirectory(directoryPath) {
87
+ try {
88
+ fs.rmSync(directoryPath, { recursive: true, force: true });
89
+ } catch (err) {
90
+ console.log(`Something went wrong while deleting directory: ${err}`);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Downloads a file from the provided url to the given path with the given file name.
96
+ * @param {string} downloadUrl the download source
97
+ * @param {string} downloadFilePath the download destination
98
+ * @param {string} downloadName the downloaded file name
99
+ * @returns {Promise<void>} Returns once the download is complete
100
+ */
101
+ async function downloadFile(downloadUrl, downloadFilePath, downloadName) {
102
+ return new Promise((resolve, reject) => {
103
+ // Download the file
104
+ https.get(downloadUrl, (res) => {
105
+
106
+ // Open file in local filesystem
107
+ const file = fs.createWriteStream(path.join(downloadFilePath, downloadName));
108
+
109
+ // Write data into local file
110
+ res.pipe(file);
111
+
112
+ // Close the file
113
+ file.on('finish', () => {
114
+ file.close();
115
+ resolve();
116
+ });
117
+ }).on("error", (err) => {
118
+ console.log("downloadFile failed...");
119
+ reject(err);
120
+ });
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Unzips a file based on the passed parameters. Saves the unziped contents in the directory
126
+ * containing the .zip.
127
+ * @param {string} unzipFileLocation the path to the directory to store the unzipped contents
128
+ * @param {string} unzipFileName the name of the unzipped file
129
+ */
130
+ async function unzipFile(unzipFileLocation, unzipFileName) {
131
+ const zipFileLocation = path.join(unzipFileLocation, unzipFileName);
132
+ try {
133
+ const zip = new AdmZip(zipFileLocation);
134
+ zip.extractAllTo(unzipFileLocation);
135
+ } catch (err) {
136
+ deleteFile(zipFileLocation);
137
+ throw("Something went wrong during unzipping.\nIf you specified a script version, confirm it is correct.\nIf the error continues, contact your OpsCompass rep.");
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Moves a directory and contents from one location to another.
143
+ * @param {string} sourcePath the directory to move
144
+ * @param {string} destinationPath where to move the directory to
145
+ */
146
+ async function moveFolder(sourcePath, destinationPath) {
147
+ try {
148
+ await fs.move(sourcePath, destinationPath);
149
+ } catch (err) {
150
+ throw (err);
151
+ }
152
+ }
153
+
154
+ /**
155
+ * See if the .opscompass(dev|demo) directory contains passed folder; if not, try to create it.
156
+ * @param {string} folderPath the path to the folder to find or create
157
+ * @returns {string} The path to the found or created folder
158
+ */
159
+ function findOrCreateFolder(folderPath) {
160
+ try {
161
+ fs.accessSync(folderPath);
162
+ } catch {
163
+ // mode 700: only the user can interact with the directory
164
+ // and can do everything in that directory (read, write, list)
165
+ fs.mkdirSync(folderPath, { mode: "700" });
166
+ }
167
+ return path.join(folderPath);
168
+ }
169
+
170
+ /**
171
+ * Checks to see if the current user can read the file at the provided file path.
172
+ * @param {string} filePath the path to the file to check read permission
173
+ * @returns {boolean} if the user can read the file
174
+ */
175
+ function canReadFile(filePath) {
176
+ try {
177
+ fs.accessSync(filePath, fs.constants.R_OK);
178
+ return true;
179
+ } catch {
180
+ return false;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Object that makes file permissions a bit more user friendly.
186
+ *
187
+ * mode 600: the user can read/write (and not execute)
188
+ * but only the user can interact with the file
189
+ */
190
+ const FilePermissions = {
191
+ userReadWrite: 600
192
+ };
193
+
48
194
  module.exports = {
49
- setArgumentArrays
195
+ setArgumentArrays,
196
+ writeFile,
197
+ deleteFile,
198
+ deleteDirectory,
199
+ downloadFile,
200
+ unzipFile,
201
+ findOrCreateFolder,
202
+ canReadFile,
203
+ moveFolder,
204
+ FilePermissions
50
205
  };
@@ -0,0 +1,182 @@
1
+ const fs = require("fs-extra");
2
+ const path = require("path");
3
+ const { opscompassHome, ScriptType, OpsCompassClient } = require("../environment/current.js");
4
+ const {
5
+ findOrCreateFolder,
6
+ deleteDirectory,
7
+ downloadFile,
8
+ unzipFile,
9
+ deleteFile,
10
+ moveFolder,
11
+ writeFile,
12
+ canReadFile,
13
+ FilePermissions
14
+ } = require("./cliHelpers.js");
15
+
16
+ const SRC_FOLDER_NAME = "src";
17
+ const METADATA_FILE_NAME = "metadata.json";
18
+ const BASE_SCRIPTS_RUN_ALL_RELATIVE_PATH = "scripts/runall.sh";
19
+
20
+ /**
21
+ * Writes provided data to the specified file in the home directory.
22
+ * @param {string} fileName the name of the file to write to
23
+ * @param {Object} data object to write to the file
24
+ * @param {number} mode sets the file permissions
25
+ * @returns when the file write is complete
26
+ */
27
+ async function writeFileToHome(fileName, data, mode) {
28
+ findOrCreateFolder(opscompassHome);
29
+
30
+ // promisify the callback of fs.writeFile
31
+ return new Promise((resolve, reject) => {
32
+ try {
33
+ // write the token data to the file
34
+ fs.writeFile(
35
+ path.join(opscompassHome, fileName),
36
+ JSON.stringify(data),
37
+ { mode: mode },
38
+ () => resolve());
39
+ } catch (ex) {
40
+ reject(ex);
41
+ }
42
+ });
43
+ }
44
+
45
+ /**
46
+ * Finds script type folder. If it doesn't exist, it will be created.
47
+ * @returns path to specific folder for script type
48
+ */
49
+ function findOrCreateScriptTypeFolder(scriptType) {
50
+ findOrCreateScriptsFolder();
51
+ const folderPath = scriptTypeFolderPath(scriptType)
52
+ findOrCreateFolder(folderPath);
53
+ return folderPath;
54
+ }
55
+
56
+ /**
57
+ * Finds the scripts folder. If it doesn't exist, it will be created.
58
+ * @returns path to the scripts folder
59
+ */
60
+ function findOrCreateScriptsFolder() {
61
+ findOrCreateFolder(opscompassHome);
62
+ return findOrCreateFolder(`${opscompassHome}/scripts`);
63
+ }
64
+
65
+ /**
66
+ * Checks the installed script version currently installed for the specified type
67
+ * @param {string} scriptType the type of script to version check
68
+ * @returns the version installed for the specified script version
69
+ */
70
+ async function getInstalledScriptVersion(scriptType) {
71
+ const scriptMetadata = await getScriptMetadata(scriptType);
72
+ return scriptMetadata?.version;
73
+ }
74
+
75
+ /**
76
+ * Fetch the contents of the script metadata file.
77
+ * @param {string} scriptType the type of the script to fetch metadata for
78
+ * @returns a metadata object
79
+ */
80
+ async function getScriptMetadata(scriptType) {
81
+ const scriptsPath = findOrCreateScriptsFolder();
82
+
83
+ try {
84
+ const metadataPath = path.join(scriptsPath, scriptType, METADATA_FILE_NAME);
85
+
86
+ // Check to make sure scripts have been downloaded
87
+ if (!canReadFile(metadataPath)) {
88
+ return;
89
+ }
90
+
91
+ const fileContents = await fs.readFile(
92
+ metadataPath,
93
+ { encoding: "utf-8" }
94
+ );
95
+ return JSON.parse(fileContents);
96
+ } catch (err) {
97
+ throw err;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Removes the currently installed script for the specified script type
103
+ * @param {string} scriptType the script type to remove
104
+ */
105
+ function removeCurrentlyInstalledScript(scriptType) {
106
+ const scriptsPath = findOrCreateScriptsFolder();
107
+ deleteDirectory(path.join(scriptsPath, scriptType, SRC_FOLDER_NAME));
108
+ }
109
+
110
+ /**
111
+ * Returns folder path for passed script type.
112
+ * @param {string} scriptType script type to use when generating folder path
113
+ * @returns {string} folder path for script type
114
+ */
115
+ function scriptTypeFolderPath(scriptType) {
116
+ return `${opscompassHome}/scripts/${scriptType}`;
117
+ }
118
+
119
+ /**
120
+ *
121
+ * @param {string} scriptType script type to use when downloading scripts
122
+ * @param {string} scriptVersion script version to use when downloading scripts. If undefined, downloads latest.
123
+ * @param {string} companySlug company slug to use when downloading scripts
124
+ * @param {OpsCompassClient} client client to use to call OpsCompass api
125
+ */
126
+ async function downloadScriptsToHome(scriptType, scriptVersion, companySlug, client) {
127
+ // Ensure base scripts are downloaded/updated
128
+ if (scriptType !== ScriptType.baseScripts) {
129
+ await downloadScriptsToHome(ScriptType.baseScripts, undefined, companySlug, client);
130
+ }
131
+
132
+ // Download specific script
133
+ const scriptDownloadInfo = await client.dataGatheringScripts.getScriptsUrl(companySlug, scriptType, scriptVersion);
134
+ const scriptTypeFolderPath = findOrCreateScriptTypeFolder(scriptType);
135
+ const fileName = scriptDownloadInfo.fileName;
136
+ scriptVersion = fileName.replace(".zip", "");
137
+
138
+ removeCurrentlyInstalledScript(scriptType);
139
+ await downloadFile(scriptDownloadInfo.downloadUrl, scriptTypeFolderPath, fileName);
140
+ await unzipFile(scriptTypeFolderPath, fileName);
141
+
142
+ // Move contents from script version folder to src
143
+ await moveFolder(path.join(scriptTypeFolderPath, scriptVersion), path.join(scriptTypeFolderPath, SRC_FOLDER_NAME));
144
+
145
+ // Set the script's metadata
146
+ await setScriptMetadata(scriptTypeFolderPath, scriptVersion);
147
+
148
+ deleteFile(path.join(scriptTypeFolderPath, fileName));
149
+ }
150
+
151
+ /**
152
+ * Creates/updates a file that contains a specific script's metadata.
153
+ * @param {string} scriptFolderPath path to the script folder
154
+ * @param {string} scriptVersion the version of the downloaded script
155
+ */
156
+ async function setScriptMetadata(scriptFolderPath, scriptVersion) {
157
+ const scriptMetadata = {
158
+ version: scriptVersion
159
+ };
160
+
161
+ const metadataFilePath = path.join(scriptFolderPath, METADATA_FILE_NAME);
162
+
163
+ // Clear out old metadata if present
164
+ if (canReadFile(metadataFilePath)) {
165
+ deleteFile(metadataFilePath);
166
+ }
167
+
168
+ await writeFile(
169
+ metadataFilePath,
170
+ scriptMetadata
171
+ );
172
+ }
173
+
174
+ module.exports = {
175
+ SRC_FOLDER_NAME,
176
+ BASE_SCRIPTS_RUN_ALL_RELATIVE_PATH,
177
+ writeFileToHome,
178
+ findOrCreateScriptTypeFolder,
179
+ getInstalledScriptVersion,
180
+ removeCurrentlyInstalledScript,
181
+ downloadScriptsToHome
182
+ };
@@ -0,0 +1,52 @@
1
+ const { getOpsCompassClient } = require("../opscompass.js");
2
+ const { getCredentials } = require("../credentials.js");
3
+
4
+ async function transferOracleDatabaseMetadata(args) {
5
+ const callParams = {};
6
+ for (let i = 0; i < args.length - 1; i++) {
7
+ switch (args[i].toLowerCase()) {
8
+ case "--filepath":
9
+ callParams.filePath = args[++i];
10
+ break;
11
+ case "--company":
12
+ callParams.company = args[++i];
13
+ break;
14
+ }
15
+ }
16
+
17
+
18
+ const client = await getOpsCompassClient();
19
+ const response = await client.compliance.transferOracleDatabaseMetadata(callParams.company, callParams.filePath);
20
+
21
+ console.log(JSON.stringify(response, null, 2));
22
+ }
23
+
24
+
25
+ async function printHelp() {
26
+ console.log("Actions available for compliance:");
27
+ console.log();
28
+ console.log("transfer-oracle-database-metadata", "Transfers OpsCompass Oracle Database metadata report into OpsCompass for processing");
29
+ console.log("Parameters:");
30
+ console.log("--company [company_slug]");
31
+ console.log("--filePath [path] Path of the file to transfer to OpsCompass for processing.");
32
+ console.log();
33
+ }
34
+
35
+
36
+ const complianceModule = (action, ...args) => {
37
+ switch (action?.toLowerCase() ?? "") {
38
+ case "transfer-oracle-database-metadata":
39
+ return transferOracleDatabaseMetadata(args);
40
+ case "help":
41
+ case "":
42
+ return printHelp();
43
+ default:
44
+ console.log("Unknown command:", action);
45
+ return printHelp();
46
+ }
47
+ };
48
+
49
+ complianceModule.requiresLogin = true;
50
+ complianceModule.description = "Provides access to details about resource Compliance in OpsCompass.";
51
+
52
+ module.exports = complianceModule;
@@ -0,0 +1,166 @@
1
+ const { getOpsCompassClient } = require("../opscompass.js");
2
+ const { ScriptType, cliCommand } = require("../environment/current.js");
3
+ const { downloadScriptsToHome, findOrCreateScriptTypeFolder, SRC_FOLDER_NAME, BASE_SCRIPTS_RUN_ALL_RELATIVE_PATH, getInstalledScriptVersion } = require("../lib/homeInteraction.js");
4
+ const { canReadFile } = require("../lib/cliHelpers.js");
5
+ const semver = require("semver");
6
+ const path = require("path");
7
+ const fs = require("fs-extra");
8
+ const util = require('util');
9
+ const exec = util.promisify(require('child_process').exec);
10
+
11
+ /**
12
+ * Downloads data gathering scripts based on the given scriptType.
13
+ */
14
+ async function downloadScripts(args) {
15
+ let companySlug = undefined;
16
+ let scriptType = undefined;
17
+ let scriptVersion = undefined
18
+ for (let i = 0; i < args.length - 1; i++) {
19
+ switch (args[i].toLowerCase()) {
20
+ case "--company":
21
+ companySlug = args[++i];
22
+ break;
23
+ case "--script-type":
24
+ case "--scripttype":
25
+ scriptType = args[++i];
26
+ break;
27
+ case "--script-version":
28
+ case "--scriptversion":
29
+ scriptVersion = args[++i];
30
+ break;
31
+ }
32
+ }
33
+
34
+ // If script type is not supported, we do not want to continue.
35
+ const scriptTypes = Object.values(ScriptType);
36
+ if (!scriptTypes.includes(scriptType)) {
37
+ console.log("Unsupported script type...");
38
+ return;
39
+ }
40
+
41
+ try {
42
+ const client = await getOpsCompassClient();
43
+
44
+ await downloadScriptsToHome(scriptType, scriptVersion, companySlug, client);
45
+
46
+ console.log("Download Successful!");
47
+ } catch (err) {
48
+ console.log("Download failed...");
49
+ console.log(err);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Checks the installed scripts version against the latest scripts version for a given scriptType.
55
+ */
56
+ async function checkScriptUpdates(args) {
57
+ let companySlug = undefined;
58
+ let scriptType = undefined;
59
+ for (let i = 0; i < args.length - 1; i++) {
60
+ switch (args[i].toLowerCase()) {
61
+ case "--company":
62
+ companySlug = args[++i];
63
+ break;
64
+ case "--script-type":
65
+ case "--scripttype":
66
+ scriptType = args[++i];
67
+ break;
68
+ }
69
+ }
70
+
71
+ // If script type is not supported, we do not want to continue.
72
+ const scriptTypes = Object.values(ScriptType);
73
+ if (!scriptTypes.includes(scriptType)) {
74
+ console.log("Unsupported script type...");
75
+ return;
76
+ }
77
+
78
+ const client = await getOpsCompassClient();
79
+ const currentScriptVersion = await getInstalledScriptVersion(scriptType);
80
+
81
+ if (!currentScriptVersion) {
82
+ console.log(`Local scripts for type ${scriptType} not found. Please make sure they are installed.`);
83
+ console.log("If the issue persists, please contact your OpsCompass rep.");
84
+ return;
85
+ }
86
+
87
+ const latestScriptVersion = await client.dataGatheringScripts.checkScriptUpdates(companySlug, scriptType);
88
+
89
+ //Semver returns true if the latest version is higher than the currentScriptVersion.
90
+ if (semver.gt(latestScriptVersion.scriptVersion, currentScriptVersion)) {
91
+ console.log(yellowText, `Warning! You are using version ${currentScriptVersion} of the the ${scriptType} scripts, but the latest version is ${latestScriptVersion.scriptVersion}.`);
92
+ console.log(yellowText, `To update to the latest version, please run: ${cliCommand} data-gathering-scripts download-scripts --company ${companySlug} --scriptType ${scriptType} `);
93
+ } else {
94
+ console.log(greenText, `You are using the latest version of ${scriptType} script, ${latestScriptVersion.scriptVersion}.`);
95
+ console.log();
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Manually runs the installed scripts. The base scripts has a runall.sh file.
101
+ * This file runs all installed modules.
102
+ */
103
+ async function manuallyRunScripts() {
104
+ try {
105
+ const baseScriptFolderPath = findOrCreateScriptTypeFolder(ScriptType.baseScripts);
106
+ const runAllFilePath = path.join(baseScriptFolderPath, SRC_FOLDER_NAME, BASE_SCRIPTS_RUN_ALL_RELATIVE_PATH);
107
+
108
+ if (canReadFile(runAllFilePath)) {
109
+ const runAllScript = await fs.readFile(
110
+ runAllFilePath,
111
+ { encoding: "utf-8" }
112
+ );
113
+
114
+ const { stdout, stderr } = await exec(runAllScript);
115
+ if (!!stderr) {
116
+ console.log(`Error: ${stderr}`);
117
+ } else {
118
+ console.log(stdout);
119
+ }
120
+ } else {
121
+ throw "Cannot manually run scripts. Make sure the scripts are downloaded.\nIf the issue persists, contact your OpsCompass rep.";
122
+ }
123
+ } catch (err) {
124
+ console.log(err);
125
+ }
126
+ }
127
+
128
+ async function printHelp() {
129
+ console.log("Actions available for data-gathering-scripts:");
130
+ console.log();
131
+ console.log("download-scripts", "Downloads scripts for the passed script type.");
132
+ console.log("Parameters:");
133
+ console.log("--company [company_slug]");
134
+ console.log("--script-type ['oracle-cis']");
135
+ console.log("--script-version (optional) [version] if not provided, the latest script will be downloaded");
136
+ console.log();
137
+ console.log("check-script-updates", "Checks locally installed script version against the latest published version for the passed script type.");
138
+ console.log("Parameters:");
139
+ console.log("--company [company_slug]");
140
+ console.log("--script-type ['oracle-cis']");
141
+ console.log();
142
+ console.log("manually-run-scripts", "Do not run this unless you know what you are doing. This manually runs all the scripts.");
143
+ console.log();
144
+ }
145
+
146
+ const dataGatheringScriptsModule = (action, ...args) => {
147
+ switch (action?.toLowerCase() ?? "") {
148
+ case "download-scripts":
149
+ return downloadScripts(args);
150
+ case "check-script-updates":
151
+ return checkScriptUpdates(args);
152
+ case "manually-run-scripts":
153
+ return manuallyRunScripts()
154
+ case "help":
155
+ case "":
156
+ return printHelp();
157
+ default:
158
+ console.log("Unknown command:", action);
159
+ return printHelp();
160
+ }
161
+ };
162
+
163
+ dataGatheringScriptsModule.requiresLogin = true;
164
+ dataGatheringScriptsModule.description = "Provides access to OpsCompass data gathering scripts.";
165
+
166
+ module.exports = dataGatheringScriptsModule;
@@ -321,6 +321,44 @@ async function updateOracleDatabaseConfiguration(args) {
321
321
  console.log(JSON.stringify(oracleDatabaseConfiguration, null, 2));
322
322
  }
323
323
 
324
+ async function updateOracleDatabaseConfigurations(args) {
325
+
326
+ let callParamsArray = [];
327
+ let jsonIndex = args.indexOf('--json-updates')
328
+ let idIndex = args.indexOf('--id')
329
+ let callParams = {};
330
+
331
+ /* Process bulk update with JSON */
332
+ if (jsonIndex !== -1) {
333
+ callParamsArray = args[jsonIndex + 1]
334
+ } else if (idIndex !== -1) {
335
+ /* If no '--json-update' flag, process bulk update with parameter flags (e.g. --id, --name, etc.) */
336
+ for(let i = 0; i < args.length - 1; i++) {
337
+ if(args[i] === '--id') {
338
+ /* Reset callParams object when a second id is encountered */
339
+ callParams = {};
340
+ /* Push callParams into the array. */
341
+ callParamsArray.push(callParams)
342
+ /* Create the object's properties based on the index (e.g. if the index is --id, you'll find the value at the next index */
343
+ callParams.id = args[i + 1];
344
+ } else if(args[i] === '--configurationName') {
345
+ callParams.configurationName = args[i + 1];
346
+ } else if(args[i] === '--action') {
347
+ callParams.action = args[i + 1];
348
+ } else if(args[i] === '--connectionstring') {
349
+ callParams.connectionString = args[i + 1];
350
+ }
351
+ }
352
+ } else {
353
+ console.warn("Invalid input, please see help for examples.")
354
+ }
355
+ /* Call the API and print to console */
356
+ const client = await getOpsCompassClient();
357
+ const oracleDatabaseConfigurations = await client.licenseManager.updateOracleDatabaseConfigurations(callParamsArray);
358
+ console.log(JSON.stringify(oracleDatabaseConfigurations, null, 2));
359
+ }
360
+
361
+
324
362
  async function updateVCenterConfiguration(args) {
325
363
  const callParams = {};
326
364
  for (let i = 0; i < args.length - 1; i++) {
@@ -347,11 +385,52 @@ async function updateVCenterConfiguration(args) {
347
385
  }
348
386
 
349
387
  const client = await getOpsCompassClient();
350
- const oracleDatabaseConfiguration = await client.licenseManager.updateVCenterConfiguration(callParams.id, callParams);
351
-
352
- console.log(JSON.stringify(oracleDatabaseConfiguration, null, 2));
388
+ const vCenterConfiguration = await client.licenseManager.updateVCenterConfiguration(callParams.id, callParams);
389
+ console.log(JSON.stringify(vCenterConfiguration, null, 2));
353
390
  }
354
391
 
392
+ async function updateVCenterConfigurations(args) {
393
+
394
+ let callParamsArray = [];
395
+ let jsonIndex = args.indexOf('--json-updates')
396
+ let idIndex = args.indexOf('--id')
397
+ let callParams = {};
398
+
399
+ /* Process bulk update with JSON */
400
+ if (jsonIndex !== -1) {
401
+ callParamsArray = args[jsonIndex + 1]
402
+ } else if (idIndex !== -1) {
403
+ /* If no '--json-update' flag, process bulk update with parameter flags (e.g. --id, --name, etc.) */
404
+ for(let i = 0; i < args.length - 1; i++) {
405
+ if(args[i] === '--id') {
406
+ /* Reset callParams object when a second id is encountered */
407
+ callParams = {};
408
+ /* if theres an existing callParams object, toss it into the array and move on. */
409
+ callParamsArray.push(callParams)
410
+ /* Create the object's properties based on the index (e.g. if the index is --id, you'll find the value at the next index */
411
+ callParams.id = args[i + 1];
412
+ } else if(args[i] === '--configurationName') {
413
+ callParams.configurationName = args[i + 1];
414
+ } else if(args[i] === '--action') {
415
+ callParams.action = args[i + 1];
416
+ } else if(args[i] === '--connection') {
417
+ callParams.connection = args[i + 1];
418
+ } else if(args[i] === '--user') {
419
+ callParams.user = args[i + 1];
420
+ } else if(args[i] === '--password') {
421
+ callParams.password = args[i + 1];
422
+ }
423
+ }
424
+ } else {
425
+ console.warn("Invalid input, please see help for examples.")
426
+ }
427
+
428
+ /* Call the API and print to console */
429
+ const client = await getOpsCompassClient();
430
+ const vCenterConfigurations = await client.licenseManager.updateVCenterConfigurations(callParamsArray);
431
+ console.log(JSON.stringify(vCenterConfigurations, null, 2));
432
+ }
433
+
355
434
  async function printHelp() {
356
435
  console.log("Actions available for license-manager:");
357
436
  console.log();
@@ -408,7 +487,7 @@ async function printHelp() {
408
487
  console.log();
409
488
  console.log("update-monitoring-configuration", "Update a single monitoring configuration.");
410
489
  console.log("Parameters:");
411
- console.log("--id [monitoring_configuration_id]");
490
+ console.log("--id [monitoring_configuration id]");
412
491
  console.log("--configurationName (optional) [unique name]");
413
492
  console.log("--dataFileRetainDays (optional) [determines how many days to retain encrypted output files locally]");
414
493
  console.log("--dataFileRetainTextDays (optional) [determines how many days to retain individual script output files locally]");
@@ -421,19 +500,45 @@ async function printHelp() {
421
500
  console.log();
422
501
  console.log("update-oracle-database-configuration", "Update a single oracle database configuration.");
423
502
  console.log("Parameters:");
424
- console.log("--id [monitoring_configuration_id]");
503
+ console.log("--id [configuration id]");
425
504
  console.log("--name (optional) [unique name]");
426
505
  console.log("--action (optional) [allowed actions: \"skip\"]");
427
506
  console.log("--connectionString (optional) [the database connection string]");
428
507
  console.log();
508
+ console.log("update-oracle-database-configurations", "Bulk update oracle database configurations.");
509
+ console.log("Parameters:");
510
+ console.log("--id [configuration id]");
511
+ console.log("--name (optional) [unique name]");
512
+ console.log("--action (optional) [allowed actions: \"skip\"]");
513
+ console.log("--connectionString (optional) [the database connection string]");
514
+ console.log("OR --json-updates [stringified json objects with your updates]");
515
+ console.log("For quick updates, you may use the above parameters");
516
+ console.log(`e.g. opscompass license-manager update-oracle-database-configurations --id 57 --configurationName "updatedName" --id 62 --configurationName "otherUpdatedName" --id 77 --configurationName "lastUpdatedName";`);
517
+ console.log("For larger updates, JavaScript Object Notation (JSON) may be used with the --json-updates flag");
518
+ console.log(`e.g. opscompass license-manager update-oracle-database-configurations --json-updates '[{"id":"57","configurationName":"updatedName"},{"id":"77", "configurationName":"otherUpdatedName", "action":"null"},{"id":"79", "configurationName":"lastUpdatedName"}]'`);
519
+ console.log();
429
520
  console.log("update-vcenter-configuration", "Update a single vcenter configuration.");
430
521
  console.log("Parameters:");
431
- console.log("--id [monitoring_configuration_id]");
522
+ console.log("--id [configuration id]");
523
+ console.log("--name (optional) [unique name]");
524
+ console.log("--action (optional) [allowed actions: \"skip\"]");
525
+ console.log("--connection (optional) [the hostname or ip address]");
526
+ console.log("--user (optional) [connection username]");
527
+ console.log("--password (optional) [connection password]");
528
+ console.log();
529
+ console.log("update-vcenter-configurations", "Bulk Update vcenter configurations.");
530
+ console.log("Parameters:");
531
+ console.log("--id [configuration id]");
432
532
  console.log("--name (optional) [unique name]");
433
533
  console.log("--action (optional) [allowed actions: \"skip\"]");
434
534
  console.log("--connection (optional) [the hostname or ip address]");
435
535
  console.log("--user (optional) [connection username]");
436
536
  console.log("--password (optional) [connection password]");
537
+ console.log("OR --json-updates [stringified json objects with your updates]");
538
+ console.log("For quick updates, you may use the above parameters");
539
+ console.log(`e.g. opscompass license-manager update-vcenter-configurations --id 137 --configurationName "updatedName" --id 138 --configurationName "otherUpdatedName" --id 144 --configurationName "lastUpdatedName";`);
540
+ console.log("For larger updates, JavaScript Object Notation (JSON) may be used with the --json-updates flag");
541
+ console.log(`e.g. opscompass license-manager update-vcenter-configurations --json-updates '[{"id":"137","configurationName":"updatedName"},{"id":"138","configurationName":"otherUpdatedName"},{"id":"144","configurationName":"lastUpdatedName"}]'`);
437
542
  console.log();
438
543
  console.log("delete-monitoring-configuration", "Delete a monitoring configuration");
439
544
  console.log("Parameters:");
@@ -475,8 +580,12 @@ const licenseManagerModule = (action, ...args) => {
475
580
  return updateMonitoringConfiguration(args);
476
581
  case "update-oracle-database-configuration":
477
582
  return updateOracleDatabaseConfiguration(args);
583
+ case "update-oracle-database-configurations":
584
+ return updateOracleDatabaseConfigurations(args);
478
585
  case "update-vcenter-configuration":
479
586
  return updateVCenterConfiguration(args);
587
+ case "update-vcenter-configurations":
588
+ return updateVCenterConfigurations(args);
480
589
  case "delete-monitoring-configuration":
481
590
  return deleteMonitoringConfiguration(args);
482
591
  case "delete-oracle-database-configuration":
@@ -495,4 +604,4 @@ const licenseManagerModule = (action, ...args) => {
495
604
  licenseManagerModule.requiresLogin = true;
496
605
  licenseManagerModule.description = "Provides access to details about License Management in OpsCompass.";
497
606
 
498
- module.exports = licenseManagerModule;
607
+ module.exports = licenseManagerModule;
package/modules.js CHANGED
@@ -1,6 +1,9 @@
1
1
  const resources = require("./modules/resources.js");
2
2
  const accounts = require("./modules/accounts.js");
3
3
  const licenseManager = require("./modules/license-manager.js");
4
+ const compliance = require("./modules/compliance.js");
5
+ const dataGatheringScripts = require("./modules/data-gathering-scripts.js");
6
+
4
7
 
5
8
  /* login acts like a module, even though it's special */
6
9
  const login = require("./login.js");
@@ -9,5 +12,7 @@ module.exports = {
9
12
  login,
10
13
  resources,
11
14
  accounts,
15
+ compliance,
12
16
  "license-manager": licenseManager,
17
+ "data-gathering-scripts": dataGatheringScripts
13
18
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opscompass/opscompass-cli",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
4
4
  "description": "Calls OpsCompass's APIs",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -15,9 +15,12 @@
15
15
  "author": "opscompass",
16
16
  "license": "SEE LICENSE IN license.txt",
17
17
  "dependencies": {
18
- "@opscompass/opscompass-api": "^1.0.9",
18
+ "@opscompass/opscompass-api": "^1.0.10",
19
+ "adm-zip": "^0.5.9",
19
20
  "axios": "^0.21.1",
20
- "open": "^8.2.1"
21
+ "fs-extra": "^10.1.0",
22
+ "open": "^8.2.1",
23
+ "semver": "^7.3.7"
21
24
  },
22
25
  "bin": {
23
26
  "opscompass": "index.js"
package/updates.js ADDED
@@ -0,0 +1,33 @@
1
+ const pkg = require("./package.json");
2
+ const semver = require("semver");
3
+ const { exec } = require("child_process");
4
+ const { greenText, yellowText } = require("./colors.js");
5
+
6
+ /* versionCheck sends a command to the terminal to check the latest package version and compares it to the current version specified in package.json, prompting the user to upgrade if it is out of date. */
7
+ /* This is turned off by default when using the local environment. To turn it on for dev purposes, comment out isLocal check in index.js */
8
+
9
+ function versionCheck() {
10
+
11
+ const environmentSpecificPackageVersion = `npm view ${pkg.name} version`
12
+ /* latestVersion is the standard output(stdout), which is read and compared to current package version */
13
+ exec(environmentSpecificPackageVersion, (error, latestVersion, stderr) => {
14
+ if (error) {
15
+ console.log(`error: ${error.message}`);
16
+ return;
17
+ }
18
+ if (stderr) {
19
+ console.log(`stderr: ${stderr}`);
20
+ };
21
+ /* Semver used to semantically compare version numbers */
22
+ if (semver.gt(latestVersion, pkg.version)) {
23
+ console.error(yellowText, `\nWarning! You are using CLI version ${pkg.version}, but the latest version is ${latestVersion}. To upgrade to the latest version, please run:`);
24
+ /* Prompt user to upgrade to the correct package based on their current environment */
25
+ console.error(greenText, `\nnpm install -g ${pkg.name}@${latestVersion}\n`);
26
+ return;
27
+ }
28
+ });
29
+ };
30
+
31
+ module.exports = {
32
+ versionCheck
33
+ };