mirror of
https://github.com/Alfresco/alfresco-ng2-components.git
synced 2025-05-12 17:04:57 +00:00
[ACS-6396] cleanup unused CLI code (#9132)
* cleanup unused CLI code * [ci:force] update CLI readme
This commit is contained in:
parent
7300f74add
commit
979bf3ac59
@ -4,7 +4,7 @@ The ADF CLI provides a set of utilities to manage your ADF projects.
|
||||
|
||||
## Installation
|
||||
|
||||
To get started follow these instructions:
|
||||
To get started, follow these instructions:
|
||||
|
||||
```bash
|
||||
npm install @alfresco/adf-cli -g
|
||||
@ -41,24 +41,15 @@ In develop mode, the CLI takes the prebuilt scripts from the dist folder.
|
||||
## Commands
|
||||
|
||||
| **Commands** |**Description** |
|
||||
|--- |--- |
|
||||
| --- | --- |
|
||||
| changelog | Generate changelog report for two branches of git repository |
|
||||
|check-cs-env |Check cs env is up |
|
||||
|check-ps-env |Check ps env is up |
|
||||
|check-plugin-env |Check plugin status |
|
||||
|artifact-from-s3 |Get artifact from S3 |
|
||||
|artifact-to-s3 |Get artifact to S3 |
|
||||
|docker |Build and publish a docker image or create additional tag link |
|
||||
|init-aae-env |Init env|
|
||||
|init-aps-env |Init aps|
|
||||
|kubectl-delete |delete kubectl |
|
||||
|kubectl-image |This command allows you to update a specific service on the rancher env with a specific tag |
|
||||
|npm-publish | publish on npm |
|
||||
| update-commit-sha | his command allows you to update the commit sha as part of the `package.json`. Your `package.json` must to have an existing property called "commit" |
|
||||
|update-version |This command allows you to update the adf dependencies and js-api with different versions Update adf libs and js-api with latest alpha|
|
||||
|licenses |Create a 3th party license file |
|
||||
|audit |Check the security risk dependency in your package.json |
|
||||
|scan-env |Scan the environment to show its status |
|
||||
| check-cs-env | Check cs env is up |
|
||||
| check-plugin-env | Check plugin status |
|
||||
| docker | Build and publish a docker image or create additional tag link |
|
||||
| init-aae-env | Init env |
|
||||
| init-aps-env | Init aps |
|
||||
| licenses | Create a 3th party license file |
|
||||
| audit | Check the security risk dependency in your package.json |
|
||||
|
||||
## Examples
|
||||
|
||||
@ -138,6 +129,7 @@ adf-cli audit
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
The command provides 2 targets 'Publish' (default value) and 'Link'
|
||||
|
||||
Publish target
|
||||
@ -159,77 +151,6 @@ In case you don't need to publish a new image but you would like to create a lin
|
||||
adf-cli docker --target "link" --dockerRepo "${docker_repository}" --dockerTags "${TAGS}" --sourceTag "develop"
|
||||
```
|
||||
|
||||
|
||||
### Kubectl update pod image
|
||||
|
||||
This command allows you to update a specific service on the rancher env with a specific tag
|
||||
|
||||
```bash
|
||||
adf-cli kubectl-image --clusterEnv ${clusterEnv} --clusterUrl ${clusterUrl} --username ${username} --token ${token} --deployName ${deployName} --dockerRepo ${dockerRepo} --tag ${tag}
|
||||
```
|
||||
|
||||
You can use the option --installCheck to install kubectl as part of the command
|
||||
|
||||
### update version
|
||||
|
||||
This command allows you to update the adf dependencies and js-api with different versions
|
||||
|
||||
Update adf libs and js-api with latest alpha
|
||||
|
||||
```bash
|
||||
adf-cli update-version --alpha --pathPackage "$(pwd)"
|
||||
```
|
||||
|
||||
Update adf libs and js-api with latest beta
|
||||
|
||||
```bash
|
||||
adf-cli update-version --beta --pathPackage "$(pwd)"
|
||||
```
|
||||
|
||||
Update adf libs and js-api with latest
|
||||
|
||||
```bash
|
||||
adf-cli update-version --latest --pathPackage "$(pwd)"
|
||||
```
|
||||
|
||||
Update only adf libs with a specific version
|
||||
|
||||
```bash
|
||||
adf-cli update-version --version "3.2.0-fa5916ff413131513c3e382d7f27dd9b4cfa0e7e" --pathPackage "$(pwd)"
|
||||
```
|
||||
|
||||
Update only js-api with a specific version
|
||||
|
||||
```bash
|
||||
adf-cli update-version --vjs "3.2.0-fa5916ff413131513c3e382d7f27dd9b4cfa0e7e" --pathPackage "$(pwd)"
|
||||
```
|
||||
|
||||
Update adf libs and js-api with latest alpha locally
|
||||
|
||||
```bash
|
||||
adf-cli update-version --alpha --pathPackage "$(pwd)" --skipGnu
|
||||
```
|
||||
|
||||
### Update commit sha
|
||||
|
||||
This command allows you to update the commit sha as part of the `package.json`.
|
||||
Your `package.json` must to have an existing property called "commit"
|
||||
|
||||
```bash
|
||||
adf-cli update-commit-sha --pathProject "$(pwd)"
|
||||
```
|
||||
|
||||
You can use the option --pointer to chose a different pointer from the default HEAD.
|
||||
|
||||
```bash
|
||||
adf-cli update-commit-sha --pointer "HEAD~1" --pathProject "$(pwd)"
|
||||
```
|
||||
|
||||
Run command locally
|
||||
```bash
|
||||
adf-cli update-commit-sha --pathProject "$(pwd)" --skipGnu
|
||||
```
|
||||
|
||||
### Initialize activiti cloud env
|
||||
|
||||
The following command is in charge of Initializing the activiti cloud env with the default apps:
|
||||
@ -264,11 +185,3 @@ The following command is in charge of checking plugin status by given plugin nam
|
||||
adf-cli check-plugin-env --host "gateway_env" --pluginName "Name of the plugin" --clientId "clientId" --appName "appName" -u "username" -p "password"
|
||||
--ui "uiName"
|
||||
```
|
||||
|
||||
### Scan the environment
|
||||
|
||||
The following command will scan the environment to show various information on its current status:
|
||||
|
||||
```bash
|
||||
adf-cli scan-env --host "https://example.com" --clientId "clientId" -u "admin" -p "password"
|
||||
```
|
||||
|
@ -1,82 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv, exit } from 'node:process';
|
||||
import { exec } from './exec';
|
||||
import { logger } from './logger';
|
||||
import program from 'commander';
|
||||
|
||||
/**
|
||||
* Perform a test
|
||||
*
|
||||
* @param output output path
|
||||
*/
|
||||
function test(output: string) {
|
||||
const response = exec('test !', [`-d ${output} && mkdir ${output}`], {});
|
||||
logger.info(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy AWS S3
|
||||
*
|
||||
* @param artifact artifact name
|
||||
*/
|
||||
function awsCp(artifact: string) {
|
||||
logger.info(`aws s3 cp ${artifact}`);
|
||||
const response = exec(`aws s3 cp ${artifact}`, [`./s3-artifact.tmp ${artifact}`], {});
|
||||
logger.info(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zip artifact
|
||||
*
|
||||
* @param output output name
|
||||
*/
|
||||
function zipArtifact(output: string) {
|
||||
logger.info(`Perform zip artifact ${output}`);
|
||||
const response = exec('tar', ['-xvf', `./s3-artifact.tmp`, '-C ' + program.output], {});
|
||||
logger.info(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Artifact from S3 command
|
||||
*/
|
||||
export default function main() {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.requiredOption('-a, --artifact [type]', ' path to the s3 artifact (tar.bz2) to download and extract')
|
||||
.requiredOption('-o, --output [type]', 'directory to extract the archive to')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!program.artifact || program.artifact === '' || !program.output || program.output === '') {
|
||||
exit(1);
|
||||
} else if (program.artifact !== '' || program.output !== '') {
|
||||
zipArtifact(program.artifact);
|
||||
awsCp(program.output);
|
||||
}
|
||||
|
||||
test(program.output);
|
||||
awsCp(program.artifact);
|
||||
zipArtifact(program.output);
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv, exit } from 'node:process';
|
||||
import { exec } from './exec';
|
||||
import { logger } from './logger';
|
||||
import program from 'commander';
|
||||
|
||||
/**
|
||||
* Zip artifact
|
||||
*
|
||||
* @param artifact artifact name
|
||||
*/
|
||||
function zipArtifact(artifact: string) {
|
||||
logger.info(`Perform zip artifact ${artifact}`);
|
||||
|
||||
const response = exec(`tar cvfj ./s3-artifact.tmp -C ${program.artifact} ls ${program.artifact}`, [], {});
|
||||
logger.info(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy to AWS S3
|
||||
*
|
||||
* @param output output path
|
||||
*/
|
||||
function awsCp(output: string) {
|
||||
logger.info(`aws s3 cp ${output}`);
|
||||
const response = exec('aws s3 cp', [`./s3-artifact.tmp ${output}`], {});
|
||||
logger.info(response);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Artifact to S3 command
|
||||
*/
|
||||
export default function main() {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('-a, --artifact [type]', ' path to the artifact to archieve (tar.bz2) and upload (like ./dist)')
|
||||
.option('-o, --output [type]', ' the S3 object to copy it to, like: s3://bucket-name/folder/whatever.tar.bz2')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!program.artifact || program.artifact === '' || !program.output || program.output === '') {
|
||||
exit(1);
|
||||
} else if (program.artifact !== '' || program.output !== '') {
|
||||
zipArtifact(program.artifact);
|
||||
awsCp(program.output);
|
||||
}
|
||||
}
|
@ -1,80 +0,0 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { AlfrescoApi } from '@alfresco/js-api';
|
||||
import { exit, argv } from 'node:process';
|
||||
const program = require('commander');
|
||||
import { logger } from './logger';
|
||||
const MAX_RETRY = 10;
|
||||
const TIMEOUT = 60000;
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
* Check PS environment command
|
||||
*/
|
||||
export default async function main() {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.description('Check Process service is up ')
|
||||
.usage('check-ps-env [options]')
|
||||
.option('--host [type]', 'Remote environment host adf.lab.com ')
|
||||
.option('-p, --password [type]', 'password ')
|
||||
.option('-u, --username [type]', 'username ')
|
||||
.parse(argv);
|
||||
|
||||
await checkEnv();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check environment
|
||||
*/
|
||||
async function checkEnv() {
|
||||
try {
|
||||
const alfrescoJsApi = new AlfrescoApi({
|
||||
provider: 'BPM',
|
||||
hostBpm: program.host,
|
||||
contextRoot: 'alfresco'
|
||||
});
|
||||
|
||||
await alfrescoJsApi.login(program.username, program.password);
|
||||
} catch (e) {
|
||||
if (e.error.code === 'ETIMEDOUT') {
|
||||
logger.error('The env is not reachable. Terminating');
|
||||
exit(1);
|
||||
}
|
||||
logger.error('Login error environment down or inaccessible');
|
||||
counter++;
|
||||
if (MAX_RETRY === counter) {
|
||||
logger.error('Give up');
|
||||
exit(1);
|
||||
} else {
|
||||
logger.error(`Retry in 1 minute attempt N ${counter}`);
|
||||
sleep(TIMEOUT);
|
||||
await checkEnv();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a delay
|
||||
*
|
||||
* @param delay timeout in milliseconds
|
||||
*/
|
||||
function sleep(delay: number) {
|
||||
const start = new Date().getTime();
|
||||
while (new Date().getTime() < start + delay) {}
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import * as docker from './docker';
|
||||
|
||||
/**
|
||||
* Docker publish command
|
||||
*
|
||||
* @param args command arguments
|
||||
*/
|
||||
export default function(args: any) {
|
||||
docker.default(args);
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { logger } from './logger';
|
||||
import { exec } from './exec';
|
||||
|
||||
export interface KubeArgs {
|
||||
tag?: string;
|
||||
installCheck?: boolean;
|
||||
username?: string;
|
||||
token?: string;
|
||||
clusterEnv?: string;
|
||||
clusterUrl?: string;
|
||||
dockerRepo?: string;
|
||||
label?: string;
|
||||
namespaces?: string;
|
||||
}
|
||||
|
||||
export const setCluster = (clusterEnv: string, clusterUrl: string) => {
|
||||
logger.info('Perform set-cluster...');
|
||||
const response = exec('kubectl', [`config`, `set-cluster`, `${clusterEnv}`, `--server=${clusterUrl}`], {});
|
||||
logger.info(response);
|
||||
};
|
||||
|
||||
export const setCredentials = (username: string, token: string) => {
|
||||
logger.info('Perform set-credentials...');
|
||||
const response = exec('kubectl', [`config`, `set-credentials`, `${username}`, `--token=${token}`], {});
|
||||
logger.info(response);
|
||||
};
|
||||
|
||||
export const setContext = (clusterEnv: string, username: string) => {
|
||||
logger.info('Perform set-context...');
|
||||
const response = exec('kubectl', [`config`, `set-context`, `${clusterEnv}`, `--cluster=${clusterEnv}`, `--user=${username}`], {});
|
||||
logger.info(response);
|
||||
};
|
||||
|
||||
export const useContext = (clusterEnv: string) => {
|
||||
logger.info('Perform use-context...');
|
||||
const response = exec('kubectl', [`config`, `use-context`, `${clusterEnv}`], {});
|
||||
logger.info(response);
|
||||
};
|
||||
|
||||
export const deletePod = (args: KubeArgs) => {
|
||||
logger.info('Perform delete pods...');
|
||||
const response = exec('kubectl', [`delete`, `pods`, `--all-namespaces`, `-l`, `app=${args.label}`], {});
|
||||
logger.info(response);
|
||||
};
|
||||
|
||||
export const getNamespaces = (): string[] => {
|
||||
logger.info('Perform get namespaces name...');
|
||||
const result = exec('kubectl', [`get`, `namespaces`, `-l`, `type=application`, `-o`, `name`], {});
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
const namespaces = result.replace(/namespace[\/]+/g, '').split(/\r?\n/);
|
||||
logger.info(`namespaces found: ${namespaces}`);
|
||||
return namespaces;
|
||||
};
|
||||
|
||||
export const getDeploymentName = (args: KubeArgs, namespace: string): string => {
|
||||
logger.info('Perform get deployment name...');
|
||||
const result = exec('kubectl', [`get`, `deployments`, `--namespace=${namespace}`, `-l`, `app=${args.label}`, `-o`, `name`], {});
|
||||
logger.info(`deployment name: ${result}`);
|
||||
return result;
|
||||
};
|
||||
|
||||
export const setImage = (args: KubeArgs, deploymentName: string, serviceName: string, namespace: string) => {
|
||||
logger.info('Perform set image...');
|
||||
const response = exec('kubectl', [`set`, `image`, `--namespace=${namespace}`, `${deploymentName}`, `${serviceName}=${args.dockerRepo}:${args.tag}`], {});
|
||||
logger.info(response);
|
||||
};
|
@ -1,377 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv, exit } from 'node:process';
|
||||
import program from 'commander';
|
||||
import moment from 'moment';
|
||||
import { AlfrescoApi, AlfrescoApiConfig } from '@alfresco/js-api';
|
||||
import { logger } from './logger';
|
||||
import * as kube from './kube-utils';
|
||||
export interface ConfigArgs {
|
||||
rancherUsername?: string;
|
||||
rancherToken?: string;
|
||||
clusterEnv?: string;
|
||||
clusterUrl?: string;
|
||||
apps?: string;
|
||||
devopsUsername: string;
|
||||
devopsPassword: string;
|
||||
modelerUsername: string;
|
||||
modelerPassword: string;
|
||||
clientId: string;
|
||||
host: string;
|
||||
oauth: string;
|
||||
identityHost: boolean;
|
||||
enableLike: boolean;
|
||||
intervalTime: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Alfresco Api instance
|
||||
*
|
||||
* @param args command parameters
|
||||
* @returns Alfresco Api instance
|
||||
*/
|
||||
function getAlfrescoJsApiInstance(args: ConfigArgs): AlfrescoApi {
|
||||
const config: AlfrescoApiConfig = {
|
||||
provider: 'BPM',
|
||||
hostBpm: `${args.host}`,
|
||||
authType: 'OAUTH',
|
||||
contextRoot: 'alfresco',
|
||||
oauth2: {
|
||||
host: `${args.oauth}/auth/realms/alfresco`,
|
||||
clientId: `${args.clientId}`,
|
||||
scope: 'openid',
|
||||
secret: '',
|
||||
implicitFlow: false,
|
||||
silentLogin: false,
|
||||
redirectUri: '/'
|
||||
}
|
||||
};
|
||||
return new AlfrescoApi(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform login
|
||||
*
|
||||
* @param username username
|
||||
* @param password password
|
||||
* @param alfrescoJsApi api client
|
||||
*/
|
||||
async function login(username: string, password: string, alfrescoJsApi: AlfrescoApi) {
|
||||
logger.info(`Perform login...`);
|
||||
try {
|
||||
await alfrescoJsApi.login(username, password);
|
||||
} catch (error) {
|
||||
logger.error(`Not able to login. Credentials ${username}:${password} are not valid`);
|
||||
exit(1);
|
||||
}
|
||||
logger.info(`Perform done...`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes deployment descriptor
|
||||
*
|
||||
* @param args command arguments
|
||||
* @param apiService api client
|
||||
* @param name descriptor name
|
||||
*/
|
||||
async function deleteDescriptor(args: ConfigArgs, apiService: AlfrescoApi, name: string) {
|
||||
logger.warn(`Delete the descriptor ${name}`);
|
||||
|
||||
const url = `${args.host}/deployment-service/v1/descriptors/${name}`;
|
||||
|
||||
const pathParams = {};
|
||||
const bodyParam = {};
|
||||
|
||||
const headerParams = {};
|
||||
const formParams = {};
|
||||
const queryParams = {};
|
||||
const contentTypes = ['application/json'];
|
||||
const accepts = ['application/json'];
|
||||
|
||||
try {
|
||||
return await apiService.oauth2Auth.callCustomApi(
|
||||
url,
|
||||
'DELETE',
|
||||
pathParams,
|
||||
queryParams,
|
||||
headerParams,
|
||||
formParams,
|
||||
bodyParam,
|
||||
contentTypes,
|
||||
accepts
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`Not possible to delete the descriptor ${name} status: ${JSON.stringify(error.status)} ${JSON.stringify(error?.response?.text)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes modeling project
|
||||
*
|
||||
* @param args arguments
|
||||
* @param apiService api client
|
||||
* @param projectId project id
|
||||
*/
|
||||
async function deleteProject(args: ConfigArgs, apiService: AlfrescoApi, projectId: string) {
|
||||
logger.warn(`Delete the project ${projectId}`);
|
||||
|
||||
const url = `${args.host}/modeling-service/v1/projects/${projectId}`;
|
||||
|
||||
const pathParams = {};
|
||||
const bodyParam = {};
|
||||
|
||||
const headerParams = {};
|
||||
const formParams = {};
|
||||
const queryParams = {};
|
||||
const contentTypes = ['application/json'];
|
||||
const accepts = ['application/json'];
|
||||
|
||||
try {
|
||||
return await apiService.oauth2Auth.callCustomApi(
|
||||
url,
|
||||
'DELETE',
|
||||
pathParams,
|
||||
queryParams,
|
||||
headerParams,
|
||||
formParams,
|
||||
bodyParam,
|
||||
contentTypes,
|
||||
accepts
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`Not possible to delete the project ${projectId} status : ${JSON.stringify(error.status)} ${JSON.stringify(error?.response?.text)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes modeling project by name
|
||||
*
|
||||
* @param args arguments
|
||||
* @param apiService api client
|
||||
* @param name project name
|
||||
*/
|
||||
async function deleteProjectByName(args: ConfigArgs, apiService: AlfrescoApi, name: string) {
|
||||
logger.warn(`Get the project by name ${name}`);
|
||||
const url = `${args.host}/modeling-service/v1/projects?name=${name}`;
|
||||
|
||||
const pathParams = {};
|
||||
const queryParams = {};
|
||||
const headerParams = {};
|
||||
const formParams = {};
|
||||
const bodyParam = {};
|
||||
const contentTypes = ['application/json'];
|
||||
const accepts = ['application/json'];
|
||||
|
||||
try {
|
||||
const data = await apiService.oauth2Auth.callCustomApi(
|
||||
url,
|
||||
'GET',
|
||||
pathParams,
|
||||
queryParams,
|
||||
headerParams,
|
||||
formParams,
|
||||
bodyParam,
|
||||
contentTypes,
|
||||
accepts
|
||||
);
|
||||
for (let i = 0; i < data.list.entries.length; i++) {
|
||||
if (data.list.entries[i].entry.name === name) {
|
||||
await deleteProject(args, apiService, data.list.entries[i].entry.id);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Not possible to get the project with name ${name} ` + JSON.stringify(error));
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get applications by name
|
||||
*
|
||||
* @param args command arguments
|
||||
* @param apiService api client
|
||||
* @param name application name
|
||||
*/
|
||||
async function getApplicationsByName(args: ConfigArgs, apiService: AlfrescoApi, name: string) {
|
||||
logger.warn(`Get the applications by name ${name}`);
|
||||
const url = `${args.host}/deployment-service/v1/applications?name=${name}`;
|
||||
|
||||
const pathParams = {};
|
||||
const queryParams = {};
|
||||
const headerParams = {};
|
||||
const formParams = {};
|
||||
const bodyParam = {};
|
||||
const contentTypes = ['application/json'];
|
||||
const accepts = ['application/json'];
|
||||
|
||||
try {
|
||||
const apps = await apiService.oauth2Auth.callCustomApi(
|
||||
url,
|
||||
'GET',
|
||||
pathParams,
|
||||
queryParams,
|
||||
headerParams,
|
||||
formParams,
|
||||
bodyParam,
|
||||
contentTypes,
|
||||
accepts
|
||||
);
|
||||
return apps ? apps.list.entries : [];
|
||||
} catch (error) {
|
||||
logger.error(`Not possible to get the applications with name ${name} ` + JSON.stringify(error));
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Undeploy applications by name
|
||||
*
|
||||
* @param args command arguments
|
||||
* @param apiService api client
|
||||
* @param name application name
|
||||
*/
|
||||
async function undeployApplication(args: ConfigArgs, apiService: AlfrescoApi, name: string) {
|
||||
logger.warn(`Undeploy the application ${name}`);
|
||||
|
||||
const url = `${args.host}/deployment-service/v1/applications/${name}`;
|
||||
|
||||
const pathParams = {};
|
||||
const bodyParam = {};
|
||||
|
||||
const headerParams = {};
|
||||
const formParams = {};
|
||||
const queryParams = {};
|
||||
const contentTypes = ['application/json'];
|
||||
const accepts = ['application/json'];
|
||||
|
||||
try {
|
||||
return await apiService.oauth2Auth.callCustomApi(
|
||||
url,
|
||||
'DELETE',
|
||||
pathParams,
|
||||
queryParams,
|
||||
headerParams,
|
||||
formParams,
|
||||
bodyParam,
|
||||
contentTypes,
|
||||
accepts
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`Not possible to undeploy the applications ${name} status: ${JSON.stringify(error.status)} ${JSON.stringify(error?.response?.text)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const main = async (args: ConfigArgs) => {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.description(
|
||||
'The following command is in charge of cleaning the releases/application/descriptor related to an app passed as input' +
|
||||
'adf-cli kubectl-clean-app --host "gateway_env" --modelerUsername "modelerusername" --modelerPassword "modelerpassword" --oauth "identity_env" --username "username" --password "password"'
|
||||
)
|
||||
.option('-h, --host [type]', 'Host gateway')
|
||||
.option('-o, --oauth [type]', 'Host sso server')
|
||||
.option('--clusterEnv [type]', 'cluster Envirorment')
|
||||
.option('--clusterUrl [type]', 'cluster URL')
|
||||
.option('--clientId [type]', 'sso client')
|
||||
.option('--devopsUsername [type]', 'username of user with ACTIVITI_DEVOPS role')
|
||||
.option('--devopsPassword [type]', 'password of user with ACTIVITI_DEVOPS role')
|
||||
.option('--modelerUsername [type]', 'username of a user with role ACTIVIT_MODELER')
|
||||
.option('--modelerPassword [type]', 'modeler password')
|
||||
.option('--rancherUsername [type]', 'rancher username')
|
||||
.option('--rancherToken [type]', 'rancher token')
|
||||
.option('--apps [type]', 'Application prefix')
|
||||
.option('--enableLike [boolean]', 'Enable the like for app name')
|
||||
.option('--intervalTime [string]', 'In case of enableLike it specify the time related to the createDate')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
const alfrescoJsApiModeler = getAlfrescoJsApiInstance(args);
|
||||
await login(args.modelerUsername, args.modelerPassword, alfrescoJsApiModeler).then(
|
||||
() => {
|
||||
logger.info('login SSO ok');
|
||||
},
|
||||
(error) => {
|
||||
logger.info(`login SSO error ${JSON.stringify(error)}`);
|
||||
exit(1);
|
||||
}
|
||||
);
|
||||
|
||||
const alfrescoJsApiDevops = getAlfrescoJsApiInstance(args);
|
||||
await login(args.devopsUsername, args.devopsPassword, alfrescoJsApiDevops).then(
|
||||
() => {
|
||||
logger.info('login SSO ok');
|
||||
},
|
||||
(error) => {
|
||||
logger.info(`login SSO error ${JSON.stringify(error)}`);
|
||||
exit(1);
|
||||
}
|
||||
);
|
||||
|
||||
if (args.apps !== undefined) {
|
||||
kube.setCluster(args.clusterEnv, args.clusterUrl);
|
||||
kube.setCredentials(args.rancherUsername, args.rancherToken);
|
||||
kube.setContext(args.clusterEnv, args.rancherUsername);
|
||||
kube.useContext(args.clusterEnv);
|
||||
|
||||
const applications = args.apps.includes(',') ? args.apps.split(',') : [args.apps];
|
||||
const interval = args.intervalTime ? args.intervalTime : '30 min';
|
||||
const extractTimeRange = parseInt(interval.split(' ')[0], 10);
|
||||
logger.info(`Extract time ${extractTimeRange} from interval: ${interval}`);
|
||||
|
||||
for (let i = 0; i < applications.length; i++) {
|
||||
logger.info(`Perform action on app: ${applications[i]}`);
|
||||
if (args.enableLike) {
|
||||
const applicationsByName = await getApplicationsByName(args, alfrescoJsApiDevops, applications[i]);
|
||||
logger.info(`Found ${applicationsByName.length} apps`);
|
||||
|
||||
for (let y = 0; y < applicationsByName.length; y++) {
|
||||
const application = applicationsByName[y].entry;
|
||||
logger.info(`Analyze app: ${application.name} `);
|
||||
const diffAsMinutes = moment.duration(moment().diff(moment(application.createdAt))).asMinutes();
|
||||
|
||||
if (diffAsMinutes > extractTimeRange) {
|
||||
logger.info(`The app: ${application} is older than ${interval}. Can delete it`);
|
||||
await undeployApplication(args, alfrescoJsApiDevops, application.name);
|
||||
await deleteDescriptor(args, alfrescoJsApiDevops, application.name);
|
||||
await deleteProjectByName(args, alfrescoJsApiModeler, application.name);
|
||||
} else {
|
||||
logger.info(`The app: ${application} is recent than ${interval}. Skip delete`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await undeployApplication(args, alfrescoJsApiDevops, applications[i]);
|
||||
await deleteDescriptor(args, alfrescoJsApiDevops, applications[i]);
|
||||
await deleteProjectByName(args, alfrescoJsApiModeler, applications[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default main;
|
@ -1,49 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv } from 'node:process';
|
||||
import program from 'commander';
|
||||
import * as kube from './kube-utils';
|
||||
|
||||
const main = (args: kube.KubeArgs) => {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('--username [type]', 'username')
|
||||
.option('--password [type]', 'password')
|
||||
.option('--token [type]', 'access token')
|
||||
.option('--clusterEnv [type]', 'cluster Env')
|
||||
.option('--clusterUrl [type]', 'cluster Url')
|
||||
.option('--label [type]', 'label cluster')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.label !== undefined) {
|
||||
kube.setCluster(args.clusterEnv, args.clusterUrl);
|
||||
kube.setCredentials(args.username, args.token);
|
||||
kube.setContext(args.clusterEnv, args.username);
|
||||
kube.useContext(args.clusterEnv);
|
||||
kube.deletePod(args);
|
||||
}
|
||||
};
|
||||
|
||||
export default main;
|
@ -1,87 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv } from 'node:process';
|
||||
import { exec } from './exec';
|
||||
import program from 'commander';
|
||||
import { logger } from './logger';
|
||||
import * as kube from './kube-utils';
|
||||
|
||||
const installPerform = () => {
|
||||
logger.info('Perform install...');
|
||||
const responseK8sStable = exec('curl', [`-s`, `https://storage.googleapis.com/kubernetes-release/release/stable.txt`], {}).trim();
|
||||
const k8sRelease = `https://storage.googleapis.com/kubernetes-release/release/${responseK8sStable}/bin/linux/amd64/kubectl`;
|
||||
exec('curl', [`LO`, `${k8sRelease}`], {});
|
||||
};
|
||||
|
||||
|
||||
const main = (args: kube.KubeArgs) => {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.description(
|
||||
'This command allows you to update a specific service on the rancher env with a specific tag \n\n' +
|
||||
'adf-cli kubectl-image --clusterEnv ${clusterEnv} --clusterUrl ${clusterUrl} --username ${username} --token ${token} --label ${label} --namespaces ${namespaces} --dockerRepo ${dockerRepo} --tag ${tag}'
|
||||
)
|
||||
.option('--tag [type]', 'tag')
|
||||
.option('--installCheck [type]', 'install kube ctl')
|
||||
.option('--username [type]', 'username')
|
||||
.option('--clusterEnv [type]', 'cluster Env')
|
||||
.option('--clusterUrl [type]', 'cluster Url')
|
||||
.option('--dockerRepo [type]', 'docker Repo')
|
||||
.option('--label [type]', 'pod label')
|
||||
.option('--namespaces [type]', 'list of namespaces')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.installCheck === true) {
|
||||
installPerform();
|
||||
}
|
||||
|
||||
if (args.tag !== undefined) {
|
||||
kube.setCluster(args.clusterEnv, args.clusterUrl);
|
||||
kube.setCredentials(args.username, args.token);
|
||||
kube.setContext(args.clusterEnv, args.username);
|
||||
kube.useContext(args.clusterEnv);
|
||||
|
||||
let namespaces: string[];
|
||||
if (args.namespaces === null || args.namespaces === 'default') {
|
||||
logger.info(`No namespaces provided. Fetch all of them`);
|
||||
namespaces = kube.getNamespaces();
|
||||
} else {
|
||||
namespaces = args.namespaces.split(',');
|
||||
}
|
||||
|
||||
namespaces.forEach((namespace) => {
|
||||
logger.info(`Find deployment name based on label ${args.label} and namespace ${namespace}`);
|
||||
const deploymentName = kube.getDeploymentName(args, namespace);
|
||||
if (deploymentName) {
|
||||
logger.info(`Found ${deploymentName}`);
|
||||
kube.setImage(args, deploymentName.trim(), '*', namespace);
|
||||
} else {
|
||||
logger.info(`No container with the label app=${args.label} found`);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default main;
|
@ -1,173 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv } from 'node:process';
|
||||
import * as path from 'path';
|
||||
import fs = require('fs');
|
||||
import { exec } from './exec';
|
||||
import program from 'commander';
|
||||
import { logger } from './logger';
|
||||
|
||||
export interface PublishArgs {
|
||||
tag?: string;
|
||||
npmRegistry?: string;
|
||||
tokenRegistry?: string;
|
||||
pathProject: string;
|
||||
dryrun?: boolean;
|
||||
}
|
||||
|
||||
const projects = ['cli', 'core', 'insights', 'testing', 'content-services', 'process-services', 'process-services-cloud', 'extensions'];
|
||||
|
||||
/**
|
||||
* Publish to NPM command
|
||||
*
|
||||
* @param args command arguments
|
||||
* @param project project name
|
||||
*/
|
||||
async function npmPublish(args: PublishArgs, project: string) {
|
||||
if (args.dryrun) {
|
||||
logger.info(`Dry run mode, no publish will be done`);
|
||||
}
|
||||
|
||||
if (args.npmRegistry) {
|
||||
changeRegistry(args, project);
|
||||
}
|
||||
|
||||
const version = require(`${args.pathProject}/dist/libs/${project}/package.json`).version;
|
||||
|
||||
const exist = npmCheckExist(project, version);
|
||||
|
||||
if (!exist) {
|
||||
logger.info(`Publishing lib ${project} to registry ${args.npmRegistry}`);
|
||||
const options = ['publish'];
|
||||
if (args.tag) {
|
||||
options.push('-tag');
|
||||
options.push(`${args.tag}`);
|
||||
}
|
||||
if (args.dryrun) {
|
||||
logger.info(`Dry-run npm publish. cwd: ${args.pathProject}/dist/libs/${project}`);
|
||||
} else {
|
||||
const response = exec('npm', options, { cwd: path.resolve(`${args.pathProject}/dist/libs/${project}`) });
|
||||
logger.info(response);
|
||||
if (args.npmRegistry) {
|
||||
removeNpmConfig(args, project);
|
||||
}
|
||||
}
|
||||
|
||||
await sleep(30000);
|
||||
} else {
|
||||
logger.info(`@alfresco/adf-${project}@${version} already exist`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the library exists on npm already
|
||||
*
|
||||
* @param project project name
|
||||
* @param version project version
|
||||
* @returns `true` if given project exists on NPM, otherwise `false`
|
||||
*/
|
||||
function npmCheckExist(project: string, version: string): boolean {
|
||||
logger.info(`Check if lib ${project} is already in npm with version ${version}`);
|
||||
let exist = '';
|
||||
try {
|
||||
exist = exec(`npm`, [`view`, `@alfresco/adf-${project}@${version} version`]);
|
||||
} catch (e) {
|
||||
logger.info(`Error: '@alfresco/adf-${project}@${version} version' is not available `);
|
||||
}
|
||||
|
||||
return exist !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Change NPM registry
|
||||
*
|
||||
* @param args command parameters
|
||||
* @param project project name
|
||||
*/
|
||||
function changeRegistry(args: PublishArgs, project: string) {
|
||||
logger.info(`Change registry... to ${args.npmRegistry} `);
|
||||
const folder = `${args.pathProject}/dist/libs/${project}`;
|
||||
const content = `strict-ssl=true
|
||||
always-auth=true
|
||||
@alfresco:registry=https://${args.npmRegistry}
|
||||
//${args.npmRegistry}/:_authToken="${args.tokenRegistry}"`;
|
||||
|
||||
try {
|
||||
fs.mkdirSync(folder, { recursive: true });
|
||||
fs.writeFileSync(`${folder}/.npmrc`, content);
|
||||
} catch (e) {
|
||||
logger.error('Cannot write file', e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes custom `.npmrc` configuration file
|
||||
*
|
||||
* @param args command arguments
|
||||
* @param project project name
|
||||
*/
|
||||
function removeNpmConfig(args: PublishArgs, project: string) {
|
||||
logger.info(`Removing file from ${project}`);
|
||||
try {
|
||||
const response = exec('rm', ['.npmrc'], { cwd: path.resolve(`${args.pathProject}/dist/libs/${project}`) });
|
||||
logger.info(response);
|
||||
} catch (e) {
|
||||
logger.error('Error removing file', e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish to NPM command
|
||||
*
|
||||
* @param args command arguments
|
||||
*/
|
||||
export default async function main(args: PublishArgs) {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.description(
|
||||
'Move in the folder where you have your Dockerfile and run the command \n\n adf-cli docker-publish --dockerRepo "${docker_repository}" --dockerTags "${TAGS}" --pathProject "$(pwd)'
|
||||
)
|
||||
.option('--tag [type]', 'tag')
|
||||
.option('--npmRegistry [type]', 'npm Registry')
|
||||
.option('--tokenRegistry [type]', 'token Registry')
|
||||
.option('--pathProject [type]', 'pathProject')
|
||||
.option('--dryrun [type]', 'dryrun')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
for (const project of projects) {
|
||||
logger.info(`======== Publishing project: ${project} ========`);
|
||||
await npmPublish(args, project);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a timeout
|
||||
*
|
||||
* @param ms timeout in milliseconds
|
||||
*/
|
||||
async function sleep(ms: number) {
|
||||
logger.info(`Waiting for ${ms} milliseconds...`);
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
@ -1,331 +0,0 @@
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { AlfrescoApi, PeopleApi, NodesApi, GroupsApi, SitesApi, SearchApi } from '@alfresco/js-api';
|
||||
import { argv, exit } from 'node:process';
|
||||
import program from 'commander';
|
||||
import { logger } from './logger';
|
||||
|
||||
interface PeopleTally {
|
||||
enabled: number;
|
||||
disabled: number;
|
||||
}
|
||||
interface RowToPrint {
|
||||
label: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
const MAX_ATTEMPTS = 1;
|
||||
const TIMEOUT = 180000;
|
||||
const MAX_PEOPLE_PER_PAGE = 100;
|
||||
const USERS_HOME_RELATIVE_PATH = 'User Homes';
|
||||
|
||||
const reset = '\x1b[0m';
|
||||
const grey = '\x1b[90m';
|
||||
const cyan = '\x1b[36m';
|
||||
const yellow = '\x1b[33m';
|
||||
const bright = '\x1b[1m';
|
||||
const red = '\x1b[31m';
|
||||
const green = '\x1b[32m';
|
||||
|
||||
let alfrescoApi: AlfrescoApi;
|
||||
let loginAttempts: number = 0;
|
||||
|
||||
/**
|
||||
* Scan environment command
|
||||
*/
|
||||
export default async function main() {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log = () => {};
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('--host <type>', 'Remote environment host')
|
||||
.option('--clientId [type]', 'sso client', 'alfresco')
|
||||
.option('-p, --password <type>', 'password ')
|
||||
.option('-u, --username <type>', 'username ')
|
||||
.parse(argv);
|
||||
|
||||
logger.info(`${cyan}${bright}Initiating environment scan...${reset}`);
|
||||
await attemptLogin();
|
||||
|
||||
const rowsToPrint: Array<RowToPrint> = [];
|
||||
const peopleCount = await getPeopleCount();
|
||||
rowsToPrint.push({ label: 'Active Users', value: peopleCount.enabled });
|
||||
rowsToPrint.push({ label: 'Deactivated Users', value: peopleCount.disabled });
|
||||
rowsToPrint.push({ label: `User's Home Folders`, value: await getHomeFoldersCount() });
|
||||
rowsToPrint.push({ label: 'Groups', value: await getGroupsCount() });
|
||||
rowsToPrint.push({ label: 'Sites', value: await getSitesCount() });
|
||||
rowsToPrint.push({ label: 'Files', value: await getFilesCount() });
|
||||
|
||||
logger.info(generateTable(rowsToPrint));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate table
|
||||
*
|
||||
* @param rowsToPrint list of table rows to print
|
||||
* @returns table as a string
|
||||
*/
|
||||
function generateTable(rowsToPrint: Array<RowToPrint>) {
|
||||
const columnWidths = rowsToPrint.reduce(
|
||||
(maxWidths, row: RowToPrint) => ({
|
||||
labelColumn: Math.max(maxWidths.labelColumn, row.label.length),
|
||||
valueColumn: Math.max(maxWidths.valueColumn, row.value.toString().length)
|
||||
}),
|
||||
{ labelColumn: 12, valueColumn: 1 }
|
||||
);
|
||||
|
||||
const horizontalLine = ''.padEnd(columnWidths.labelColumn + columnWidths.valueColumn + 5, '═');
|
||||
const headerText =
|
||||
'ENVIRONM'.padStart(Math.floor((columnWidths.labelColumn + columnWidths.valueColumn + 3) / 2), ' ') +
|
||||
'ENT SCAN'.padEnd(Math.ceil((columnWidths.labelColumn + columnWidths.valueColumn + 3) / 2), ' ');
|
||||
|
||||
let tableString = `${grey}╒${horizontalLine}╕${reset}
|
||||
${grey}│ ${bright}${cyan}${headerText} ${grey}│${reset}
|
||||
${grey}╞${horizontalLine}╡${reset}`;
|
||||
rowsToPrint.forEach((row) => {
|
||||
tableString += `\n${grey}│${reset} ${row.label.padEnd(columnWidths.labelColumn, ' ')} ${yellow}${row.value
|
||||
.toString()
|
||||
.padEnd(columnWidths.valueColumn, ' ')} ${grey}│${reset}`;
|
||||
});
|
||||
tableString += `\n${grey}╘${horizontalLine}╛${reset}`;
|
||||
|
||||
return tableString;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to login
|
||||
*/
|
||||
async function attemptLogin() {
|
||||
logger.info(` Logging into ${yellow}${program.host}${reset} with user ${yellow}${program.username}${reset}`);
|
||||
try {
|
||||
alfrescoApi = new AlfrescoApi({
|
||||
provider: 'ALL',
|
||||
hostBpm: program.host,
|
||||
hostEcm: program.host,
|
||||
authType: 'OAUTH',
|
||||
contextRoot: 'alfresco',
|
||||
oauth2: {
|
||||
host: `${program.host}/auth/realms/alfresco`,
|
||||
clientId: `${program.clientId}`,
|
||||
scope: 'openid',
|
||||
redirectUri: '/',
|
||||
implicitFlow: false
|
||||
}
|
||||
});
|
||||
await alfrescoApi.login(program.username, program.password);
|
||||
logger.info(` ${green}Login SSO successful${reset}`);
|
||||
} catch (err) {
|
||||
await handleLoginError(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles login error
|
||||
*
|
||||
* @param loginError error object
|
||||
*/
|
||||
async function handleLoginError(loginError) {
|
||||
if (loginAttempts === 0) {
|
||||
logger.error(` ${red}Login SSO error${reset}`);
|
||||
}
|
||||
checkEnvReachable(loginError);
|
||||
loginAttempts++;
|
||||
if (MAX_ATTEMPTS === loginAttempts) {
|
||||
if (loginError?.response?.text) {
|
||||
try {
|
||||
const parsedJson = JSON.parse(loginError?.response?.text);
|
||||
if (typeof parsedJson === 'object' && parsedJson.error) {
|
||||
const { stackTrace, ...errorWithoutDeprecatedProperty } = parsedJson.error;
|
||||
logger.error(errorWithoutDeprecatedProperty);
|
||||
}
|
||||
} catch (jsonParseError) {
|
||||
logger.error(` ${red}Could not parse the error response. Possibly non json format${reset}`);
|
||||
}
|
||||
}
|
||||
logger.error(` ${red}Give up${reset}`);
|
||||
failScript();
|
||||
} else {
|
||||
logger.error(` Retry in 1 minute attempt N ${loginAttempts}`);
|
||||
await wait(TIMEOUT);
|
||||
await attemptLogin();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check environment is reachable
|
||||
*
|
||||
* @param loginError error object
|
||||
*/
|
||||
function checkEnvReachable(loginError) {
|
||||
const failingErrorCodes = ['ENOTFOUND', 'ETIMEDOUT', 'ECONNREFUSED'];
|
||||
if (typeof loginError === 'object' && failingErrorCodes.indexOf(loginError.code) > -1) {
|
||||
logger.error(` ${red}The environment is not reachable (${loginError.code})${reset}`);
|
||||
failScript();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get people count
|
||||
*
|
||||
* @param skipCount skip count
|
||||
*/
|
||||
async function getPeopleCount(skipCount: number = 0): Promise<PeopleTally> {
|
||||
if (skipCount === 0) {
|
||||
logger.info(` Fetching number of users`);
|
||||
}
|
||||
try {
|
||||
const peopleApi = new PeopleApi(alfrescoApi);
|
||||
const apiResult = await peopleApi.listPeople({
|
||||
fields: ['enabled'],
|
||||
maxItems: MAX_PEOPLE_PER_PAGE,
|
||||
skipCount
|
||||
});
|
||||
const result: PeopleTally = apiResult.list.entries.reduce(
|
||||
(peopleTally: PeopleTally, currentPerson) => {
|
||||
if (currentPerson.entry.enabled) {
|
||||
peopleTally.enabled++;
|
||||
} else {
|
||||
peopleTally.disabled++;
|
||||
}
|
||||
return peopleTally;
|
||||
},
|
||||
{ enabled: 0, disabled: 0 }
|
||||
);
|
||||
if (apiResult.list.pagination.hasMoreItems) {
|
||||
const more = await getPeopleCount(apiResult.list.pagination.skipCount + MAX_PEOPLE_PER_PAGE);
|
||||
result.enabled += more.enabled;
|
||||
result.disabled += more.disabled;
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the amount of Home folders
|
||||
*/
|
||||
async function getHomeFoldersCount(): Promise<number> {
|
||||
logger.info(` Fetching number of home folders`);
|
||||
try {
|
||||
const nodesApi = new NodesApi(alfrescoApi);
|
||||
const homesFolderApiResult = await nodesApi.listNodeChildren('-root-', {
|
||||
maxItems: 1,
|
||||
relativePath: USERS_HOME_RELATIVE_PATH
|
||||
});
|
||||
return homesFolderApiResult.list.pagination.totalItems;
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the amount of groups
|
||||
*/
|
||||
async function getGroupsCount(): Promise<number> {
|
||||
logger.info(` Fetching number of groups`);
|
||||
try {
|
||||
const groupsApi = new GroupsApi(alfrescoApi);
|
||||
const groupsApiResult = await groupsApi.listGroups({ maxItems: 1 });
|
||||
return groupsApiResult.list.pagination.totalItems;
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the amount of sites
|
||||
*/
|
||||
async function getSitesCount(): Promise<number> {
|
||||
logger.info(` Fetching number of sites`);
|
||||
try {
|
||||
const sitesApi = new SitesApi(alfrescoApi);
|
||||
const sitesApiResult = await sitesApi.listSites({ maxItems: 1 });
|
||||
return sitesApiResult.list.pagination.totalItems;
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the amount of files
|
||||
*/
|
||||
async function getFilesCount(): Promise<number> {
|
||||
logger.info(` Fetching number of files`);
|
||||
try {
|
||||
const searchApi = new SearchApi(alfrescoApi);
|
||||
const searchApiResult = await searchApi.search({
|
||||
query: {
|
||||
query: 'select * from cmis:document',
|
||||
language: 'cmis'
|
||||
},
|
||||
paging: {
|
||||
maxItems: 1
|
||||
}
|
||||
});
|
||||
return searchApiResult.list.pagination.totalItems;
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle error
|
||||
*
|
||||
* @param error error object
|
||||
*/
|
||||
function handleError(error) {
|
||||
logger.error(` ${red}Error encountered${reset}`);
|
||||
if (error?.response && error?.response?.text) {
|
||||
try {
|
||||
const parsedJson = JSON.parse(error?.response?.text);
|
||||
if (typeof parsedJson === 'object' && parsedJson.error) {
|
||||
const { stackTrace, ...errorWithoutDeprecatedProperty } = parsedJson.error;
|
||||
logger.error(errorWithoutDeprecatedProperty);
|
||||
}
|
||||
} catch (jsonParseError) {
|
||||
logger.error(` ${red}Could not parse the error response. Possibly non json format${reset}`);
|
||||
}
|
||||
}
|
||||
failScript();
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the error and exit
|
||||
*/
|
||||
function failScript() {
|
||||
logger.error(`${red}${bright}Environment scan failed. Exiting${reset}`);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait with a certain period
|
||||
*
|
||||
* @param ms timeout in milliseconds
|
||||
*/
|
||||
async function wait(ms: number) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
@ -1,91 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv } from 'node:process';
|
||||
import { exec } from './exec';
|
||||
import program from 'commander';
|
||||
import { logger } from './logger';
|
||||
|
||||
export interface CommitArgs {
|
||||
pointer: string;
|
||||
pathPackage: string;
|
||||
skipGnu: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commit SHA
|
||||
*
|
||||
* @param args command arguments
|
||||
* @returns commit SHA value
|
||||
*/
|
||||
function getSha(args: CommitArgs): string {
|
||||
logger.info('Check commit sha...');
|
||||
|
||||
const gitPointer = args.pointer ? args.pointer : 'HEAD';
|
||||
|
||||
return exec('git', [`rev-parse`, `${gitPointer}`], {}).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the sha replacement
|
||||
*
|
||||
* @param args command parameters
|
||||
* @param sha value to use
|
||||
*/
|
||||
function performReplace(args: CommitArgs, sha: string) {
|
||||
logger.info(`Replace commit ${sha} in package...`);
|
||||
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
const sedRule = `s/\"commit\": \".*\"/\"commit\": \"${sha}\"/g`;
|
||||
|
||||
if (args.skipGnu) {
|
||||
exec('sed', [`-i`, '', `${sedRule}`, `${args.pathPackage}/package.json`], {});
|
||||
} else {
|
||||
exec('sed', [`-i`, `${sedRule}`, `${args.pathPackage}/package.json`], {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update commit SHA command
|
||||
*
|
||||
* @param args command arguments
|
||||
*/
|
||||
export default function main(args: CommitArgs) {
|
||||
program
|
||||
.version('0.1.0')
|
||||
.description(
|
||||
'This command allows you to update the commit sha as part of the package.json.\n' +
|
||||
'Your package.json must to have an existing property called "commit.\n\n' +
|
||||
'adf-cli update-commit-sha --pointer "HEAD~1" --pathProject "$(pwd)"\n\n' +
|
||||
'adf-cli update-commit-sha --pathProject "$(pwd)" --skipGnu'
|
||||
)
|
||||
.option('--pointer [type]', 'pointer')
|
||||
.option('--pathPackage [type]', 'pathPackage')
|
||||
.option('--skipGnu [type]', 'skipGnu')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
const sha = getSha(args);
|
||||
|
||||
performReplace(args, sha);
|
||||
}
|
@ -1,156 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/*!
|
||||
* @license
|
||||
* Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { argv } from 'node:process';
|
||||
import program from 'commander';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as shell from 'shelljs';
|
||||
|
||||
export interface UpdateArgs {
|
||||
pathPackage: string;
|
||||
latest?: boolean;
|
||||
alpha?: boolean;
|
||||
beta?: boolean;
|
||||
version: string;
|
||||
vjs: string;
|
||||
}
|
||||
|
||||
export interface PackageInfo {
|
||||
dependencies?: string[];
|
||||
devDependencies?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse alfresco libraries in package.json file
|
||||
*
|
||||
* @param workingDir working directory
|
||||
* @returns package info model
|
||||
*/
|
||||
function parseAlfrescoLibs(workingDir: string): PackageInfo {
|
||||
const packagePath = path.resolve(path.join(workingDir, 'package.json'));
|
||||
|
||||
let dependencies: string[] = [];
|
||||
let devDependencies: string[] = [];
|
||||
|
||||
if (fs.existsSync(packagePath)) {
|
||||
const json = require(packagePath);
|
||||
const isAlfrescoLib = (key: string) => key.startsWith('@alfresco');
|
||||
|
||||
dependencies = Object.keys(json.dependencies || []).filter(isAlfrescoLib);
|
||||
devDependencies = Object.keys(json.devDependencies || []).filter(isAlfrescoLib);
|
||||
}
|
||||
|
||||
return {
|
||||
dependencies,
|
||||
devDependencies
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Format npm command
|
||||
*
|
||||
* @param deps dependencies
|
||||
* @param tag tag
|
||||
* @returns npm command to execute
|
||||
*/
|
||||
function formatNpmCommand(deps: string[], tag: string): string {
|
||||
return ['npm i -E', deps.map((name) => `${name}@${tag}`).join(' ')].join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Run npm command
|
||||
*
|
||||
* @param command command to execute
|
||||
* @param workingDir working directory
|
||||
*/
|
||||
function runNpmCommand(command: string, workingDir: string) {
|
||||
if (shell.exec(command, { cwd: workingDir }).code !== 0) {
|
||||
shell.echo('Error running NPM command');
|
||||
shell.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update libraries
|
||||
*
|
||||
* @param pkg package info model
|
||||
* @param tag tag name
|
||||
* @param workingDir working directory
|
||||
*/
|
||||
function updateLibs(pkg: PackageInfo, tag: string, workingDir: string) {
|
||||
if (pkg.dependencies && pkg.dependencies.length > 0) {
|
||||
runNpmCommand(formatNpmCommand(pkg.dependencies, tag), workingDir);
|
||||
}
|
||||
|
||||
if (pkg.devDependencies && pkg.devDependencies.length > 0) {
|
||||
runNpmCommand(formatNpmCommand(pkg.devDependencies, tag) + ' -D', workingDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse tag
|
||||
*
|
||||
* @param args update arguments
|
||||
* @returns tag value
|
||||
*/
|
||||
function parseTag(args: UpdateArgs): string {
|
||||
if (args.alpha) {
|
||||
return 'alpha';
|
||||
}
|
||||
|
||||
if (args.beta) {
|
||||
return 'beta';
|
||||
}
|
||||
|
||||
return args.version || 'latest';
|
||||
}
|
||||
|
||||
/**
|
||||
* update version command
|
||||
*
|
||||
* @param args arguments
|
||||
* @param workingDir working directory
|
||||
*/
|
||||
export default function main(args: UpdateArgs, workingDir: string) {
|
||||
program
|
||||
.description(
|
||||
'This command allows you to update the adf dependencies and js-api with different versions\n\n' +
|
||||
'Update adf libs and js-api with latest alpha\n\n' +
|
||||
'adf-cli update-version --alpha'
|
||||
)
|
||||
.option('--pathPackage [dir]', 'Directory that contains package.json file', 'current directory')
|
||||
.option('--alpha', 'use alpha')
|
||||
.option('--beta', 'use beta')
|
||||
.option('--version [tag]', 'use specific version can be also alpha/beta/latest', 'latest')
|
||||
.option('--vjs [tag]', 'Upgrade only JS-API to a specific version')
|
||||
.parse(argv);
|
||||
|
||||
if (argv.includes('-h') || argv.includes('--help')) {
|
||||
program.outputHelp();
|
||||
return;
|
||||
}
|
||||
|
||||
workingDir = args.pathPackage || workingDir;
|
||||
|
||||
const tag = args.vjs || parseTag(args);
|
||||
const pkg = args.vjs ? { dependencies: ['@alfresco/js-api'] } : parseAlfrescoLibs(workingDir);
|
||||
|
||||
updateLibs(pkg, tag, workingDir);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user