underpost 2.8.6 → 2.8.8

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 (103) hide show
  1. package/.vscode/extensions.json +36 -3
  2. package/.vscode/settings.json +2 -0
  3. package/CHANGELOG.md +24 -4
  4. package/Dockerfile +9 -10
  5. package/README.md +41 -2
  6. package/bin/build.js +2 -2
  7. package/bin/db.js +1 -0
  8. package/bin/deploy.js +1521 -130
  9. package/bin/file.js +8 -0
  10. package/bin/index.js +1 -218
  11. package/cli.md +530 -0
  12. package/conf.js +4 -0
  13. package/docker-compose.yml +1 -1
  14. package/jsdoc.json +1 -1
  15. package/manifests/deployment/adminer/deployment.yaml +32 -0
  16. package/manifests/deployment/adminer/kustomization.yaml +7 -0
  17. package/manifests/deployment/adminer/service.yaml +13 -0
  18. package/manifests/deployment/dd-template-development/deployment.yaml +167 -0
  19. package/manifests/deployment/dd-template-development/proxy.yaml +46 -0
  20. package/manifests/deployment/fastapi/backend-deployment.yml +120 -0
  21. package/manifests/deployment/fastapi/backend-service.yml +19 -0
  22. package/manifests/deployment/fastapi/frontend-deployment.yml +54 -0
  23. package/manifests/deployment/fastapi/frontend-service.yml +15 -0
  24. package/manifests/deployment/fastapi/initial_data.sh +56 -0
  25. package/manifests/deployment/kafka/deployment.yaml +69 -0
  26. package/manifests/deployment/spark/spark-pi-py.yaml +21 -0
  27. package/manifests/envoy-service-nodeport.yaml +23 -0
  28. package/manifests/kubeadm-calico-config.yaml +119 -0
  29. package/manifests/kubelet-config.yaml +65 -0
  30. package/manifests/lxd/lxd-admin-profile.yaml +17 -0
  31. package/manifests/lxd/lxd-preseed.yaml +30 -0
  32. package/manifests/lxd/underpost-setup.sh +163 -0
  33. package/manifests/maas/lxd-preseed.yaml +32 -0
  34. package/manifests/maas/maas-setup.sh +82 -0
  35. package/manifests/mariadb/statefulset.yaml +2 -1
  36. package/manifests/mariadb/storage-class.yaml +10 -0
  37. package/manifests/mongodb/kustomization.yaml +1 -1
  38. package/manifests/mongodb/statefulset.yaml +12 -11
  39. package/manifests/mongodb/storage-class.yaml +9 -0
  40. package/manifests/mongodb-4.4/service-deployment.yaml +3 -3
  41. package/manifests/mysql/kustomization.yaml +7 -0
  42. package/manifests/mysql/pv-pvc.yaml +27 -0
  43. package/manifests/mysql/statefulset.yaml +55 -0
  44. package/manifests/postgresql/configmap.yaml +9 -0
  45. package/manifests/postgresql/kustomization.yaml +10 -0
  46. package/manifests/postgresql/pv.yaml +15 -0
  47. package/manifests/postgresql/pvc.yaml +13 -0
  48. package/manifests/postgresql/service.yaml +10 -0
  49. package/manifests/postgresql/statefulset.yaml +37 -0
  50. package/manifests/valkey/service.yaml +3 -9
  51. package/manifests/valkey/statefulset.yaml +12 -13
  52. package/package.json +3 -9
  53. package/src/api/default/default.service.js +1 -1
  54. package/src/api/user/user.service.js +14 -11
  55. package/src/cli/baremetal.js +60 -0
  56. package/src/cli/cluster.js +551 -65
  57. package/src/cli/cron.js +39 -8
  58. package/src/cli/db.js +20 -10
  59. package/src/cli/deploy.js +288 -86
  60. package/src/cli/env.js +10 -4
  61. package/src/cli/fs.js +21 -9
  62. package/src/cli/image.js +116 -124
  63. package/src/cli/index.js +319 -0
  64. package/src/cli/lxd.js +395 -0
  65. package/src/cli/monitor.js +236 -0
  66. package/src/cli/repository.js +14 -8
  67. package/src/client/components/core/Account.js +28 -24
  68. package/src/client/components/core/Blockchain.js +1 -1
  69. package/src/client/components/core/CalendarCore.js +14 -84
  70. package/src/client/components/core/CommonJs.js +2 -1
  71. package/src/client/components/core/Css.js +0 -1
  72. package/src/client/components/core/CssCore.js +10 -2
  73. package/src/client/components/core/Docs.js +1 -1
  74. package/src/client/components/core/EventsUI.js +3 -3
  75. package/src/client/components/core/FileExplorer.js +86 -78
  76. package/src/client/components/core/JoyStick.js +2 -2
  77. package/src/client/components/core/LoadingAnimation.js +1 -17
  78. package/src/client/components/core/LogIn.js +3 -3
  79. package/src/client/components/core/LogOut.js +1 -1
  80. package/src/client/components/core/Modal.js +14 -8
  81. package/src/client/components/core/Panel.js +19 -61
  82. package/src/client/components/core/PanelForm.js +13 -22
  83. package/src/client/components/core/Recover.js +3 -3
  84. package/src/client/components/core/RichText.js +1 -11
  85. package/src/client/components/core/Router.js +3 -1
  86. package/src/client/components/core/SignUp.js +2 -2
  87. package/src/client/components/default/RoutesDefault.js +3 -2
  88. package/src/client/services/default/default.management.js +45 -38
  89. package/src/client/ssr/Render.js +2 -0
  90. package/src/index.js +34 -2
  91. package/src/mailer/MailerProvider.js +3 -0
  92. package/src/runtime/lampp/Dockerfile +65 -0
  93. package/src/server/client-build.js +13 -0
  94. package/src/server/conf.js +151 -1
  95. package/src/server/dns.js +56 -18
  96. package/src/server/json-schema.js +77 -0
  97. package/src/server/logger.js +3 -3
  98. package/src/server/network.js +7 -122
  99. package/src/server/peer.js +2 -2
  100. package/src/server/proxy.js +4 -4
  101. package/src/server/runtime.js +24 -11
  102. package/src/server/start.js +122 -0
  103. package/src/server/valkey.js +27 -13
package/src/cli/lxd.js ADDED
@@ -0,0 +1,395 @@
1
+ import { getNpmRootPath } from '../server/conf.js';
2
+ import { getLocalIPv4Address } from '../server/dns.js';
3
+ import { pbcopy, shellExec } from '../server/process.js';
4
+ import fs from 'fs-extra';
5
+
6
+ /**
7
+ * @class UnderpostLxd
8
+ * @description Provides a set of static methods to interact with LXD,
9
+ * encapsulating common LXD operations for VM management and network testing.
10
+ */
11
+ class UnderpostLxd {
12
+ static API = {
13
+ /**
14
+ * @method callback
15
+ * @description Main entry point for LXD operations based on provided options.
16
+ * @param {object} options - Configuration options for LXD operations.
17
+ * @param {boolean} [options.init=false] - Initialize LXD.
18
+ * @param {boolean} [options.reset=false] - Reset LXD installation.
19
+ * @param {boolean} [options.dev=false] - Run in development mode (adjusts paths).
20
+ * @param {boolean} [options.install=false] - Install LXD snap.
21
+ * @param {boolean} [options.createVirtualNetwork=false] - Create default LXD bridge network (lxdbr0).
22
+ * @param {boolean} [options.createAdminProfile=false] - Create admin-profile for VMs.
23
+ * @param {boolean} [options.control=false] - Flag for control plane VM initialization.
24
+ * @param {boolean} [options.worker=false] - Flag for worker node VM initialization.
25
+ * @param {boolean} [options.k3s=false] - Flag to indicate K3s cluster type for VM initialization.
26
+ * @param {string} [options.initVm=''] - Initialize a specific VM.
27
+ * @param {string} [options.createVm=''] - Create a new VM with the given name.
28
+ * @param {string} [options.infoVm=''] - Display information about a specific VM.
29
+ * @param {string} [options.rootSize=''] - Root disk size for new VMs (e.g., '32GiB').
30
+ * @param {string} [options.joinNode=''] - Join a worker node to a control plane (format: 'workerName,controlName').
31
+ * @param {string} [options.expose=''] - Expose ports from a VM to the host (format: 'vmName:port1,port2').
32
+ * @param {string} [options.deleteExpose=''] - Delete exposed ports from a VM (format: 'vmName:port1,port2').
33
+ * @param {string} [options.test=''] - Test health, status and network connectivity for a VM.
34
+ * @param {string} [options.autoExposeK8sPorts=''] - Automatically expose common Kubernetes ports for the VM.
35
+ */
36
+ async callback(
37
+ options = {
38
+ init: false,
39
+ reset: false,
40
+ dev: false,
41
+ install: false,
42
+ createVirtualNetwork: false,
43
+ createAdminProfile: false,
44
+ control: false,
45
+ worker: false,
46
+ k3s: false,
47
+ initVm: '',
48
+ createVm: '',
49
+ infoVm: '',
50
+ rootSize: '',
51
+ joinNode: '',
52
+ expose: '',
53
+ deleteExpose: '',
54
+ test: '',
55
+ autoExposeK8sPorts: '',
56
+ },
57
+ ) {
58
+ const npmRoot = getNpmRootPath();
59
+ const underpostRoot = options?.dev === true ? '.' : `${npmRoot}/underpost`;
60
+ if (options.reset === true) {
61
+ shellExec(`sudo systemctl stop snap.lxd.daemon || true`);
62
+ shellExec(`sudo snap remove lxd --purge || true`);
63
+ }
64
+ if (options.install === true) shellExec(`sudo snap install lxd`);
65
+ if (options.init === true) {
66
+ shellExec(`sudo systemctl start snap.lxd.daemon`);
67
+ shellExec(`sudo systemctl status snap.lxd.daemon`);
68
+ const lxdPressedContent = fs
69
+ .readFileSync(`${underpostRoot}/manifests/lxd/lxd-preseed.yaml`, 'utf8')
70
+ .replaceAll(`127.0.0.1`, getLocalIPv4Address());
71
+ shellExec(`echo "${lxdPressedContent}" | lxd init --preseed`);
72
+ shellExec(`lxc cluster list`);
73
+ }
74
+ if (options.createVirtualNetwork === true) {
75
+ shellExec(`lxc network create lxdbr0 \
76
+ ipv4.address=10.250.250.1/24 \
77
+ ipv4.nat=true \
78
+ ipv4.dhcp=true \
79
+ ipv6.address=none`);
80
+ }
81
+ if (options.createAdminProfile === true) {
82
+ pbcopy(`lxc profile create admin-profile`);
83
+ shellExec(`cat ${underpostRoot}/manifests/lxd/lxd-admin-profile.yaml | lxc profile edit admin-profile`);
84
+ shellExec(`lxc profile show admin-profile`);
85
+ }
86
+ if (options.createVm && typeof options.createVm === 'string') {
87
+ pbcopy(
88
+ `lxc launch images:rockylinux/9 ${
89
+ options.createVm
90
+ } --vm --target lxd-node1 -c limits.cpu=2 -c limits.memory=4GB --profile admin-profile -d root,size=${
91
+ options.rootSize && typeof options.rootSize === 'string' ? options.rootSize + 'GiB' : '32GiB'
92
+ }`,
93
+ );
94
+ }
95
+ if (options.initVm && typeof options.initVm === 'string') {
96
+ let flag = '';
97
+ if (options.control === true) {
98
+ if (options.k3s === true) {
99
+ flag = ' -s -- --k3s';
100
+ } else {
101
+ // Default to kubeadm if not K3s
102
+ flag = ' -s -- --kubeadm';
103
+ }
104
+ shellExec(`lxc exec ${options.initVm} -- bash -c 'mkdir -p /home/dd/engine'`);
105
+ shellExec(`lxc file push /home/dd/engine/engine-private ${options.initVm}/home/dd/engine --recursive`);
106
+ shellExec(`lxc file push /home/dd/engine/manifests ${options.initVm}/home/dd/engine --recursive`);
107
+ } else if (options.worker == true) {
108
+ if (options.k3s === true) {
109
+ flag = ' -s -- --worker --k3s';
110
+ } else {
111
+ // Default to kubeadm worker
112
+ flag = ' -s -- --worker';
113
+ }
114
+ }
115
+ console.log(`Executing underpost-setup.sh on VM: ${options.initVm}`);
116
+ shellExec(`cat ${underpostRoot}/manifests/lxd/underpost-setup.sh | lxc exec ${options.initVm} -- bash${flag}`);
117
+ console.log(`underpost-setup.sh execution completed on VM: ${options.initVm}`);
118
+ }
119
+ // --- Automatic Kubernetes Port Exposure ---
120
+ if (options.autoExposeK8sPorts && typeof options.autoExposeK8sPorts === 'string') {
121
+ console.log(`Automatically exposing Kubernetes ports for VM: ${options.autoExposeK8sPorts}`);
122
+ const vmName = options.autoExposeK8sPorts;
123
+ const hostIp = getLocalIPv4Address();
124
+ let vmIp = '';
125
+ let retries = 0;
126
+ const maxRetries = 10;
127
+ const delayMs = 5000; // 5 seconds
128
+
129
+ // Wait for VM to get an IP address
130
+ while (!vmIp && retries < maxRetries) {
131
+ try {
132
+ console.log(`Attempting to get IPv4 address for ${vmName} (Attempt ${retries + 1}/${maxRetries})...`);
133
+ vmIp = shellExec(
134
+ `lxc list ${vmName} --format json | jq -r '.[0].state.network.enp5s0.addresses[] | select(.family=="inet") | .address'`,
135
+ { stdout: true },
136
+ ).trim();
137
+ if (vmIp) {
138
+ console.log(`IPv4 address found for ${vmName}: ${vmIp}`);
139
+ } else {
140
+ console.log(`IPv4 address not yet available for ${vmName}. Retrying in ${delayMs / 1000} seconds...`);
141
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
142
+ }
143
+ } catch (error) {
144
+ console.error(`Error getting IPv4 address for exposure: ${error.message}`);
145
+ console.log(`Retrying in ${delayMs / 1000} seconds...`);
146
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
147
+ }
148
+ retries++;
149
+ }
150
+
151
+ if (!vmIp) {
152
+ console.error(`Failed to get VM IP for ${vmName} after ${maxRetries} attempts. Cannot expose ports.`);
153
+ return;
154
+ }
155
+
156
+ let portsToExpose = [];
157
+ if (options.control === true) {
158
+ // Kubernetes API Server (Kubeadm and K3s both use 6443 by default)
159
+ portsToExpose.push('6443');
160
+ // Standard HTTP/HTTPS for Ingress if deployed
161
+ portsToExpose.push('80');
162
+ portsToExpose.push('443');
163
+ }
164
+ // Add common NodePorts if needed, or rely on explicit 'expose'
165
+ portsToExpose.push('30000'); // Example NodePort
166
+ portsToExpose.push('30001'); // Example NodePort
167
+ portsToExpose.push('30002'); // Example NodePort
168
+
169
+ const protocols = ['tcp']; // Most K8s services are TCP, UDP for some like DNS
170
+
171
+ for (const port of portsToExpose) {
172
+ for (const protocol of protocols) {
173
+ const deviceName = `${vmName}-${protocol}-port-${port}`;
174
+ try {
175
+ // Remove existing device first to avoid conflicts if re-running
176
+ shellExec(`lxc config device remove ${vmName} ${deviceName} || true`);
177
+ shellExec(
178
+ `lxc config device add ${vmName} ${deviceName} proxy listen=${protocol}:${hostIp}:${port} connect=${protocol}:${vmIp}:${port} nat=true`,
179
+ );
180
+ console.log(`Exposed ${protocol}:${hostIp}:${port} -> ${vmIp}:${port} for ${vmName}`);
181
+ } catch (error) {
182
+ console.error(`Failed to expose port ${port} for ${vmName}: ${error.message}`);
183
+ }
184
+ }
185
+ }
186
+ }
187
+ if (options.joinNode && typeof options.joinNode === 'string') {
188
+ const [workerNode, controlNode] = options.joinNode.split(',');
189
+ // Determine if it's a Kubeadm or K3s join
190
+ const isK3sJoin = options.k3s === true;
191
+
192
+ if (isK3sJoin) {
193
+ console.log(`Attempting to join K3s worker node ${workerNode} to control plane ${controlNode}`);
194
+ // Get K3s token from control plane
195
+ const k3sToken = shellExec(
196
+ `lxc exec ${controlNode} -- bash -c 'sudo cat /var/lib/rancher/k3s/server/node-token'`,
197
+ { stdout: true },
198
+ ).trim();
199
+ // Get control plane IP
200
+ const controlPlaneIp = shellExec(
201
+ `lxc list ${controlNode} --format json | jq -r '.[0].state.network.enp5s0.addresses[] | select(.family=="inet") | .address'`,
202
+ { stdout: true },
203
+ ).trim();
204
+
205
+ if (!k3sToken || !controlPlaneIp) {
206
+ console.error(`Failed to get K3s token or control plane IP. Cannot join worker.`);
207
+ return;
208
+ }
209
+ const k3sJoinCommand = `K3S_URL=https://${controlPlaneIp}:6443 K3S_TOKEN=${k3sToken} curl -sfL https://get.k3s.io | sh -`;
210
+ shellExec(`lxc exec ${workerNode} -- bash -c '${k3sJoinCommand}'`);
211
+ console.log(`K3s worker node ${workerNode} join command executed.`);
212
+ } else {
213
+ // Kubeadm join
214
+ console.log(`Attempting to join Kubeadm worker node ${workerNode} to control plane ${controlNode}`);
215
+ const token = shellExec(
216
+ `echo "$(lxc exec ${controlNode} -- bash -c 'sudo kubeadm token create --print-join-command')"`,
217
+ { stdout: true },
218
+ );
219
+ shellExec(`lxc exec ${workerNode} -- bash -c '${token}'`);
220
+ console.log(`Kubeadm worker node ${workerNode} join command executed.`);
221
+ }
222
+ }
223
+ if (options.infoVm && typeof options.infoVm === 'string') {
224
+ shellExec(`lxc config show ${options.infoVm}`);
225
+ shellExec(`lxc info --show-log ${options.infoVm}`);
226
+ shellExec(`lxc info ${options.infoVm}`);
227
+ shellExec(`lxc list ${options.infoVm}`);
228
+ }
229
+ if (options.expose && typeof options.expose === 'string') {
230
+ const [vmName, ports] = options.expose.split(':');
231
+ console.log({ vmName, ports });
232
+ const protocols = ['tcp']; // udp
233
+ const hostIp = getLocalIPv4Address();
234
+ const vmIp = shellExec(
235
+ `lxc list ${vmName} --format json | jq -r '.[0].state.network.enp5s0.addresses[] | select(.family=="inet") | .address'`,
236
+ { stdout: true },
237
+ ).trim();
238
+ if (!vmIp) {
239
+ console.error(`Could not get VM IP for ${vmName}. Cannot expose ports.`);
240
+ return;
241
+ }
242
+ for (const port of ports.split(',')) {
243
+ for (const protocol of protocols) {
244
+ const deviceName = `${vmName}-${protocol}-port-${port}`;
245
+ shellExec(`lxc config device remove ${vmName} ${deviceName} || true`); // Use || true to prevent error if device doesn't exist
246
+ shellExec(
247
+ `lxc config device add ${vmName} ${deviceName} proxy listen=${protocol}:${hostIp}:${port} connect=${protocol}:${vmIp}:${port} nat=true`,
248
+ );
249
+ console.log(`Manually exposed ${protocol}:${hostIp}:${port} -> ${vmIp}:${port} for ${vmName}`);
250
+ }
251
+ }
252
+ }
253
+ if (options.deleteExpose && typeof options.deleteExpose === 'string') {
254
+ const [controlNode, ports] = options.deleteExpose.split(':');
255
+ console.log({ controlNode, ports });
256
+ const protocols = ['tcp']; // udp
257
+ for (const port of ports.split(',')) {
258
+ for (const protocol of protocols) {
259
+ shellExec(`lxc config device remove ${controlNode} ${controlNode}-${protocol}-port-${port}`);
260
+ }
261
+ }
262
+ }
263
+
264
+ if (options.test && typeof options.test === 'string') {
265
+ const vmName = options.test;
266
+ console.log(`Starting comprehensive test for VM: ${vmName}`);
267
+
268
+ // 1. Monitor for IPv4 address
269
+ let vmIp = '';
270
+ let retries = 0;
271
+ const maxRetries = 10;
272
+ const delayMs = 5000; // 5 seconds
273
+
274
+ while (!vmIp && retries < maxRetries) {
275
+ try {
276
+ console.log(`Attempting to get IPv4 address for ${vmName} (Attempt ${retries + 1}/${maxRetries})...`);
277
+ vmIp = shellExec(
278
+ `lxc list ${vmName} --format json | jq -r '.[0].state.network.enp5s0.addresses[] | select(.family=="inet") | .address'`,
279
+ { stdout: true },
280
+ ).trim();
281
+ if (vmIp) {
282
+ console.log(`IPv4 address found for ${vmName}: ${vmIp}`);
283
+ } else {
284
+ console.log(`IPv4 address not yet available for ${vmName}. Retrying in ${delayMs / 1000} seconds...`);
285
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
286
+ }
287
+ } catch (error) {
288
+ console.error(`Error getting IPv4 address: ${error.message}`);
289
+ console.log(`Retrying in ${delayMs / 1000} seconds...`);
290
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
291
+ }
292
+ retries++;
293
+ }
294
+
295
+ if (!vmIp) {
296
+ console.error(`Failed to get IPv4 address for ${vmName} after ${maxRetries} attempts. Aborting tests.`);
297
+ return;
298
+ }
299
+
300
+ // 2. Iteratively check connection to google.com
301
+ let connectedToGoogle = false;
302
+ retries = 0;
303
+ while (!connectedToGoogle && retries < maxRetries) {
304
+ try {
305
+ console.log(`Checking connectivity to google.com from ${vmName} (Attempt ${retries + 1}/${maxRetries})...`);
306
+ const curlOutput = shellExec(
307
+ `lxc exec ${vmName} -- bash -c 'curl -s -o /dev/null -w "%{http_code}" http://google.com'`,
308
+ { stdout: true },
309
+ );
310
+ if (curlOutput.startsWith('2') || curlOutput.startsWith('3')) {
311
+ console.log(`Successfully connected to google.com from ${vmName}.`);
312
+ connectedToGoogle = true;
313
+ } else {
314
+ console.log(`Connectivity to google.com not yet verified. Retrying in ${delayMs / 1000} seconds...`);
315
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
316
+ }
317
+ } catch (error) {
318
+ console.error(`Error checking connectivity to google.com: ${error.message}`);
319
+ console.log(`Retrying in ${delayMs / 1000} seconds...`);
320
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
321
+ }
322
+ retries++;
323
+ }
324
+
325
+ if (!connectedToGoogle) {
326
+ console.error(
327
+ `Failed to connect to google.com from ${vmName} after ${maxRetries} attempts. Aborting further tests.`,
328
+ );
329
+ return;
330
+ }
331
+
332
+ // 3. Check other connectivity, network, and VM health parameters
333
+ console.log(`\n--- Comprehensive Health Report for ${vmName} ---`);
334
+
335
+ // VM Status
336
+ console.log('\n--- VM Status ---');
337
+ try {
338
+ const vmStatus = shellExec(`lxc list ${vmName} --format json`, { stdout: true, silent: true });
339
+ console.log(JSON.stringify(JSON.parse(vmStatus), null, 2));
340
+ } catch (error) {
341
+ console.error(`Error getting VM status: ${error.message}`);
342
+ }
343
+
344
+ // CPU Usage
345
+ console.log('\n--- CPU Usage ---');
346
+ try {
347
+ const cpuUsage = shellExec(`lxc exec ${vmName} -- bash -c 'top -bn1 | grep "Cpu(s)"'`, { stdout: true });
348
+ console.log(cpuUsage.trim());
349
+ } catch (error) {
350
+ console.error(`Error getting CPU usage: ${error.message}`);
351
+ }
352
+
353
+ // Memory Usage
354
+ console.log('\n--- Memory Usage ---');
355
+ try {
356
+ const memoryUsage = shellExec(`lxc exec ${vmName} -- bash -c 'free -m'`, { stdout: true });
357
+ console.log(memoryUsage.trim());
358
+ } catch (error) {
359
+ console.error(`Error getting memory usage: ${error.message}`);
360
+ }
361
+
362
+ // Disk Usage
363
+ console.log('\n--- Disk Usage (Root Partition) ---');
364
+ try {
365
+ const diskUsage = shellExec(`lxc exec ${vmName} -- bash -c 'df -h /'`, { stdout: true });
366
+ console.log(diskUsage.trim());
367
+ } catch (error) {
368
+ console.error(`Error getting disk usage: ${error.message}`);
369
+ }
370
+
371
+ // Network Interface Status
372
+ console.log('\n--- Network Interface Status (ip a) ---');
373
+ try {
374
+ const ipA = shellExec(`lxc exec ${vmName} -- bash -c 'ip a'`, { stdout: true });
375
+ console.log(ipA.trim());
376
+ } catch (error) {
377
+ console.error(`Error getting network interface status: ${error.message}`);
378
+ }
379
+
380
+ // DNS Resolution (resolv.conf)
381
+ console.log('\n--- DNS Configuration (/etc/resolv.conf) ---');
382
+ try {
383
+ const resolvConf = shellExec(`lxc exec ${vmName} -- bash -c 'cat /etc/resolv.conf'`, { stdout: true });
384
+ console.log(resolvConf.trim());
385
+ } catch (error) {
386
+ console.error(`Error getting DNS configuration: ${error.message}`);
387
+ }
388
+
389
+ console.log(`\nComprehensive test for VM: ${vmName} completed.`);
390
+ }
391
+ },
392
+ };
393
+ }
394
+
395
+ export default UnderpostLxd;
@@ -0,0 +1,236 @@
1
+ import { loadReplicas, pathPortAssignmentFactory } from '../server/conf.js';
2
+ import { loggerFactory } from '../server/logger.js';
3
+ import UnderpostDeploy from './deploy.js';
4
+ import axios from 'axios';
5
+ import UnderpostRootEnv from './env.js';
6
+ import fs from 'fs-extra';
7
+ import { shellExec } from '../server/process.js';
8
+ import { isInternetConnection } from '../server/dns.js';
9
+
10
+ const logger = loggerFactory(import.meta);
11
+
12
+ class UnderpostMonitor {
13
+ static API = {
14
+ async callback(
15
+ deployId,
16
+ env = 'development',
17
+ options = { now: false, single: false, msInterval: '', type: '', replicas: '', sync: false },
18
+ commanderOptions,
19
+ auxRouter,
20
+ ) {
21
+ if (deployId === 'dd' && fs.existsSync(`./engine-private/deploy/dd.router`)) {
22
+ for (const _deployId of fs.readFileSync(`./engine-private/deploy/dd.router`, 'utf8').split(','))
23
+ UnderpostMonitor.API.callback(
24
+ _deployId.trim(),
25
+ env,
26
+ options,
27
+ commanderOptions,
28
+ await UnderpostDeploy.API.routerFactory(_deployId, env),
29
+ );
30
+ return;
31
+ }
32
+
33
+ const router = auxRouter ?? (await UnderpostDeploy.API.routerFactory(deployId, env));
34
+
35
+ const confServer = loadReplicas(
36
+ JSON.parse(fs.readFileSync(`./engine-private/conf/${deployId}/conf.server.json`, 'utf8')),
37
+ 'proxy',
38
+ );
39
+
40
+ const pathPortAssignmentData = pathPortAssignmentFactory(router, confServer);
41
+
42
+ let errorPayloads = [];
43
+ if (options.sync === true) {
44
+ const currentTraffic = UnderpostDeploy.API.getCurrentTraffic(deployId);
45
+ if (currentTraffic) UnderpostRootEnv.API.set(`${deployId}-${env}-traffic`, currentTraffic);
46
+ }
47
+ let traffic = UnderpostRootEnv.API.get(`${deployId}-${env}-traffic`) ?? 'blue';
48
+ const maxAttempts = parseInt(
49
+ Object.keys(pathPortAssignmentData)
50
+ .map((host) => pathPortAssignmentData[host].length)
51
+ .reduce((accumulator, value) => accumulator + value, 0) * 2.5,
52
+ );
53
+
54
+ logger.info(`Init deploy monitor`, {
55
+ pathPortAssignmentData,
56
+ maxAttempts,
57
+ deployId,
58
+ env,
59
+ traffic,
60
+ });
61
+
62
+ const switchTraffic = () => {
63
+ if (traffic === 'blue') traffic = 'green';
64
+ else traffic = 'blue';
65
+ UnderpostRootEnv.API.set(`${deployId}-${env}-traffic`, traffic);
66
+ shellExec(
67
+ `node bin deploy --info-router --build-manifest --traffic ${traffic} --replicas ${
68
+ options.replicas ? options.replicas : 1
69
+ } ${deployId} ${env}`,
70
+ );
71
+ shellExec(`sudo kubectl apply -f ./engine-private/conf/${deployId}/build/${env}/proxy.yaml`);
72
+ };
73
+
74
+ const monitor = async (reject) => {
75
+ if (UnderpostRootEnv.API.get(`monitor-init-callback-script`))
76
+ shellExec(UnderpostRootEnv.API.get(`monitor-init-callback-script`));
77
+ const currentTimestamp = new Date().getTime();
78
+ errorPayloads = errorPayloads.filter((e) => currentTimestamp - e.timestamp < 60 * 1000 * 5);
79
+ logger.info(`[${deployId}-${env}] Check server health`);
80
+ for (const host of Object.keys(pathPortAssignmentData)) {
81
+ for (const instance of pathPortAssignmentData[host]) {
82
+ const { port, path } = instance;
83
+ if (path.match('peer') || path.match('socket')) continue;
84
+ let urlTest = `http://localhost:${port}${path}`;
85
+ switch (options.type) {
86
+ case 'remote':
87
+ case 'blue-green':
88
+ urlTest = `https://${host}${path}`;
89
+ break;
90
+
91
+ default:
92
+ break;
93
+ }
94
+ // logger.info('Test instance', urlTest);
95
+ await axios.get(urlTest, { timeout: 10000 }).catch((error) => {
96
+ // console.log(error);
97
+ const errorPayload = {
98
+ urlTest,
99
+ host,
100
+ port,
101
+ path,
102
+ name: error.name,
103
+ status: error.status,
104
+ code: error.code,
105
+ errors: error.errors,
106
+ timestamp: new Date().getTime(),
107
+ };
108
+ if (errorPayload.status !== 404) {
109
+ errorPayloads.push(errorPayload);
110
+ if (errorPayloads.length >= maxAttempts) {
111
+ const message = JSON.stringify(errorPayloads, null, 4);
112
+ logger.error(
113
+ `Deployment ${deployId} ${env} has been reached max attempts error payloads`,
114
+ errorPayloads,
115
+ );
116
+ switch (options.type) {
117
+ case 'blue-green':
118
+ {
119
+ const confServer = JSON.parse(
120
+ fs.readFileSync(`./engine-private/conf/${deployId}/conf.server.json`, 'utf8'),
121
+ );
122
+
123
+ shellExec(`kubectl delete configmap underpost-config`);
124
+ shellExec(
125
+ `kubectl create configmap underpost-config --from-file=/home/dd/engine/engine-private/conf/dd-cron/.env.${env}`,
126
+ );
127
+
128
+ for (const host of Object.keys(confServer)) {
129
+ shellExec(`sudo kubectl delete HTTPProxy ${host}`);
130
+ }
131
+ shellExec(`sudo kubectl rollout restart deployment/${deployId}-${env}-${traffic}`);
132
+
133
+ switchTraffic();
134
+ }
135
+
136
+ break;
137
+
138
+ case 'remote':
139
+ break;
140
+
141
+ default:
142
+ if (reject) reject(message);
143
+ else throw new Error(message);
144
+ }
145
+ errorPayloads = [];
146
+ }
147
+ logger.error(`Error accumulator ${deployId}-${env}-${traffic}`, errorPayloads.length);
148
+ }
149
+ });
150
+ }
151
+ }
152
+ };
153
+ if (options.now === true) await monitor();
154
+ if (options.single === true) return;
155
+ let optionsMsTimeout = parseInt(options.msInterval);
156
+ if (isNaN(optionsMsTimeout)) optionsMsTimeout = 60250; // 60.25 seconds
157
+ let monitorTrafficName;
158
+ let monitorPodName;
159
+ const monitorCallBack = (resolve, reject) => {
160
+ const envMsTimeout = UnderpostRootEnv.API.get(`${deployId}-${env}-monitor-ms`);
161
+ setTimeout(
162
+ async () => {
163
+ const isOnline = await isInternetConnection();
164
+ if (!isOnline) {
165
+ logger.warn('No internet connection');
166
+ monitorCallBack(resolve, reject);
167
+ return;
168
+ }
169
+ switch (options.type) {
170
+ case 'blue-green':
171
+ {
172
+ if (monitorTrafficName !== traffic) {
173
+ monitorTrafficName = undefined;
174
+ monitorPodName = undefined;
175
+ }
176
+ const cmd = `underpost config get container-status`;
177
+ const checkDeploymentReadyStatus = () => {
178
+ const pods = UnderpostDeploy.API.get(`${deployId}-${env}-${traffic}`);
179
+ if (pods && pods[0]) {
180
+ const { NAME } = pods[0];
181
+ if (
182
+ shellExec(`sudo kubectl exec -i ${NAME} -- sh -c "${cmd}"`, { stdout: true }).match(
183
+ `${deployId}-${env}-running-deployment`,
184
+ )
185
+ ) {
186
+ monitorPodName = NAME;
187
+ monitorTrafficName = `${traffic}`;
188
+ }
189
+ }
190
+ };
191
+ if (!monitorPodName) {
192
+ checkDeploymentReadyStatus();
193
+ monitorCallBack(resolve, reject);
194
+ return;
195
+ }
196
+ }
197
+
198
+ break;
199
+
200
+ default:
201
+ break;
202
+ }
203
+ for (const monitorStatus of [
204
+ { key: `monitor-input`, value: UnderpostRootEnv.API.get(`monitor-input`) },
205
+ {
206
+ key: `${deployId}-${env}-monitor-input`,
207
+ value: UnderpostRootEnv.API.get(`${deployId}-${env}-monitor-input`),
208
+ },
209
+ ])
210
+ switch (monitorStatus.value) {
211
+ case 'pause':
212
+ monitorCallBack(resolve, reject);
213
+ return;
214
+ case 'restart':
215
+ UnderpostRootEnv.API.delete(monitorStatus.key);
216
+ return reject();
217
+ case 'stop':
218
+ UnderpostRootEnv.API.delete(monitorStatus.key);
219
+ return resolve();
220
+ case 'blue-green-switch':
221
+ UnderpostRootEnv.API.delete(monitorStatus.key);
222
+ switchTraffic();
223
+ }
224
+ await monitor(reject);
225
+ monitorCallBack(resolve, reject);
226
+ return;
227
+ },
228
+ !isNaN(envMsTimeout) ? envMsTimeout : optionsMsTimeout,
229
+ );
230
+ };
231
+ return new Promise((...args) => monitorCallBack(...args));
232
+ },
233
+ };
234
+ }
235
+
236
+ export default UnderpostMonitor;