underpost 2.8.453 → 2.8.481

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/Dockerfile CHANGED
@@ -4,7 +4,7 @@ FROM debian:${BASE_DEBIAN}
4
4
 
5
5
  ENV DEBIAN_FRONTEND=noninteractive
6
6
 
7
- WORKDIR /code
7
+ WORKDIR /home/dd
8
8
 
9
9
  # Set root password to root, format is 'user:password'.
10
10
  RUN echo 'root:root' | chpasswd
@@ -39,10 +39,10 @@ RUN npm --version
39
39
 
40
40
  RUN npm install -g underpost
41
41
 
42
- VOLUME [ "/code/app/logs" ]
42
+ VOLUME [ "/home/dd/engine/logs" ]
43
43
 
44
44
  EXPOSE 22
45
45
 
46
46
  EXPOSE 4000-4004
47
47
 
48
- CMD [ "underpost", "new", "app" ]
48
+ CMD [ "underpost", "new", "service" ]
package/bin/build.js CHANGED
@@ -3,7 +3,7 @@ import { loggerFactory } from '../src/server/logger.js';
3
3
  import { shellExec } from '../src/server/process.js';
4
4
  import dotenv from 'dotenv';
5
5
  import { getCapVariableName } from '../src/client/components/core/CommonJs.js';
6
- import { buildProxyRouter, buildPortProxyRouter, Config, getPathsSSR, buildKindPorts } from '../src/server/conf.js';
6
+ import { getPathsSSR } from '../src/server/conf.js';
7
7
 
8
8
  const baseConfPath = './engine-private/conf/dd-cron/.env.production';
9
9
  if (fs.existsSync(baseConfPath)) dotenv.config({ path: baseConfPath, override: true });
@@ -20,21 +20,13 @@ const logger = loggerFactory(import.meta);
20
20
  const confName = process.argv[2];
21
21
  const basePath = '../pwa-microservices-template';
22
22
  const repoName = `engine-${confName.split('dd-')[1]}`;
23
- const privateRepoName = `${repoName}-private`;
24
- const privateRepoNameBackUp = `${repoName}-cron-backups`;
25
- const gitPrivateUrl = `https://${process.env.GITHUB_TOKEN}@github.com/underpostnet/${privateRepoName}.git`;
26
- const gitPrivateBackUpUrl = `https://${process.env.GITHUB_TOKEN}@github.com/underpostnet/${privateRepoNameBackUp}.git`;
27
23
 
28
24
  logger.info('', {
29
25
  confName,
30
26
  repoName,
31
- privateRepoName,
32
- privateRepoNameBackUp,
33
27
  basePath,
34
28
  });
35
29
 
36
- if (process.argv.includes('info')) process.exit(0);
37
-
38
30
  if (process.argv.includes('clean')) {
39
31
  if (fs.existsSync(`${basePath}/images`)) fs.copySync(`${basePath}/images`, `./images`);
40
32
  shellExec(`cd ${basePath} && git checkout .`);
@@ -42,173 +34,40 @@ if (process.argv.includes('clean')) {
42
34
  process.exit(0);
43
35
  }
44
36
 
45
- if (process.argv.includes('proxy')) {
46
- const env = process.argv.includes('development') ? 'development' : 'production';
47
- process.env.NODE_ENV = env;
48
- process.env.PORT = process.env.NODE_ENV === 'development' ? 4000 : 3000;
49
- process.argv[2] = 'proxy';
50
- process.argv[3] = fs.readFileSync('./engine-private/deploy/dd-router', 'utf8').trim();
51
-
52
- await Config.build();
53
- process.env.NODE_ENV = 'production';
54
- const router = buildPortProxyRouter(443, buildProxyRouter());
55
- const confServer = JSON.parse(fs.readFileSync(`./engine-private/conf/${confName}/conf.server.json`, 'utf8'));
56
- const confHosts = Object.keys(confServer);
57
-
58
- for (const host of Object.keys(router)) {
59
- if (!confHosts.find((_host) => host.match(_host))) {
60
- delete router[host];
61
- }
62
- }
63
-
64
- const ports = Object.values(router).map((p) => p.split(':')[2]);
65
-
66
- const fromPort = ports[0];
67
- const toPort = ports[ports.length - 1];
68
-
69
- logger.info('port range', { fromPort, toPort, router });
70
-
71
- const deploymentYamlFilePath = `./engine-private/conf/${confName}/build/${env}/deployment.yaml`;
72
-
73
- const deploymentYamlParts = fs.readFileSync(deploymentYamlFilePath, 'utf8').split('ports:');
74
- deploymentYamlParts[1] =
75
- buildKindPorts(fromPort, toPort) +
76
- ` type: LoadBalancer
77
- `;
78
-
79
- fs.writeFileSync(
80
- deploymentYamlFilePath,
81
- deploymentYamlParts.join(`ports:
82
- `),
83
- );
84
-
85
- let proxyYaml = '';
86
- let secretYaml = '';
87
-
88
- for (const host of Object.keys(confServer)) {
89
- if (env === 'production')
90
- secretYaml += `
91
- ---
92
- apiVersion: cert-manager.io/v1
93
- kind: Certificate
94
- metadata:
95
- name: ${host}
96
- spec:
97
- commonName: ${host}
98
- dnsNames:
99
- - ${host}
100
- issuerRef:
101
- name: letsencrypt-prod
102
- kind: ClusterIssuer
103
- secretName: ${host}`;
104
-
105
- const pathPortConditions = [];
106
- for (const path of Object.keys(confServer[host])) {
107
- const { peer } = confServer[host][path];
108
- const port = parseInt(router[`${host}${path === '/' ? '' : path}`].split(':')[2]);
109
- // logger.info('', { host, port, path });
110
- pathPortConditions.push({
111
- port,
112
- path,
113
- });
114
-
115
- if (peer) {
116
- // logger.info('', { host, port: port + 1, path: '/peer' });
117
- pathPortConditions.push({
118
- port: port + 1,
119
- path: '/peer',
120
- });
121
- }
122
- }
123
- // logger.info('', { host, pathPortConditions });
124
- proxyYaml += `
125
- ---
126
- apiVersion: projectcontour.io/v1
127
- kind: HTTPProxy
128
- metadata:
129
- name: ${host}
130
- spec:
131
- virtualhost:
132
- fqdn: ${host}${
133
- env === 'development'
134
- ? ''
135
- : `
136
- tls:
137
- secretName: ${host}`
138
- }
139
- routes:`;
140
- for (const conditionObj of pathPortConditions) {
141
- const { path, port } = conditionObj;
142
- proxyYaml += `
143
- - conditions:
144
- - prefix: ${path}
145
- enableWebsockets: true
146
- services:
147
- - name: ${confName}-${env}-service
148
- port: ${port}`;
149
- }
150
- }
151
- const yamlPath = `./engine-private/conf/${confName}/build/${env}/proxy.yaml`;
152
- fs.writeFileSync(yamlPath, proxyYaml, 'utf8');
153
- if (env === 'production') {
154
- const yamlPath = `./engine-private/conf/${confName}/build/${env}/secret.yaml`;
155
- fs.writeFileSync(yamlPath, secretYaml, 'utf8');
156
- }
157
-
158
- process.exit(0);
159
- }
160
37
  if (process.argv.includes('conf')) {
161
- if (!fs.existsSync(`../${privateRepoName}`)) {
162
- shellExec(`cd .. && git clone ${gitPrivateUrl}`, { silent: true });
163
- } else {
164
- shellExec(`cd ../${privateRepoName} && git pull`);
165
- }
166
- const toPath = `../${privateRepoName}/conf/${confName}`;
167
- fs.removeSync(toPath);
168
- fs.mkdirSync(toPath, { recursive: true });
169
- fs.copySync(`./engine-private/conf/${confName}`, toPath);
170
- shellExec(
171
- `cd ../${privateRepoName}` +
172
- ` && git add .` +
173
- ` && git commit -m "ci(engine-core-conf): ⚙️ Update ${confName} conf"` +
174
- ` && git push`,
175
- );
176
- process.exit(0);
177
- }
178
-
179
- if (process.argv.includes('cron-backups')) {
180
- if (!fs.existsSync(`../${privateRepoNameBackUp}`)) {
181
- shellExec(`cd .. && git clone ${gitPrivateBackUpUrl}`, { silent: true });
182
- } else {
183
- shellExec(`cd ../${privateRepoNameBackUp} && git pull`);
184
- }
185
- const serverConf = JSON.parse(fs.readFileSync(`./engine-private/conf/${confName}/conf.server.json`, 'utf8'));
186
- for (const host of Object.keys(serverConf)) {
187
- for (let path of Object.keys(serverConf[host])) {
188
- path = path.replaceAll('/', '-');
189
- const toPath = `../${privateRepoNameBackUp}/${host}${path}`;
190
- const fromPath = `./engine-private/cron-backups/${host}${path}`;
191
- if (fs.existsSync(fromPath)) {
192
- if (fs.existsSync(toPath)) fs.removeSync(toPath);
193
- logger.info('Build', { fromPath, toPath });
194
- fs.copySync(fromPath, toPath);
195
- }
38
+ for (const _confName of (confName === 'dd'
39
+ ? fs.readFileSync(`./engine-private/deploy/dd-router`, 'utf8')
40
+ : confName
41
+ ).split(',')) {
42
+ const _repoName = `engine-${_confName.split('dd-')[1]}`;
43
+ const privateRepoName = `${_repoName}-private`;
44
+ const privateGitUri = `${process.env.GITHUB_USERNAME}/${privateRepoName}`;
45
+
46
+ if (!fs.existsSync(`../${privateRepoName}`)) {
47
+ shellExec(`cd .. && underpost clone ${privateGitUri}`, { silent: true });
48
+ } else {
49
+ shellExec(`cd ../${privateRepoName} && underpost pull . ${privateGitUri}`);
50
+ }
51
+ const toPath = `../${privateRepoName}/conf/${_confName}`;
52
+ fs.removeSync(toPath);
53
+ fs.mkdirSync(toPath, { recursive: true });
54
+ fs.copySync(`./engine-private/conf/${_confName}`, toPath);
55
+ if (fs.existsSync(`./engine-private/replica`)) {
56
+ const replicas = await fs.readdir(`./engine-private/replica`);
57
+ for (const replica of replicas)
58
+ if (replica.match(_confName))
59
+ fs.copySync(`./engine-private/replica/${replica}`, `../${privateRepoName}/replica/${replica}`);
196
60
  }
61
+ shellExec(
62
+ `cd ../${privateRepoName}` +
63
+ ` && git add .` +
64
+ ` && underpost cmt . ci engine-core-conf 'Update ${_confName} conf'` +
65
+ ` && underpost push . ${privateGitUri}`,
66
+ );
197
67
  }
198
- shellExec(
199
- `cd ../${privateRepoNameBackUp}` +
200
- ` && git add .` +
201
- ` && git commit -m "ci(engine-core-cron-backups): ⚙️ Update ${confName} cron backups"` +
202
- ` && git push`,
203
- );
204
68
  process.exit(0);
205
69
  }
206
70
 
207
- if (process.argv.includes('test')) {
208
- fs.mkdirSync(`${basePath}/engine-private/conf`, { recursive: true });
209
- fs.copySync(`./engine-private/conf/${confName}`, `${basePath}/engine-private/conf/${confName}`);
210
- }
211
-
212
71
  const { DefaultConf } = await import(`../conf.${confName}.js`);
213
72
 
214
73
  {
@@ -294,27 +153,9 @@ const { DefaultConf } = await import(`../conf.${confName}.js`);
294
153
  const env = process.argv.includes('development') ? 'development' : 'production';
295
154
  const deploymentsFiles = ['Dockerfile', 'proxy.yaml', 'deployment.yaml', 'secret.yaml'];
296
155
  // remove engine-private of .dockerignore for local testing
297
-
298
- if (process.argv.includes('engine')) {
299
- fs.removeSync(`${basePath}/manifests/deployment`);
300
-
301
- if (!fs.existsSync(`./manifests/deployment/${confName}-${env}`))
302
- fs.mkdirSync(`./manifests/deployment/${confName}-${env}`);
303
-
304
- for (const file of deploymentsFiles) {
305
- if (fs.existsSync(`./engine-private/conf/${confName}/build/${env}/${file}`)) {
306
- fs.copyFileSync(`./engine-private/conf/${confName}/build/${env}/${file}`, `${basePath}/${file}`);
307
- fs.copyFileSync(
308
- `./engine-private/conf/${confName}/build/${env}/${file}`,
309
- `./manifests/deployment/${confName}-${env}/${file}`,
310
- );
311
- }
312
- }
313
- } else {
314
- for (const file of deploymentsFiles) {
315
- if (fs.existsSync(`./manifests/deployment/${confName}-${env}/${file}`)) {
316
- fs.copyFileSync(`./manifests/deployment/${confName}-${env}/${file}`, `${basePath}/${file}`);
317
- }
156
+ for (const file of deploymentsFiles) {
157
+ if (fs.existsSync(`./manifests/deployment/${confName}-${env}/${file}`)) {
158
+ fs.copyFileSync(`./manifests/deployment/${confName}-${env}/${file}`, `${basePath}/${file}`);
318
159
  }
319
160
  }
320
161
  }
package/bin/deploy.js CHANGED
@@ -159,10 +159,6 @@ try {
159
159
  }
160
160
  break;
161
161
 
162
- case 'remove-await-deploy': {
163
- if (fs.existsSync(`./tmp/await-deploy`)) fs.remove(`./tmp/await-deploy`);
164
- break;
165
- }
166
162
  case 'new-nodejs-app':
167
163
  {
168
164
  const deployId = process.argv[3];
@@ -229,6 +225,7 @@ try {
229
225
  break;
230
226
  case 'build-full-client':
231
227
  {
228
+ dotenv.config({ override: true });
232
229
  if (!process.argv[3]) process.argv[3] = 'default';
233
230
  const { deployId, folder } = loadConf(process.argv[3]);
234
231
 
@@ -254,20 +251,7 @@ try {
254
251
  serverConf[host][path].replicas.map((replica) => buildReplicaId({ deployId, replica })),
255
252
  );
256
253
 
257
- shellExec(Cmd.replica(deployId, host, path));
258
- }
259
- if (serverConf[host][path].db) {
260
- switch (serverConf[host][path].db.provider) {
261
- case 'mariadb':
262
- {
263
- shellExec(`node bin/db ${host}${path} create ${deployId}`);
264
- }
265
-
266
- break;
267
-
268
- default:
269
- break;
270
- }
254
+ // shellExec(Cmd.replica(deployId, host, path));
271
255
  }
272
256
  }
273
257
  }
@@ -276,7 +260,7 @@ try {
276
260
  await buildClient();
277
261
 
278
262
  for (const replicaDeployId of deployIdSingleReplicas) {
279
- shellExec(Cmd.conf(replicaDeployId));
263
+ shellExec(Cmd.conf(replicaDeployId, process.env.NODE_ENV));
280
264
  shellExec(Cmd.build(replicaDeployId));
281
265
  }
282
266
  }
package/bin/file.js CHANGED
@@ -1,7 +1,13 @@
1
1
  import fs from 'fs-extra';
2
2
 
3
3
  import { loggerFactory } from '../src/server/logger.js';
4
- import { cap, getCapVariableName, getDirname, newInstance } from '../src/client/components/core/CommonJs.js';
4
+ import {
5
+ cap,
6
+ getCapVariableName,
7
+ getDirname,
8
+ newInstance,
9
+ uniqueArray,
10
+ } from '../src/client/components/core/CommonJs.js';
5
11
  import { shellCd, shellExec } from '../src/server/process.js';
6
12
  import walk from 'ignore-walk';
7
13
  import { validateTemplatePath } from '../src/server/conf.js';
@@ -81,10 +87,12 @@ try {
81
87
  '.github/workflows/engine.core.ci.yml',
82
88
  '.github/workflows/engine.cyberia.ci.yml',
83
89
  './manifests/deployment/dd-lampp-development',
90
+ './manifests/deployment/dd-cyberia-development',
91
+ './manifests/deployment/dd-core-development',
84
92
  'bin/web3.js',
85
93
  'bin/cyberia.js',
86
94
  ]) {
87
- fs.removeSync('../pwa-microservices-template/' + deletePath);
95
+ if (fs.existsSync(deletePath)) fs.removeSync('../pwa-microservices-template/' + deletePath);
88
96
  }
89
97
  const originPackageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
90
98
  const templatePackageJson = JSON.parse(fs.readFileSync('../pwa-microservices-template/package.json', 'utf8'));
@@ -102,6 +110,9 @@ try {
102
110
  templatePackageJson.description = description;
103
111
  templatePackageJson.scripts.dev = dev;
104
112
  templatePackageJson.scripts.build = build;
113
+ templatePackageJson.keywords = uniqueArray(
114
+ ['pwa', 'microservices', 'template', 'builder'].concat(templatePackageJson.keywords),
115
+ );
105
116
  delete templatePackageJson.scripts['update-template'];
106
117
  fs.writeFileSync(
107
118
  '../pwa-microservices-template/package.json',
package/bin/index.js CHANGED
@@ -9,6 +9,7 @@ import fs from 'fs-extra';
9
9
  import { commitData } from '../src/client/components/core/CommonJs.js';
10
10
  import UnderpostScript from '../src/cli/script.js';
11
11
  import { shellExec } from '../src/server/process.js';
12
+ import UnderpostDB from '../src/cli/db.js';
12
13
 
13
14
  const npmRoot = getNpmRootPath();
14
15
  const underpostRoot = `${npmRoot}/underpost/.env`;
@@ -96,6 +97,17 @@ program
96
97
  })
97
98
  .description('Manage cluster, for default initialization base kind cluster');
98
99
 
100
+ program
101
+ .command('deploy')
102
+ .argument('<deploy-list>', 'Deploy id list, e.g. default-a,default-b')
103
+ .argument('[env]', 'Optional environment, for default is development')
104
+ .option('--remove', 'Delete deployments and services')
105
+ .option('--sync', 'Sync deployments env, ports, and replicas')
106
+ .option('--info-router', 'Display router structure')
107
+ .option('--build-manifest', 'Build kind yaml manifests: deployments, services, proxy and secrets')
108
+ .description('Manage deployment, for default deploy development pods')
109
+ .action(Underpost.deploy.callback);
110
+
99
111
  program
100
112
  .command('secret')
101
113
  .argument('<platform>', `Options: ${Object.keys(Underpost.secret)}`)
@@ -115,6 +127,7 @@ program
115
127
  .command('dockerfile-node-script')
116
128
  .argument('<deploy-id>', 'Deploy configuration id')
117
129
  .argument('[env]', 'Optional environment, for default is development')
130
+ .option('--run', 'Run custom entry point script')
118
131
  .description('Dockerfile custom node build script')
119
132
  .action(Underpost.image.dockerfile.script);
120
133
 
@@ -139,6 +152,14 @@ program
139
152
  fs.copySync(`${npmRoot}/underpost/node_modules`, './node_modules');
140
153
  });
141
154
 
155
+ program
156
+ .command('db')
157
+ .argument('<deploy-list>', 'Deploy id list, e.g. default-a,default-b')
158
+ .option('--import', 'Import container backups from repositories')
159
+ .option('--export', 'Export container backups to repositories')
160
+ .description('Manage databases')
161
+ .action(UnderpostDB.API.callback);
162
+
142
163
  program
143
164
  .command('script')
144
165
  .argument('operator', `Options: ${Object.keys(UnderpostScript.API)}`)
@@ -149,6 +170,13 @@ program
149
170
  )
150
171
  .action((...args) => Underpost.script[args[0]](args[1], args[2]));
151
172
 
152
- program.command('test').description('Run tests').action(Underpost.test.run);
173
+ program
174
+ .command('test')
175
+ .argument('[deploy-list]', 'Deploy id list, e.g. default-a,default-b')
176
+ .description('Manage Test, for default run current underpost default test')
177
+ .option('--inside-container', 'Inside container execution context')
178
+ .option('--sh', 'Copy to clipboard, container entrypoint shell command')
179
+ .option('--logs', 'Display container logs')
180
+ .action(Underpost.test.callback);
153
181
 
154
182
  program.parse();
@@ -58,7 +58,7 @@ services:
58
58
  cpus: '0.25'
59
59
  memory: 20M
60
60
  labels: # labels in Compose file instead of Dockerfile
61
- engine.version: '2.8.453'
61
+ engine.version: '2.8.481'
62
62
  networks:
63
63
  - load-balancer
64
64
 
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "type": "module",
3
3
  "main": "src/index.js",
4
4
  "name": "underpost",
5
- "version": "2.8.453",
5
+ "version": "2.8.481",
6
6
  "description": "pwa api rest template",
7
7
  "scripts": {
8
8
  "start": "env-cmd -f .env.production node --max-old-space-size=8192 src/server",
@@ -32,6 +32,10 @@
32
32
  "url": "git+https://github.com/underpostnet/pwa-microservices-template.git"
33
33
  },
34
34
  "keywords": [
35
+ "pwa",
36
+ "microservices",
37
+ "template",
38
+ "builder",
35
39
  "engine",
36
40
  "server",
37
41
  "proxy",
@@ -43,7 +43,7 @@ class UnderpostCluster {
43
43
  return;
44
44
  }
45
45
  const testClusterInit = shellExec(`kubectl get pods --all-namespaces -o wide`, {
46
- disableLogging: true,
46
+ disableLog: true,
47
47
  silent: true,
48
48
  stdout: true,
49
49
  });
@@ -93,7 +93,7 @@ class UnderpostCluster {
93
93
  silent: true,
94
94
  stdout: true,
95
95
  disableLog: true,
96
- }).match(`mongodb-0 1/1 Running`)
96
+ }).match(`mongodb-1 1/1 Running`)
97
97
  )
98
98
  return resolve();
99
99
  return monitor();
@@ -110,7 +110,7 @@ class UnderpostCluster {
110
110
  };
111
111
 
112
112
  shellExec(
113
- `kubectl exec -i mongodb-0 -- mongosh --quiet --json=relaxed \
113
+ `sudo kubectl exec -i mongodb-0 -- mongosh --quiet --json=relaxed \
114
114
  --eval 'use admin' \
115
115
  --eval 'rs.initiate(${JSON.stringify(mongoConfig)})' \
116
116
  --eval 'rs.status()'`,
package/src/cli/db.js ADDED
@@ -0,0 +1,148 @@
1
+ import { mergeFile, splitFileFactory } from '../server/conf.js';
2
+ import { loggerFactory } from '../server/logger.js';
3
+ import { shellExec } from '../server/process.js';
4
+ import fs from 'fs-extra';
5
+
6
+ const logger = loggerFactory(import.meta);
7
+
8
+ class UnderpostDB {
9
+ static API = {
10
+ async callback(deployList = 'default', options = { import: false, export: false }) {
11
+ const newBackupTimestamp = new Date().getTime();
12
+ const nameSpace = 'default';
13
+ for (const _deployId of deployList.split(',')) {
14
+ const deployId = _deployId.trim();
15
+ if (!deployId) continue;
16
+ const dbs = {};
17
+ const repoName = `engine-${deployId.split('dd-')[1]}-cron-backups`;
18
+
19
+ const confServer = JSON.parse(fs.readFileSync(`./engine-private/conf/${deployId}/conf.server.json`, 'utf8'));
20
+ for (const host of Object.keys(confServer)) {
21
+ for (const path of Object.keys(confServer[host])) {
22
+ const { db } = confServer[host][path];
23
+ if (db) {
24
+ const { provider, name, user, password } = db;
25
+ if (!dbs[provider]) dbs[provider] = {};
26
+
27
+ if (!(name in dbs[provider]))
28
+ dbs[provider][name] = { user, password, hostFolder: host + path.replaceAll('/', '-') };
29
+ }
30
+ }
31
+ }
32
+
33
+ if (!fs.existsSync(`../${repoName}`)) {
34
+ shellExec(`cd .. && underpost clone ${process.env.GITHUB_USERNAME}/${repoName}`);
35
+ } else {
36
+ shellExec(`cd ../${repoName} && underpost pull . ${process.env.GITHUB_USERNAME}/${repoName}`);
37
+ }
38
+
39
+ for (const provider of Object.keys(dbs)) {
40
+ for (const dbName of Object.keys(dbs[provider])) {
41
+ const { hostFolder, user, password } = dbs[provider][dbName];
42
+ if (hostFolder) {
43
+ logger.info('', { hostFolder, provider, dbName });
44
+
45
+ const backUpPath = `../${repoName}/${hostFolder}`;
46
+ const times = await fs.readdir(backUpPath);
47
+ const currentBackupTimestamp = Math.max(...times.map((t) => parseInt(t)));
48
+ dbs[provider][dbName].currentBackupTimestamp = currentBackupTimestamp;
49
+ const removeBackupTimestamp = Math.min(...times.map((t) => parseInt(t)));
50
+
51
+ const sqlContainerPath = `/home/${dbName}.sql`;
52
+ const _fromPartsParts = `../${repoName}/${hostFolder}/${currentBackupTimestamp}/${dbName}-parths.json`;
53
+ const _toSqlPath = `../${repoName}/${hostFolder}/${currentBackupTimestamp}/${dbName}.sql`;
54
+ const _toNewSqlPath = `../${repoName}/${hostFolder}/${newBackupTimestamp}/${dbName}.sql`;
55
+ const _toBsonPath = `../${repoName}/${hostFolder}/${currentBackupTimestamp}/${dbName}`;
56
+ const _toNewBsonPath = `../${repoName}/${hostFolder}/${newBackupTimestamp}/${dbName}`;
57
+
58
+ if (options.import === true && fs.existsSync(_fromPartsParts) && !fs.existsSync(_toSqlPath)) {
59
+ const names = JSON.parse(fs.readFileSync(_fromPartsParts, 'utf8')).map((_path) => {
60
+ return `../${repoName}/${hostFolder}/${currentBackupTimestamp}/${_path.split('/').pop()}`;
61
+ });
62
+ logger.info('merge Back Up paths', {
63
+ _fromPartsParts,
64
+ _toSqlPath,
65
+ names,
66
+ });
67
+ await mergeFile(names, _toSqlPath);
68
+ }
69
+
70
+ if (options.export === true && times.length >= 5) {
71
+ fs.removeSync(`../${repoName}/${hostFolder}/${removeBackupTimestamp}`);
72
+ fs.mkdirSync(`../${repoName}/${hostFolder}/${newBackupTimestamp}`, { recursive: true });
73
+ }
74
+
75
+ switch (provider) {
76
+ case 'mariadb': {
77
+ const podName = `mariadb-statefulset-0`;
78
+ const serviceName = 'mariadb';
79
+ if (options.import === true) {
80
+ shellExec(`sudo kubectl cp ${_toSqlPath} ${nameSpace}/${podName}:/${dbName}.sql`);
81
+ const cmd = `mariadb -u ${user} -p${password} ${dbName} < /${dbName}.sql`;
82
+ shellExec(
83
+ `kubectl exec -i ${podName} -- ${serviceName} -p${password} -e 'CREATE DATABASE ${dbName};'`,
84
+ );
85
+ shellExec(`sudo kubectl exec -i ${podName} -- sh -c "${cmd}"`);
86
+ }
87
+ if (options.export === true) {
88
+ const cmd = `mariadb-dump --user=${user} --password=${password} --lock-tables ${dbName} > ${sqlContainerPath}`;
89
+ shellExec(`sudo kubectl exec -i ${podName} -- sh -c "${cmd}"`);
90
+ shellExec(`sudo kubectl cp ${nameSpace}/${podName}:${sqlContainerPath} ${_toNewSqlPath}`);
91
+ await splitFileFactory(dbName, _toNewSqlPath);
92
+ }
93
+ break;
94
+ }
95
+
96
+ case 'mongoose': {
97
+ if (options.import === true) {
98
+ const podName = `mongodb-0`;
99
+ shellExec(`sudo kubectl cp ${_toBsonPath} ${nameSpace}/${podName}:/${dbName}`);
100
+ const cmd = `mongorestore -d ${dbName} /${dbName}`;
101
+ shellExec(`sudo kubectl exec -i ${podName} -- sh -c "${cmd}"`);
102
+ }
103
+ if (options.export === true) {
104
+ const podName = `backup-access`;
105
+ const containerBaseBackupPath = '/backup';
106
+ let timeFolder = shellExec(
107
+ `sudo kubectl exec -i ${podName} -- sh -c "cd ${containerBaseBackupPath} && ls -a"`,
108
+ {
109
+ stdout: true,
110
+ disableLog: false,
111
+ silent: true,
112
+ },
113
+ ).split(`\n`);
114
+ timeFolder = timeFolder[timeFolder.length - 2];
115
+ if (timeFolder === '..') {
116
+ logger.warn(`Cannot backup available`, { timeFolder });
117
+ } else {
118
+ shellExec(
119
+ `sudo kubectl cp ${nameSpace}/${podName}:${containerBaseBackupPath}/${timeFolder}/${dbName} ${_toNewBsonPath}`,
120
+ );
121
+ }
122
+ }
123
+ break;
124
+ }
125
+
126
+ default:
127
+ break;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ if (options.export === true) {
133
+ shellExec(`cd ../${repoName} && git add .`);
134
+ shellExec(
135
+ `underpost cmt ../${repoName} backup '' '${new Date(newBackupTimestamp).toLocaleDateString()} ${new Date(
136
+ newBackupTimestamp,
137
+ ).toLocaleTimeString()}'`,
138
+ );
139
+ shellExec(`cd ../${repoName} && underpost push . ${process.env.GITHUB_USERNAME}/${repoName}`, {
140
+ disableLog: true,
141
+ });
142
+ }
143
+ }
144
+ },
145
+ };
146
+ }
147
+
148
+ export default UnderpostDB;