@docupace/pipeline 1.0.5-alpha.25.ervins.9 → 1.0.5-alpha.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@docupace/pipeline",
3
- "version": "1.0.5-alpha.25.ervins.9",
3
+ "version": "1.0.5-alpha.3",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -15,14 +15,13 @@
15
15
  "license": "ISC",
16
16
  "dependencies": {
17
17
  "@changesets/cli": "^2.27.10",
18
- "axios": "^1.7.9",
19
18
  "commander": "^12.1.0",
20
19
  "dotenv": "^16.4.7",
21
20
  "js-yaml": "^4.1.0",
22
21
  "lodash": "^4.17.21",
23
22
  "openai": "^4.76.3",
24
23
  "zod": "^3.24.1",
25
- "zx": "^8.3.0"
24
+ "zx": "^8.2.4"
26
25
  },
27
26
  "devDependencies": {
28
27
  "@eslint/js": "^9.17.0",
@@ -32,9 +31,5 @@
32
31
  "eslint-plugin-prettier": "^5.2.1",
33
32
  "globals": "^15.14.0",
34
33
  "prettier": "^3.4.2"
35
- },
36
- "scripts": {
37
- "test-deploy-core": "dp-next-cli deploy-core-pipeline dev template",
38
- "test-deploy-from-site": "dp-next-cli deploy-from-site --from-env dev --to-env dev --from-site financialdev --to-site template --deploy-core true"
39
34
  }
40
35
  }
@@ -9,36 +9,12 @@ import { zodResponseFormat } from 'openai/helpers/zod';
9
9
  import z from 'zod';
10
10
  import dotenv from 'dotenv';
11
11
  dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
12
- import { exec } from 'child_process';
13
12
 
14
13
  const program = new Command();
15
14
 
16
15
  const args = process.argv;
17
16
 
18
- async function createChangesetDirectory() {
19
- try {
20
- // Use path.join to build a safe path to `.changeset`
21
- const targetDir = path.join(process.cwd(), '.changeset');
22
-
23
- // Create the directory recursively if it doesn't exist
24
- await fs.promises.mkdir(targetDir, { recursive: true });
25
- } catch (error) {
26
- console.error('Error creating .changeset directory:', error);
27
- }
28
- }
29
-
30
-
31
- function run(command) {
32
- return new Promise((resolve, reject) => {
33
- exec(command, { shell: true }, (error, stdout, stderr) => {
34
- if (error) {
35
- reject(error);
36
- } else {
37
- resolve({ stdout, stderr });
38
- }
39
- });
40
- });
41
- }
17
+ const DIR = path.resolve(process.cwd());
42
18
 
43
19
  async function fileExists(filePath) {
44
20
  try {
@@ -179,8 +155,7 @@ program
179
155
 
180
156
  try {
181
157
  // Step 1: Get the current branch name
182
- const { stdout: branchStdout } = await run(`git branch --show-current`);
183
- const branchName = branchStdout.trim();
158
+ const branchName = (await $`git branch --show-current`).stdout.trim();
184
159
  console.log(`Current branch: ${branchName}`);
185
160
 
186
161
  // Step 2: Extract Jira ticket number (e.g., matching JIRA-1234 pattern)
@@ -220,7 +195,6 @@ program
220
195
  `Generating release notes for ${jiraTicketId} - ${jiraSummary}`,
221
196
  );
222
197
 
223
- // Step 4: Use OpenAI to generate release notes
224
198
  const openaiClient = new OpenAI({
225
199
  apiKey: process.env['OPENAI_API_KEY'],
226
200
  });
@@ -257,23 +231,22 @@ program
257
231
  console.log(`Change type: ${change_type}`);
258
232
  console.log(`Release note: ${summary}`);
259
233
 
260
- // Step 5: Create a changeset .md file
234
+ // Step 5: Create a changeset using pnpm
261
235
  const changesetContent = `---
262
236
  "${componentName}": ${change_type}
263
237
  ---
264
238
 
265
239
  ${summary} [${jiraTicketId}]
266
- `;
240
+ `;
267
241
  const changesetFile = `./.changeset/${jiraTicketId}.md`;
268
242
 
269
- await createChangesetDirectory();
243
+ await $`mkdir -p ./.changeset`;
270
244
  await fs.promises.writeFile(changesetFile, changesetContent);
271
245
  console.log(`Created changeset file at ${changesetFile}`);
272
246
 
273
247
  console.log('Done!');
274
248
  } catch (err) {
275
249
  console.error(`Error: ${err.message}`);
276
- process.exit(1);
277
250
  }
278
251
  });
279
252
 
package/src/next/cli.js CHANGED
@@ -4,13 +4,9 @@ import { Command } from 'commander';
4
4
  import { pull } from './pull.js';
5
5
  import { sonar } from './sonar.js';
6
6
  import { publish } from './publish.js';
7
- import { deployFromSite } from './deploy.js';
7
+ import {deploy, deployFromSite} from './deploy.js';
8
8
  import { deployTemplate } from './deploy.js';
9
9
  import { copy } from './copy.js';
10
- import { vaultAddSiteData } from './vault.js';
11
- import { addApacheSite } from './apache.js';
12
- import { haproxySync } from './haproxy.js';
13
- import { connectClone } from './connect.js';
14
10
  import dotenv from 'dotenv';
15
11
 
16
12
  dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
@@ -19,9 +15,6 @@ const program = new Command();
19
15
 
20
16
  // GIT SHA computation
21
17
  import { $ } from 'zx';
22
- import { deployCore } from './jenkins.js';
23
- import { runPipeline } from './pipline.js';
24
-
25
18
  const GIT_SHA = (await $`git log --pretty=format:'%h' -n 1`).stdout.trim();
26
19
 
27
20
  program
@@ -38,39 +31,6 @@ program
38
31
  await sonar(GIT_SHA);
39
32
  });
40
33
 
41
- program
42
- .command('addApacheSite')
43
- .description('Add site to apache')
44
- .action(async () => {
45
- await addApacheSite();
46
- });
47
-
48
- program
49
- .command('connectClone')
50
- .description('Clone connect site')
51
- .action(async () => {
52
- await connectClone();
53
- });
54
-
55
-
56
- program
57
- .command('haproxySync')
58
- .description('Sync haproxy config')
59
- .action(async () => {
60
- await haproxySync();
61
- });
62
-
63
-
64
-
65
- program
66
- .command('vaultAddSiteData')
67
- .description('Add m2m auth0 data to vault')
68
- .requiredOption('-s, --site-name <siteName>', 'Site name')
69
- .action(async (options) => {
70
- const { siteName, } = options;
71
- await vaultAddSiteData(siteName);
72
- });
73
-
74
34
  program
75
35
  .command('publish')
76
36
  .description('Publish a Docker image')
@@ -85,10 +45,9 @@ program
85
45
  .requiredOption('-t, --to-env <toEnv>', 'Target environment')
86
46
  .requiredOption('-F, --from-site <fromSite>', 'Source site')
87
47
  .requiredOption('-T, --to-site <toSite>', 'Target site')
88
- .option('-c, --deploy-core <deployCore>', 'Deploy Core', 'false')
89
48
  .action(async (options) => {
90
- const { fromEnv, fromSite, toEnv, toSite, deployCore } = options;
91
- await deployFromSite(fromEnv, fromSite, toEnv, toSite, deployCore);
49
+ const { fromEnv, fromSite, toEnv, toSite } = options;
50
+ await deployFromSite(fromEnv, fromSite, toEnv, toSite);
92
51
  });
93
52
 
94
53
  program
@@ -99,30 +58,6 @@ program
99
58
  });
100
59
 
101
60
  program
102
- .command('deploy-core <env> <site>')
103
- .description('Deploy Core')
104
- .option('-l, --liquibase <liquibase>', 'Application name', 'true')
105
- .option('-b, --branch <branch>', 'Branch', 'master')
106
- .action(async (env, site, options) => {
107
- await deployCore(env, site, options.liquibase, options.branch);
108
- });
109
-
110
- program
111
- .command('deploy-core-pipeline <env> <site>')
112
- .description('Deploy Core')
113
- .option('-l, --liquibase <liquibase>', 'Application name', 'true')
114
- .option('-b, --branch <branch>', 'Branch', 'master')
115
- .action(async (env, site, options) => {
116
- await runPipeline('site-deploy', 'deploy-core', 'main', {
117
- ENV: env,
118
- SITE: site,
119
- LIQUIBASE: options.liquibase,
120
- BRANCH: options.branch,
121
- });
122
- });
123
-
124
-
125
- program
126
61
  .command('copy')
127
62
  .description('Copy a Docker image between registries')
128
63
  .requiredOption('-a, --application <application>', 'Application name')
@@ -1,29 +1,5 @@
1
1
  export const environments = ['dev', 'qa', 'uat', 'stage', 'prod'];
2
2
 
3
- export const environmentConfig = {
4
- dev: {
5
- newUrl: (site) => `${site}.dev.dpai.tech`,
6
- oldUrl: (site) => `https://www.dev.docupaceinc.com/${site}`,
7
- },
8
- qa: {
9
- newUrl: (site) => `${site}.qa.dpai.tech`,
10
- oldUrl: (site) => `https://www.preprod.docupaceinc.com/${site}`,
11
- },
12
- uat: {
13
- newUrl: (site) => `${site}.qa.dpai.tech`,
14
- oldUrl: (site) => `https://www2.paperout.com/${site}_uat`,
15
- },
16
- stage: {
17
- newUrl: (site) => `${site}.stage.dpai.tech`,
18
- oldUrl: (site) => `https://www2.paperout.com/${site}_staging`,
19
- },
20
-
21
- prod: {
22
- newUrl: (site) => `${site}.dpai.tech`,
23
- oldUrl: (site) => `https://www2.paperout.com/${site}`,
24
- },
25
- };
26
-
27
3
  export const appInfo = {
28
4
  'graphql-server': {
29
5
  repositoryName: 'docupace-graphql-server',
@@ -59,14 +35,7 @@ export const getBitbucketInfo = () => {
59
35
  return {
60
36
  username: process.env.BITBUCKET_USERNAME,
61
37
  password: process.env.BITBUCKET_APP_PASSWORD,
62
- workspace: 'dp-cloud',
63
38
  };
64
39
  };
65
40
 
66
- export const getRepUrl = (repoName) => {
67
- const { username, password, workspace } = getBitbucketInfo();
68
- const repoUrl = `https://${username}:${password}@bitbucket.org/${workspace}/${repoName}.git`;
69
- return repoUrl;
70
- };
71
-
72
41
  export const jfRegistryUrl = 'registry.paperout.com';
@@ -3,11 +3,8 @@ import path from 'path';
3
3
  import yaml from 'js-yaml';
4
4
  import { $ } from 'zx';
5
5
  import lodash from 'lodash';
6
- import { appInfo, environmentConfig, getRepUrl } from './config.js';
6
+ import { appInfo, getBitbucketInfo } from './config.js';
7
7
  import { copy } from './copy.js';
8
- import axios from 'axios';
9
- import { runPipeline } from './pipline.js';
10
- import { deployCore } from './jenkins.js';
11
8
 
12
9
  /**
13
10
  * Clone the repository, read the YAML file, and return the parsed data and file paths.
@@ -24,7 +21,8 @@ function getRepoLocalPath(env) {
24
21
 
25
22
  async function cloneEnvRepository(env) {
26
23
  const { repoPath, repoName } = getRepoLocalPath(env);
27
- const repoUrl = getRepUrl(repoName);
24
+ const { username, password } = getBitbucketInfo();
25
+ const repoUrl = `https://${username}:${password}@bitbucket.org/dp-cloud/${repoName}.git`;
28
26
  console.log(`Cloning repository: ${repoName}`);
29
27
  await $`git clone ${repoUrl}`;
30
28
  console.log(`Repository cloned to: ${repoPath}`);
@@ -59,7 +57,7 @@ async function readDeployConfig(application, env, site) {
59
57
  export async function cloneAndReadDeployConfig(application, env, site) {
60
58
  const repoPath = await cloneEnvRepository(env);
61
59
 
62
- const { deployConfig, deployConfigFilePath } = await readDeployConfig(
60
+ const { deployConfig, deployConfigFilePath } = readDeployConfig(
63
61
  application,
64
62
  env,
65
63
  site,
@@ -109,7 +107,7 @@ export async function pushDeployConfig(repoPath, commitMessage) {
109
107
  console.log('📌 Committing changes to the repository...');
110
108
  await $`cd ${repoPath} && git config user.email "gitops@docupace.com"`;
111
109
  await $`cd ${repoPath} && git add .`;
112
- await $`cd ${repoPath} && git commit -m ${commitMessage}`;
110
+ await $`cd ${repoPath} && git commit -m "${commitMessage}"`;
113
111
  await $`cd ${repoPath} && git push`;
114
112
  console.log('✅ Changes pushed to the remote repository.');
115
113
 
@@ -189,72 +187,7 @@ export async function deploy(application, site) {
189
187
  console.log('Deployment completed successfully.');
190
188
  }
191
189
 
192
- async function getAppInfo(coreUrl) {
193
- const url = `${coreUrl}/b2b/rest/v1/appinfo`;
194
- return await axios.get(url);
195
- }
196
-
197
- function getBranchNameFromVersion(version) {
198
- const match = version.match(/(\d+\.\d+\.[^\-]+)(?:-(\d+)-g([a-f0-9]+))?/);
199
-
200
- if (!match) {
201
- throw new Error(`Invalid version format: ${version}`);
202
- }
203
-
204
- const fullVersion = match[1]; // e.g., 24.19.19, 24.20.alpha3, etc.
205
- const customBranch = match[2]; // e.g., 4, 58, or 0
206
- const commitHash = match[3]; // e.g., 668edef58e, 634cf6c904, etc.
207
-
208
- // If "alpha" is in the version or customBranch is non-zero, use the commit hash
209
- if (fullVersion.includes('alpha') || (customBranch && customBranch !== '0')) {
210
- return commitHash;
211
- }
212
-
213
- // Otherwise, use the full version
214
- return fullVersion;
215
- }
216
-
217
- async function getCoreBranchName(fromEnv, fromSite) {
218
- const envConfig = environmentConfig[fromEnv];
219
- const oldUrl = envConfig.oldUrl(fromSite);
220
- const newUrl = envConfig.newUrl(fromSite) + '/core';
221
-
222
- let appinfo;
223
- try {
224
- appinfo = await getAppInfo(oldUrl);
225
- } catch {
226
- try {
227
- appinfo = await getAppInfo(newUrl);
228
- } catch {
229
- throw new Error('Cannot get app info');
230
- }
231
- }
232
-
233
- const coreVersion = appinfo.data.core.version;
234
- const branchName = getBranchNameFromVersion(coreVersion);
235
- return branchName;
236
- }
237
-
238
- export async function deployFromSite(
239
- fromEnv,
240
- fromSite,
241
- toEnv,
242
- toSite,
243
- isDeployCore,
244
- ) {
245
- if (isDeployCore === 'true') {
246
- const branchName = await getCoreBranchName(fromEnv, fromSite);
247
- await deployCore(toEnv, toSite, 'true', branchName);
248
-
249
- // To be added back when splitting between on prem and in cloud
250
- /*await runPipeline('site-deploy', 'deploy-core', 'main', {
251
- ENV: toEnv,
252
- SITE: toSite,
253
- LIQUIBASE: 'true',
254
- BRANCH: branchName,
255
- });*/
256
- }
257
-
190
+ export async function deployFromSite(fromEnv, fromSite, toEnv, toSite) {
258
191
  // Clone repositories for source and target environments
259
192
  const fromRepoPath = await cloneEnvRepository(fromEnv);
260
193
  const toRepoPath =
@@ -1,59 +0,0 @@
1
- import groovy.json.JsonSlurper
2
-
3
- import hudson.model.*;
4
-
5
- def build = Thread.currentThread().executable
6
- def params = build.getEnvironment(listener)
7
-
8
- def site = params.get('site')
9
- def server = "jboss7"
10
- def environment = params.get('environment')
11
-
12
- def buildFile=new File("D:\\Docupace\\CustomFolders\\" + environment + "\\" + site + "\\" + server + "\\buildApp.properties")
13
-
14
- List<String> jboss7controllerResult = []
15
-
16
- def controllersReport = new File("D:\\Docupace\\controllers_report.json")
17
- def inputJSON = new JsonSlurper().parseText(controllersReport.text)
18
- def props = new Properties()
19
- buildFile.withInputStream { stream -> props.load(stream) }
20
- def webRootContext = props["web.root.context"]
21
- if (webRootContext == null || webRootContext =="core") webRootContext = props["docupace.config.client.id"].toLowerCase()
22
-
23
- webRootContext = webRootContext.replaceFirst('_sso','')
24
- def map = inputJSON.'content'
25
-
26
- def Boolean enabled
27
-
28
- map.each {k,v ->
29
- v.each{vk, vv -> if (vk == webRootContext ) {
30
- enabled = false
31
- if(vv.deploymentsProperty.size()>0) enabled = vv.deploymentsProperty[0].isEnabled
32
- if (enabled) jboss7controllerResult.push(k)
33
- else jboss7controllerResult << k
34
- }
35
- }
36
- }
37
-
38
- if (jboss7controllerResult.size()>0) {
39
- if (environment == 'preprod') {
40
- jboss7controllerResult.remove("dev-corjbdc10.corp.docupace.com")
41
- jboss7controllerResult.remove("usdoc-s-jbdc1.corp.docupace.com")
42
- }
43
- if (environment == 'dev') {
44
- jboss7controllerResult.remove("qa-corjbdc10.corp.docupace.com")
45
- jboss7controllerResult.remove("qa-corjbdc20.corp.docupace.com")
46
- jboss7controllerResult.remove("usdoc-s-jbdc2.corp.docupace.com")
47
- }
48
- }
49
-
50
- println jboss7controllerResult[0]
51
-
52
- env.jboss7controller = jboss7controllerResult[0]
53
-
54
- def serverGroup = inputJSON.'content'."${jboss7controller}"."${webRootContext}".'serverGroup'
55
-
56
- println serverGroup
57
-
58
- params.put("serverGroup", serverGroup)
59
-
@@ -1,36 +0,0 @@
1
- import { $ } from 'zx';
2
-
3
- export async function addApacheSite() {
4
- if (
5
- !process.env.ENVIRONMENT ||
6
- (process.env.ENVIRONMENT !== 'dev' && process.env.ENVIRONMENT !== 'qa')
7
- ) {
8
- log("Error: ENVIRONMENT must be either 'dev' or 'qa'.");
9
- process.exit(1);
10
- }
11
- if (!process.env.SITE) {
12
- log('Error: SITE cannot be empty.');
13
- process.exit(1);
14
- }
15
-
16
- // Save private key from base64
17
- const haproxyPrivateKey = process.env.HAPROXY_PRIVATE_KEY;
18
- if (!haproxyPrivateKey) {
19
- log('Error: HAPROXY_PRIVATE_KEY not set.');
20
- process.exit(1);
21
- }
22
-
23
- await fs.writeFile('private.key', Buffer.from(haproxyPrivateKey, 'base64'));
24
- await fs.chmod('private.key', 0o600);
25
-
26
- const server = `${process.env.ENVIRONMENT}-apalb01a.corp.docupace.com`;
27
- console.log("Running command");
28
- const sshCmd = (script) =>
29
- $`ssh -i private.key -o StrictHostKeyChecking=no root@${server} ${script}`;
30
-
31
- // The script is run twice in the Bash version
32
- await sshCmd(`/root/repo/iis-preprod/scripts/addsite/add_core_site.sh ${process.env.ENVIRONMENT} ${process.env.SITE}`);
33
- //await sshCmd(`/root/repo/iis-preprod/scripts/addsite/add_core_site.sh ${process.env.ENVIRONMENT} ${process.env.SITE}`);
34
- }
35
-
36
-
@@ -1,212 +0,0 @@
1
- import 'zx/globals'; // npm i zx
2
- import fs from 'fs-extra';
3
- import path from 'path';
4
- import axios from 'axios';
5
- import { $ } from 'zx';
6
-
7
-
8
- process.env.COMMON_VAULT_PATH = process.env.COMMON_VAULT_PATH || 'secret/data/common/config';
9
- process.env.VAULT_SKIP_VERIFY = process.env.VAULT_SKIP_VERIFY || 'true';
10
- process.env.CONNECT_DIR = process.env.CONNECT_DIR || 'connect';
11
-
12
-
13
- function log(msg) {
14
- console.log(`[*] ${msg}`);
15
- }
16
-
17
- /* --------------------------------
18
- * 1. GIT CHECKOUT
19
- * -------------------------------- */
20
- async function gitCheckout(repository, destDir, branch = 'master') {
21
- if (!(await fs.pathExists(destDir))) {
22
- log(`Directory ${destDir} does not exist. Cloning repository...`);
23
- } else {
24
- log(`Directory ${destDir} exists. Removing it...`);
25
- await fs.remove(destDir);
26
- log(`Cloning ${destDir} repository...`);
27
- }
28
-
29
- // Since we use zx, the environment variables can be read from process.env
30
- // e.g. $BITBUCKET_USERNAME, $BITBUCKET_APP_PASSWORD
31
- const username = process.env.BITBUCKET_USERNAME;
32
- const password = process.env.BITBUCKET_APP_PASSWORD;
33
-
34
- // Construct clone command
35
- const cloneUrl = `https://${username}:${password}@bitbucket.org/dp-cloud/${repository}.git`;
36
-
37
- // Perform the clone
38
- await $`git clone --branch=${branch} --depth 1 ${cloneUrl} ${destDir}`;
39
- }
40
-
41
- /* --------------------------------
42
- * 2. CHECK VAULT
43
- * -------------------------------- */
44
- async function checkVault(vaultPath) {
45
- if (!vaultPath) {
46
- log('Error: VAULT_PATH is required.');
47
- process.exit(1);
48
- }
49
-
50
- if (!process.env.VAULT_TOKEN || !process.env.VAULT_ADDR) {
51
- log('Error: VAULT_TOKEN and VAULT_ADDR must be set.');
52
- process.exit(1);
53
- }
54
-
55
- log(`Checking if ${vaultPath} exists and has data...`);
56
-
57
- try {
58
- const vaultAddr = process.env.VAULT_ADDR;
59
- const response = await axios.get(`${vaultAddr}/v1/${vaultPath}`, {
60
- headers: {
61
- 'X-Vault-Token': process.env.VAULT_TOKEN,
62
- },
63
- // If you want to skip TLS verification, you might need a custom httpsAgent
64
- // or globally define NODE_TLS_REJECT_UNAUTHORIZED=0.
65
- // Here we demonstrate a minimal approach:
66
- httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }),
67
- });
68
-
69
- // If data exists
70
- if (response.data?.data?.data && Object.keys(response.data.data.data).length > 0) {
71
- log(`Data exists at ${vaultPath}`);
72
- } else if (response.data?.warnings) {
73
- log(`Warning: ${response.data.warnings.join(', ')}`);
74
- process.exit(1);
75
- } else {
76
- log(`No data found at ${vaultPath} or path does not exist.`);
77
- }
78
- } catch (error) {
79
- log(`Error: Failed to connect to Vault server at ${process.env.VAULT_ADDR}`);
80
- process.exit(1);
81
- }
82
- }
83
-
84
- /* --------------------------------
85
- * 3. GET VAULT SECRETS
86
- * -------------------------------- */
87
- async function getVaultSecrets(vaultPath) {
88
- if (!vaultPath) {
89
- log('Error: VAULT_PATH is required.');
90
- process.exit(1);
91
- }
92
-
93
- try {
94
- const vaultAddr = process.env.VAULT_ADDR;
95
- const response = await axios.get(`${vaultAddr}/v1/${vaultPath}`, {
96
- headers: {
97
- 'X-Vault-Token': process.env.VAULT_TOKEN,
98
- },
99
- httpsAgent: new (require('https').Agent)({ rejectUnauthorized: false }),
100
- });
101
-
102
- // Check if the response is valid JSON
103
- return response.data;
104
- } catch (error) {
105
- log(`Error: Failed to connect to Vault server at ${process.env.VAULT_ADDR}`);
106
- process.exit(1);
107
- }
108
- }
109
-
110
-
111
- export async function connectClone() {
112
- const site = process.env.BUILD_SITE;
113
- if (!site) {
114
- log('Error: BUILD_SITE is not set');
115
- process.exit(1);
116
- }
117
- const siteCommonVaultPath = `secret/data/${site}/common/config`;
118
-
119
- // 1) checkVault
120
- await checkVault(siteCommonVaultPath);
121
-
122
- // 2) getVaultSecrets
123
- const secretsJson = await getVaultSecrets(siteCommonVaultPath);
124
- if (!secretsJson?.data?.data) {
125
- log('Failed to retrieve secret data.');
126
- process.exit(1);
127
- }
128
- const siteCommonSecrets = secretsJson.data.data;
129
-
130
- // 3) Export secrets as environment variables
131
- process.env.AUTH0_CLIENT_ID = siteCommonSecrets.AUTH0_CLIENT_ID;
132
- process.env.AUTH0_CLIENT_SECRET = siteCommonSecrets.AUTH0_CLIENT_SECRET;
133
-
134
- process.env.AUTH0_SUBDOMAIN="docupace-${BUILD_ENVIRONMENT}-${BUILD_SITE}"
135
- process.env.AUTH0_REGION_DOMAIN="us.auth0.com"
136
-
137
- log(`BUILD_ENVIRONMENT: ${process.env.BUILD_ENVIRONMENT}`);
138
- log(`BUILD_SITE: ${process.env.BUILD_SITE}`);
139
- log(`AUTH0_SUBDOMAIN: ${process.env.AUTH0_SUBDOMAIN}`);
140
- log(`AUTH0_REGION_DOMAIN: ${process.env.AUTH0_REGION_DOMAIN}`);
141
- log(`AUTH0_CLIENT_ID: ${process.env.AUTH0_CLIENT_ID}`);
142
-
143
- process.env.AUTH0_DOMAIN = `${process.env.AUTH0_SUBDOMAIN}.${process.env.AUTH0_REGION_DOMAIN}`;
144
-
145
- // 4) Clone 'connect-deploy' into CONNECT_DIR
146
- await gitCheckout('connect-deploy', process.env.CONNECT_DIR);
147
-
148
- // 5) Create site clone (emulating the dock.sh call)
149
- const cloneFrom = `${process.env.FROM_BUILD_ENVIRONMENT}/${process.env.FROM_BUILD_SITE}`;
150
- const projectHome = path.resolve(process.env.CONNECT_DIR);
151
-
152
- const cloneFromPath = path.join(projectHome, 'envs', cloneFrom);
153
- if (!(await fs.pathExists(cloneFromPath))) {
154
- log('Clone template directory not found');
155
- process.exit(1);
156
- }
157
-
158
- const newSitePath = path.join(
159
- projectHome,
160
- 'envs',
161
- process.env.BUILD_ENVIRONMENT,
162
- process.env.BUILD_SITE
163
- );
164
-
165
- if (!(await fs.pathExists(newSitePath))) {
166
- log('New site does not exist. Performing cloning...');
167
- // This is where the bash script does: bash dock.sh clone ...
168
- // We'll replicate with zx:
169
- process.env.IMAGE_VERSION=$`cd ${cloneFromPath} && grep -E '^IMAGE_VERSION=' dock.sh | cut -f2 -d=`
170
- await $`bash dock.sh clone ${process.env.BUILD_ENVIRONMENT} ${process.env.BUILD_SITE} ${process.env.IMAGE_VERSION}`;
171
- } else {
172
- log('Site already exists. Continuing Auth0 setup...');
173
- }
174
-
175
- // 6) Retrieve Auth0 metadata
176
- const targetSitePath = path.join(
177
- projectHome,
178
- 'envs',
179
- process.env.BUILD_ENVIRONMENT,
180
- process.env.BUILD_SITE
181
- );
182
- await $`cd ${targetSitePath} && bash dock.sh getAuth0Metadata`;
183
-
184
- // 7) Check conf files, print logs
185
- await $`grep "auth0" ${path.join(targetSitePath, 'conf/application.conf')}`;
186
- await $`ls -all ${path.join(targetSitePath, 'conf')}`;
187
- await $`ls -all ${path.join(targetSitePath, 'conf/saml')}`;
188
- await $`cat ${path.join(targetSitePath, 'conf/saml/auth0.xml')}`;
189
-
190
- // 8) Git add, commit, push
191
- await $`cd ${targetSitePath} && git checkout master && git pull --ff-only`;
192
- await $`cd ${targetSitePath} && git remote -v`;
193
- await $`cd ${targetSitePath} && git branch`;
194
- await $`cd ${targetSitePath} && git status`;
195
- await $`cd ${targetSitePath} && git add . ../sites.sh`;
196
- await $`cd ${targetSitePath} && git status`;
197
-
198
- const numChanges = (
199
- await $`cd ${targetSitePath} && git diff-index HEAD`
200
- ).stdout.split('\n').filter(Boolean).length;
201
-
202
- if (numChanges > 0) {
203
- const jiraTicket = process.env.JIRA_TICKET || 'NO_JIRA';
204
- const message = `${jiraTicket} usdoc-s-builui job download_auth0_metadata for ${process.env.BUILD_ENVIRONMENT}/${process.env.BUILD_SITE}`;
205
- log('About to commit changes to git');
206
- await $`cd ${targetSitePath} && git commit -m ${message}`;
207
- await $`cd ${targetSitePath} && git push -u origin master`;
208
- } else {
209
- log('No changes have been made. The site likely already has the correct configuration.');
210
- }
211
- }
212
-
@@ -1,50 +0,0 @@
1
- import { $ } from 'zx';
2
-
3
-
4
- export async function haproxySync() {
5
- const repoPath = '/root/repo/docupace-ansible';
6
- const inventory = path.join(repoPath, 'inventories/preprod/inventory');
7
-
8
- // Create haproxy.sh
9
- const scriptContent = `
10
- #!/bin/bash
11
-
12
- [[ ! -f ${inventory} ]] && ( echo "Alert: no inventory file: ${inventory}" ; exit 1 )
13
- cd ${repoPath}
14
- pwd
15
- git stash
16
- git pull origin master
17
- git checkout master
18
- git submodule update --remote
19
- git submodule foreach --recursive git checkout master
20
- git submodule foreach --recursive git pull origin master
21
-
22
- ansible-playbook -i inventories/preprod/inventory haproxy.yml -e "cluster=preprod"
23
-
24
- echo "proceeding"
25
- echo "committing changes"
26
- git add preprod-haproxy.cfg
27
- git commit -m "Sync haproxy"
28
- git push origin master
29
- `;
30
-
31
- await fs.writeFile('haproxy.sh', scriptContent);
32
-
33
- // Private key
34
- const haproxyPrivateKey = process.env.HAPROXY_PRIVATE_KEY;
35
- if (!haproxyPrivateKey) {
36
- log('Error: HAPROXY_PRIVATE_KEY not set.');
37
- process.exit(1);
38
- }
39
-
40
- await fs.writeFile('private.key', Buffer.from(haproxyPrivateKey, 'base64'));
41
- await fs.chmod('private.key', 0o600);
42
-
43
- await $`cat private.key`; // Just to mimic the script's behavior
44
-
45
- // Copy script to remote
46
- await $`scp -i private.key -o StrictHostKeyChecking=no haproxy.sh root@10.10.28.198:/tmp/haproxy.sh`;
47
-
48
- // Execute script on remote
49
- await $`ssh -i private.key -o StrictHostKeyChecking=no root@10.10.28.198 "bash /tmp/haproxy.sh"`;
50
- }
@@ -1,88 +0,0 @@
1
- import axios from 'axios';
2
-
3
- const JENKINS_URL = 'http://devops.corp.docupace.com';
4
- const JOB_NAME = 'auto-deploy-site';
5
- const USERNAME = process.env.CORE_JENKINS_USERNAME;
6
- const API_TOKEN = process.env.CORE_JENKINS_API_TOKEN;
7
-
8
- export async function deployCore(env, site, liquibase, gitBranch) {
9
- const parameters = {
10
- environment: env,
11
- site: site.toUpperCase(),
12
- runLiquibase: liquibase,
13
- gitBranch,
14
- };
15
-
16
- try {
17
- // Trigger the job
18
- console.log('Triggering Jenkins job...');
19
- const buildResponse = await axios.post(
20
- `${JENKINS_URL}/job/${JOB_NAME}/buildWithParameters`,
21
- new URLSearchParams(parameters),
22
- {
23
- auth: { username: USERNAME, password: API_TOKEN },
24
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
25
- validateStatus: (status) => status === 201 || status === 302, // Accept 201 and 302 as valid statuses
26
- },
27
- );
28
-
29
- const queueUrl = buildResponse.headers.location;
30
- console.log(`Job queued at: ${queueUrl}`);
31
-
32
- // Poll queue for executable URL
33
- let jobUrl = null;
34
- while (!jobUrl) {
35
- const queueResponse = await axios.get(`${queueUrl}api/json`, {
36
- auth: { username: USERNAME, password: API_TOKEN },
37
- });
38
- jobUrl = queueResponse.data.executable?.url || null;
39
-
40
- if (!jobUrl) {
41
- console.log('Waiting for job to start...');
42
- await new Promise((resolve) => setTimeout(resolve, 5000));
43
- }
44
- }
45
-
46
- jobUrl = jobUrl.replaceAll('https', 'http');
47
-
48
- console.log(`Job started at: ${jobUrl}`);
49
-
50
- // Stream console output
51
- const consoleUrl = `${jobUrl}consoleText`;
52
- let lastSize = 0;
53
-
54
- console.log('Streaming job output...');
55
- while (true) {
56
- const consoleResponse = await axios.get(consoleUrl, {
57
- auth: { username: USERNAME, password: API_TOKEN },
58
- responseType: 'text',
59
- });
60
-
61
- const consoleText = consoleResponse.data;
62
- const newOutput = consoleText.slice(lastSize);
63
- process.stdout.write(newOutput); // Write new output to console
64
- lastSize = consoleText.length;
65
-
66
- // Check job status
67
- const jobResponse = await axios.get(`${jobUrl}api/json`, {
68
- auth: { username: USERNAME, password: API_TOKEN },
69
- });
70
- const result = jobResponse.data.result;
71
-
72
- if (result) {
73
- console.log(`\nJob completed with result: ${result}`);
74
- if (result === 'SUCCESS') {
75
- process.exit(0);
76
- } else {
77
- process.exit(1);
78
- }
79
- }
80
-
81
- // Wait before polling again
82
- await new Promise((resolve) => setTimeout(resolve, 5000));
83
- }
84
- } catch (error) {
85
- console.error('Error:', error.message);
86
- process.exit(1);
87
- }
88
- }
@@ -1,94 +0,0 @@
1
- import axios from 'axios';
2
- import { getBitbucketInfo } from './config.js';
3
-
4
- const BITBUCKET_BASE_URL = 'https://api.bitbucket.org/2.0';
5
-
6
- async function triggerPipelineByName(
7
- repository,
8
- pipelineName,
9
- branch,
10
- variables,
11
- ) {
12
- const { username, password, workspace } = getBitbucketInfo();
13
- const url = `${BITBUCKET_BASE_URL}/repositories/${workspace}/${repository}/pipelines/`;
14
- const auth = {
15
- username: username,
16
- password: password,
17
- };
18
-
19
- const payload = {
20
- target: {
21
- type: 'pipeline_ref_target',
22
- ref_type: 'branch',
23
- ref_name: branch,
24
- selector: {
25
- type: 'custom',
26
- pattern: pipelineName,
27
- },
28
- },
29
- variables: Object.entries(variables).map(([key, value]) => ({
30
- key,
31
- value,
32
- secured: false, // Set to true if the variable should be secure
33
- })),
34
- };
35
-
36
- try {
37
- const response = await axios.post(url, payload, { auth });
38
- return response.data;
39
- } catch (error) {
40
- console.error(
41
- 'Error triggering custom pipeline:',
42
- error.response?.data || error.message,
43
- );
44
- throw error;
45
- }
46
- }
47
-
48
- async function getPipelineStatus(repository, pipelineUUID) {
49
- const { username, password, workspace } = getBitbucketInfo();
50
- const url = `${BITBUCKET_BASE_URL}/repositories/${workspace}/${repository}/pipelines/${pipelineUUID}`;
51
- const auth = {
52
- username: username,
53
- password: password,
54
- };
55
-
56
- try {
57
- const response = await axios.get(url, { auth });
58
- return response.data.state.name;
59
- } catch (error) {
60
- console.error(
61
- 'Error fetching pipeline status:',
62
- error.response?.data || error.message,
63
- );
64
- throw error;
65
- }
66
- }
67
-
68
- export async function runPipeline(repository, pipelineName, branch, variables) {
69
- try {
70
- console.log(
71
- `Triggering custom pipeline: ${pipelineName} for branch: ${branch}...`,
72
- );
73
- const pipeline = await triggerPipelineByName(
74
- repository,
75
- pipelineName,
76
- branch,
77
- variables,
78
- );
79
- const pipelineUUID = pipeline.uuid;
80
-
81
- console.log(`Pipeline triggered with UUID: ${pipelineUUID}`);
82
- let status = '';
83
- do {
84
- console.log('Checking pipeline status...');
85
- await new Promise((resolve) => setTimeout(resolve, 10000)); // Wait 10 seconds
86
- status = await getPipelineStatus(repository, pipelineUUID);
87
- console.log(`Pipeline status: ${status}`);
88
- } while (['IN_PROGRESS', 'PENDING', 'RUNNING'].includes(status));
89
-
90
- console.log(`Pipeline completed with status: ${status}`);
91
- } catch (error) {
92
- console.error('Error monitoring pipeline:', error.message);
93
- }
94
- }
package/src/next/vault.js DELETED
@@ -1,13 +0,0 @@
1
- import { $ } from 'zx';
2
-
3
-
4
- export async function vaultAddSiteData(SITE) {
5
- const AUTH0_CLIENT_ID = `${process.env.AUTH0_CLIENT_ID}`;
6
- const AUTH0_CLIENT_SECRET = `${process.env.AUTH0_CLIENT_SECRET}`;
7
- await $`export VAULT_SKIP_VERIFY=true`;
8
- await $`vault kv put secret/dp-${SITE}/common/config AUTH0_CLIENT_ID="${AUTH0_CLIENT_ID}" AUTH0_CLIENT_SECRET="${AUTH0_CLIENT_SECRET}"`
9
- }
10
-
11
-
12
-
13
-