@underpostnet/underpost 2.8.4 → 2.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/.github/workflows/ghpkg.yml +13 -46
  2. package/.github/workflows/npmpkg.yml +67 -0
  3. package/.github/workflows/publish.yml +5 -5
  4. package/.github/workflows/pwa-microservices-template.page.yml +3 -2
  5. package/.github/workflows/pwa-microservices-template.test.yml +2 -2
  6. package/.vscode/settings.json +6 -1
  7. package/CHANGELOG.md +16 -0
  8. package/Dockerfile +6 -27
  9. package/bin/build.js +52 -169
  10. package/bin/deploy.js +6 -27
  11. package/bin/file.js +29 -15
  12. package/bin/index.js +158 -30
  13. package/bin/util.js +0 -8
  14. package/docker-compose.yml +1 -1
  15. package/manifests/mongodb/backup-access.yaml +16 -0
  16. package/manifests/mongodb/backup-cronjob.yaml +42 -0
  17. package/manifests/mongodb/backup-pv-pvc.yaml +22 -0
  18. package/manifests/mongodb/configmap.yaml +26 -0
  19. package/manifests/mongodb/headless-service.yaml +10 -0
  20. package/manifests/mongodb/kustomization.yaml +11 -0
  21. package/manifests/mongodb/pv-pvc.yaml +23 -0
  22. package/manifests/mongodb/statefulset.yaml +125 -0
  23. package/manifests/valkey/kustomization.yaml +2 -2
  24. package/manifests/valkey/service.yaml +17 -0
  25. package/manifests/valkey/statefulset.yaml +39 -0
  26. package/package.json +21 -5
  27. package/src/api/core/core.service.js +1 -1
  28. package/src/cli/cluster.js +154 -0
  29. package/src/cli/cron.js +90 -0
  30. package/src/cli/db.js +148 -0
  31. package/src/cli/deploy.js +277 -0
  32. package/src/cli/env.js +52 -0
  33. package/src/cli/image.js +125 -0
  34. package/src/cli/repository.js +104 -0
  35. package/src/cli/script.js +29 -0
  36. package/src/cli/secrets.js +37 -0
  37. package/src/cli/test.js +83 -0
  38. package/src/client/components/core/Auth.js +22 -4
  39. package/src/client/components/core/CommonJs.js +82 -1
  40. package/src/client/components/core/Css.js +1 -0
  41. package/src/client/components/core/Input.js +1 -1
  42. package/src/client/components/core/Modal.js +0 -1
  43. package/src/client/components/core/Scroll.js +1 -0
  44. package/src/client/components/core/Translate.js +4 -0
  45. package/src/client/components/core/VanillaJs.js +0 -9
  46. package/src/client/components/core/Worker.js +34 -31
  47. package/src/client/ssr/body/CacheControl.js +2 -2
  48. package/src/index.js +77 -26
  49. package/src/server/backup.js +49 -93
  50. package/src/server/client-build.js +1 -10
  51. package/src/server/client-formatted.js +5 -3
  52. package/src/server/conf.js +68 -187
  53. package/src/server/dns.js +48 -65
  54. package/src/server/logger.js +7 -7
  55. package/src/server/network.js +17 -7
  56. package/src/server/runtime.js +8 -22
  57. package/src/dns.js +0 -22
  58. package/src/server/project.js +0 -39
  59. package/startup.cjs +0 -12
  60. /package/manifests/deployment/{mongo-express.yaml → mongo-express/deployment.yaml} +0 -0
  61. /package/manifests/deployment/{phpmyadmin.yaml → phpmyadmin/deployment.yaml} +0 -0
@@ -0,0 +1,39 @@
1
+ ---
2
+ apiVersion: apps/v1
3
+ kind: StatefulSet
4
+ metadata:
5
+ name: service-valkey
6
+ namespace: default
7
+ spec:
8
+ serviceName: service-valkey
9
+ replicas: 1
10
+ selector:
11
+ matchLabels:
12
+ app: service-valkey
13
+ template:
14
+ metadata:
15
+ labels:
16
+ app: service-valkey
17
+ spec:
18
+ containers:
19
+ - name: service-valkey
20
+ image: docker.io/valkey/valkey:latest
21
+ env:
22
+ - name: TZ
23
+ value: Europe/Zurich
24
+ ports:
25
+ - containerPort: 6379
26
+ startupProbe:
27
+ tcpSocket:
28
+ port: 6379
29
+ failureThreshold: 30
30
+ periodSeconds: 5
31
+ timeoutSeconds: 5
32
+ livenessProbe:
33
+ tcpSocket:
34
+ port: 6379
35
+ failureThreshold: 2
36
+ periodSeconds: 30
37
+ timeoutSeconds: 5
38
+ restartPolicy: Always
39
+ automountServiceAccountToken: false
package/package.json CHANGED
@@ -2,20 +2,27 @@
2
2
  "type": "module",
3
3
  "main": "src/index.js",
4
4
  "name": "@underpostnet/underpost",
5
- "version": "2.8.4",
5
+ "version": "2.8.5",
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",
9
- "build": "node bin/deploy build-full-client",
9
+ "test": "env-cmd -f .env.test c8 mocha",
10
+ "pm2": "env-cmd -f .env.production pm2 start src/server.js --node-args=\"--max-old-space-size=8192\" --name engine",
10
11
  "dev": "env-cmd -f .env.development node src/client.dev default",
12
+ "dev-img": "env-cmd -f .env.development node src/server",
11
13
  "dev-api": "env-cmd -f .env.development nodemon --watch src --ignore src/client src/api",
14
+ "dev-client": "env-cmd -f .env.development node src/client.dev",
15
+ "proxy": "node src/proxy proxy",
12
16
  "docs": "jsdoc -c jsdoc.json",
13
17
  "install-global": "npm install -g pm2 && npm install -g jsdoc && npm install -g prettier && npm install -g env-cmd && npm install -g yarn && npm install -g auto-changelog",
14
18
  "install-test": "npm install -g mocha && npm install -g c8 && npm install -g nyc && npm install -g coveralls",
19
+ "install-underpost": "cp -a $(npm root -g)/underpost/node_modules ./node_modules && npm install --only=dev --ignore-scripts",
15
20
  "install": "npm run install-global && npm run install-test",
16
21
  "docker:start": "docker-compose up",
17
22
  "prettier": "prettier --write .",
18
- "test": "env-cmd -f .env.test c8 mocha"
23
+ "fix": "npm audit fix --force && npm audit",
24
+ "changelog": "auto-changelog",
25
+ "build": "node bin/deploy build-full-client"
19
26
  },
20
27
  "bin": {
21
28
  "underpost": "bin/index.js"
@@ -25,6 +32,10 @@
25
32
  "url": "git+https://github.com/underpostnet/pwa-microservices-template-ghpkg.git"
26
33
  },
27
34
  "keywords": [
35
+ "pwa",
36
+ "microservices",
37
+ "template",
38
+ "builder",
28
39
  "engine",
29
40
  "server",
30
41
  "proxy",
@@ -99,12 +110,17 @@
99
110
  "uglify-js": "^3.17.4",
100
111
  "validator": "^13.11.0",
101
112
  "vanilla-jsoneditor": "^2.3.2",
102
- "winston": "^3.11.0"
113
+ "winston": "^3.11.0",
114
+ "clean-jsdoc-theme": "^4.3.0",
115
+ "easy-json-schema": "^0.0.2-beta",
116
+ "mocha": "^10.8.2",
117
+ "plantuml": "^0.0.2",
118
+ "swagger-autogen": "^2.23.7"
103
119
  },
104
120
  "devDependencies": {
105
121
  "clean-jsdoc-theme": "^4.3.0",
106
122
  "easy-json-schema": "^0.0.2-beta",
107
- "mocha": "^10.4.0",
123
+ "mocha": "^10.8.2",
108
124
  "plantuml": "^0.0.2",
109
125
  "swagger-autogen": "^2.23.7"
110
126
  },
@@ -9,7 +9,7 @@ const CoreService = {
9
9
  /** @type {import('./core.model.js').CoreModel} */
10
10
  const Core = DataBaseProvider.instance[`${options.host}${options.path}`].mongoose.models.Core;
11
11
  if (req.path.startsWith('/sh')) {
12
- if (req.body.print) return shellExec(req.body.sh, { stdout: true });
12
+ if (req.body.stdout) return shellExec(req.body.sh, { stdout: true });
13
13
  shellExec(req.body.sh, { async: true });
14
14
  return 'Command "' + req.body.sh + '" running';
15
15
  }
@@ -0,0 +1,154 @@
1
+ import { timer } from '../client/components/core/CommonJs.js';
2
+ import { cliSpinner } from '../server/conf.js';
3
+ import { loggerFactory } from '../server/logger.js';
4
+ import { shellExec } from '../server/process.js';
5
+
6
+ const logger = loggerFactory(import.meta);
7
+
8
+ class UnderpostCluster {
9
+ static API = {
10
+ async init(options = { valkey: false, mariadb: false, valkey: false, full: false, info: false, nsUse: '' }) {
11
+ if (options.nsUse) {
12
+ shellExec(`kubectl config set-context --current --namespace=${options.nsUse}`);
13
+ return;
14
+ }
15
+ if (options.info) {
16
+ shellExec(`kubectl config get-contexts`); // config env persisente for manage multiple clusters
17
+ shellExec(`kubectl config get-clusters`);
18
+ shellExec(`kubectl get nodes -o wide`); // set of nodes of a cluster
19
+ shellExec(`kubectl config view | grep namespace`);
20
+ shellExec(`kubectl get ns -o wide`); // A namespace can have pods of different nodes
21
+ shellExec(`kubectl get pvc --all-namespaces -o wide`); // PersistentVolumeClaim -> request storage service
22
+ shellExec(`kubectl get pv --all-namespaces -o wide`); // PersistentVolume -> real storage
23
+ shellExec(`kubectl get cronjob --all-namespaces -o wide`);
24
+ shellExec(`kubectl get svc --all-namespaces -o wide`); // proxy dns gate way -> deployments, statefulsets, pods
25
+ shellExec(`kubectl get statefulsets --all-namespaces -o wide`); // set pods with data/volume persistence
26
+ shellExec(`kubectl get deployments --all-namespaces -o wide`); // set pods
27
+ shellExec(`kubectl get configmap --all-namespaces -o wide`);
28
+ shellExec(`kubectl get pods --all-namespaces -o wide`);
29
+ shellExec(
30
+ `kubectl get pod --all-namespaces -o="custom-columns=NAME:.metadata.name,INIT-CONTAINERS:.spec.initContainers[*].name,CONTAINERS:.spec.containers[*].name"`,
31
+ );
32
+ shellExec(
33
+ `kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{"\\n"}{.metadata.name}{":\\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}'`,
34
+ );
35
+ console.log();
36
+ logger.info('contour -------------------------------------------------');
37
+ for (const _k of ['Cluster', 'HTTPProxy', 'ClusterIssuer', 'Certificate']) {
38
+ shellExec(`kubectl get ${_k} --all-namespaces -o wide`);
39
+ }
40
+ logger.info('----------------------------------------------------------------');
41
+ shellExec(`kubectl get secrets --all-namespaces -o wide`);
42
+ shellExec(`docker secret ls`);
43
+ return;
44
+ }
45
+ const testClusterInit = shellExec(`kubectl get pods --all-namespaces -o wide`, {
46
+ disableLog: true,
47
+ silent: true,
48
+ stdout: true,
49
+ });
50
+ if (!(testClusterInit.match('kube-system') && testClusterInit.match('kube-proxy'))) {
51
+ shellExec(`containerd config default > /etc/containerd/config.toml`);
52
+ shellExec(`sed -i -e "s/SystemdCgroup = false/SystemdCgroup = true/g" /etc/containerd/config.toml`);
53
+ // shellExec(`cp /etc/kubernetes/admin.conf ~/.kube/config`);
54
+ shellExec(`sudo systemctl restart kubelet`);
55
+ shellExec(`sudo service docker restart`);
56
+ shellExec(`cd ./manifests && kind create cluster --config kind-config.yaml`);
57
+ shellExec(`sudo chown $(id -u):$(id -g) $HOME/.kube/config**`);
58
+ } else logger.warn('Cluster already initialized');
59
+
60
+ if (options.full || options.valkey) {
61
+ shellExec(`kubectl delete statefulset service-valkey`);
62
+ shellExec(`kubectl apply -k ./manifests/valkey`);
63
+ }
64
+ if (options.full || options.mariadb) {
65
+ shellExec(
66
+ `sudo kubectl create secret generic mariadb-secret --from-file=username=/home/dd/engine/engine-private/mariadb-username --from-file=password=/home/dd/engine/engine-private/mariadb-password`,
67
+ );
68
+ shellExec(
69
+ `sudo kubectl create secret generic github-secret --from-literal=GITHUB_TOKEN=${process.env.GITHUB_TOKEN}`,
70
+ );
71
+ shellExec(`kubectl delete statefulset mariadb-statefulset`);
72
+ shellExec(`kubectl apply -k ./manifests/mariadb`);
73
+ }
74
+ if (options.full || options.mongodb) {
75
+ shellExec(
76
+ `sudo kubectl create secret generic mongodb-keyfile --from-file=/home/dd/engine/engine-private/mongodb-keyfile`,
77
+ );
78
+ shellExec(
79
+ `sudo kubectl create secret generic mongodb-secret --from-file=username=/home/dd/engine/engine-private/mongodb-username --from-file=password=/home/dd/engine/engine-private/mongodb-password`,
80
+ );
81
+ shellExec(`kubectl delete statefulset mongodb`);
82
+ shellExec(`kubectl apply -k ./manifests/mongodb`);
83
+
84
+ await new Promise(async (resolve) => {
85
+ cliSpinner(3000, `[cluster.js] `, ` Load mongodb instance`, 'yellow', 'material');
86
+ await timer(3000);
87
+
88
+ const monitor = async () => {
89
+ cliSpinner(1000, `[cluster.js] `, ` Load mongodb instance`, 'yellow', 'material');
90
+ await timer(1000);
91
+ if (
92
+ shellExec(`kubectl get pods --all-namespaces -o wide`, {
93
+ silent: true,
94
+ stdout: true,
95
+ disableLog: true,
96
+ }).match(`mongodb-1 1/1 Running`)
97
+ )
98
+ return resolve();
99
+ return monitor();
100
+ };
101
+ await monitor();
102
+ });
103
+
104
+ const mongoConfig = {
105
+ _id: 'rs0',
106
+ members: [
107
+ { _id: 0, host: 'mongodb-0.mongodb-service:27017', priority: 1 },
108
+ { _id: 1, host: 'mongodb-1.mongodb-service:27017', priority: 1 },
109
+ ],
110
+ };
111
+
112
+ shellExec(
113
+ `sudo kubectl exec -i mongodb-0 -- mongosh --quiet --json=relaxed \
114
+ --eval 'use admin' \
115
+ --eval 'rs.initiate(${JSON.stringify(mongoConfig)})' \
116
+ --eval 'rs.status()'`,
117
+ );
118
+ }
119
+
120
+ if (options.full || options.contour)
121
+ shellExec(`kubectl apply -f https://projectcontour.io/quickstart/contour.yaml`);
122
+ },
123
+ reset() {
124
+ shellExec(`kind get clusters | xargs -t -n1 kind delete cluster --name`);
125
+ shellExec(`sudo kubeadm reset -f`);
126
+ shellExec('sudo rm -f /etc/cni/net.d/10-flannel.conflist');
127
+ shellExec('sudo iptables -F && sudo iptables -t nat -F && sudo iptables -t mangle -F && sudo iptables -X');
128
+ shellExec('sudo rm -f $HOME/.kube/config');
129
+ shellExec('sudo rm -rf /root/.local/share/Trash/files/*');
130
+ shellExec('sudo docker system prune -a -f');
131
+ shellExec('sudo service docker stop');
132
+ shellExec(`sudo rm -rf /var/lib/containers/storage/*`);
133
+ shellExec(`sudo rm -rf /var/lib/docker/volumes/*`);
134
+ shellExec(`sudo rm -rf /var/lib/docker~/*`);
135
+ shellExec(`sudo rm -rf /home/containers/storage/*`);
136
+ shellExec(`sudo rm -rf /home/docker/*`);
137
+ shellExec('sudo mv /var/lib/docker /var/lib/docker~');
138
+ shellExec('sudo mkdir /home/docker');
139
+ shellExec('sudo chmod 0711 /home/docker');
140
+ shellExec('sudo ln -s /home/docker /var/lib/docker');
141
+ shellExec(`sudo podman system prune -a -f`);
142
+ shellExec(`sudo podman system prune --all --volumes --force`);
143
+ shellExec(`sudo podman system prune --external --force`);
144
+ shellExec(`sudo podman system prune --all --volumes --force`);
145
+ shellExec(`sudo mkdir -p /home/containers/storage`);
146
+ shellExec('sudo chmod 0711 /home/containers/storage');
147
+ shellExec(
148
+ `sudo sed -i -e "s@/var/lib/containers/storage@/home/containers/storage@g" /etc/containers/storage.conf`,
149
+ );
150
+ shellExec(`sudo podman system reset -f`);
151
+ },
152
+ };
153
+ }
154
+ export default UnderpostCluster;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * UnderpostCron CLI index module
3
+ * @module src/cli/cron.js
4
+ * @namespace UnderpostCron
5
+ */
6
+
7
+ import Underpost from '../index.js';
8
+ import BackUp from '../server/backup.js';
9
+ import { Cmd } from '../server/conf.js';
10
+ import Dns from '../server/dns.js';
11
+ import { netWorkCron, saveRuntimeCron } from '../server/network.js';
12
+ import { shellExec } from '../server/process.js';
13
+ import fs from 'fs-extra';
14
+
15
+ /**
16
+ * UnderpostCron main module methods
17
+ * @class
18
+ * @memberof UnderpostCron
19
+ */
20
+ class UnderpostCron {
21
+ static JOB = {
22
+ /**
23
+ * DNS cli API
24
+ * @static
25
+ * @type {Dns}
26
+ * @memberof UnderpostCron
27
+ */
28
+ dns: Dns,
29
+ /**
30
+ * BackUp cli API
31
+ * @static
32
+ * @type {BackUp}
33
+ * @memberof UnderpostCron
34
+ */
35
+ backup: BackUp,
36
+ };
37
+ static API = {
38
+ /**
39
+ * Run the cron jobs
40
+ * @static
41
+ * @param {String} deployList - Comma separated deploy ids
42
+ * @param {String} jobList - Comma separated job ids
43
+ * @return {void}
44
+ * @memberof UnderpostCron
45
+ */
46
+ callback: async function (
47
+ deployList = 'default',
48
+ jobList = Object.keys(UnderpostCron.JOB),
49
+ options = { disableKindCluster: false, init: false },
50
+ ) {
51
+ if (options.init === true) {
52
+ await Underpost.test.setUpInfo();
53
+ const jobDeployId = fs.readFileSync('./engine-private/deploy/dd.cron', 'utf8').trim();
54
+ deployList = fs.readFileSync('./engine-private/deploy/dd.router', 'utf8').trim();
55
+ const confCronConfig = JSON.parse(fs.readFileSync(`./engine-private/conf/${jobDeployId}/conf.cron.json`));
56
+ if (confCronConfig.jobs && Object.keys(confCronConfig.jobs).length > 0) {
57
+ for (const job of Object.keys(confCronConfig.jobs)) {
58
+ const name = `${jobDeployId}-${job}`;
59
+ let deployId;
60
+ shellExec(Cmd.delete(name));
61
+ switch (job) {
62
+ case 'dns':
63
+ deployId = jobDeployId;
64
+ break;
65
+
66
+ default:
67
+ deployId = deployList;
68
+ break;
69
+ }
70
+ shellExec(Cmd.cron(deployId, job, name, confCronConfig.jobs[job].expression, options));
71
+ netWorkCron.push({
72
+ deployId,
73
+ jobId: job,
74
+ expression: confCronConfig.jobs[job].expression,
75
+ });
76
+ }
77
+ }
78
+ await saveRuntimeCron();
79
+ if (fs.existsSync(`./tmp/await-deploy`)) fs.remove(`./tmp/await-deploy`);
80
+ return;
81
+ }
82
+ for (const _jobId of jobList.split(',')) {
83
+ const jobId = _jobId.trim();
84
+ if (UnderpostCron.JOB[jobId]) await UnderpostCron.JOB[jobId].callback(deployList, options);
85
+ }
86
+ },
87
+ };
88
+ }
89
+
90
+ export default UnderpostCron;
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;