-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage-plugin.mjs
More file actions
223 lines (217 loc) · 9.15 KB
/
Copy pathpackage-plugin.mjs
File metadata and controls
223 lines (217 loc) · 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { createHash } from "node:crypto";
import { cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { execFile, spawn } from "node:child_process";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { promisify } from "node:util";
import { build as bundle } from "esbuild";
const exec = promisify(execFile);
const root = path.resolve(import.meta.dirname, "..");
const pkg = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
const unraidVersion = pkg.unraidVersion ?? pkg.version;
if (!/^\d{4}\.\d{2}\.\d{2}\.\d+$/.test(unraidVersion)) {
throw new Error("package.json unraidVersion must use YYYY.MM.DD.REVISION format");
}
const build = path.join(root, "build");
const stage = path.join(build, "stage");
const artifactName = `unraid.vmbackup-${unraidVersion}-x86_64-1.txz`;
const artifact = path.join(build, artifactName);
const [releaseYear, releaseMonth, releaseDay] = unraidVersion.split(".").map(Number);
const sourceDateEpoch = Math.floor(Date.UTC(releaseYear, releaseMonth - 1, releaseDay) / 1000);
async function normalizeTextFiles(directory) {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name);
if (entry.isDirectory()) {
await normalizeTextFiles(file);
continue;
}
if (!entry.isFile()) continue;
const data = await readFile(file);
if (data.includes(0)) continue;
const text = data.toString("utf8");
if (text.includes("\uFFFD")) continue;
const normalized = text.replace(/\r\n?/g, "\n");
if (normalized !== text) await writeFile(file, normalized);
}
}
await rm(stage, { recursive: true, force: true });
await mkdir(path.join(stage, "usr/local/lib/unraid-vm-backup"), { recursive: true });
await cp(path.join(root, "plugin/source"), stage, { recursive: true });
await bundle({
entryPoints: [path.join(root, "src/main.ts")],
bundle: true,
platform: "node",
format: "cjs",
target: "node22",
outfile: path.join(stage, "usr/local/lib/unraid-vm-backup/service.cjs"),
});
await normalizeTextFiles(stage);
const getAvailablePort = async () => new Promise((resolve, reject) => {
const server = createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
server.close((error) => error ? reject(error) : resolve(address.port));
});
});
const smokeState = await mkdtemp(path.join(tmpdir(), "unraid-vmbackup-smoke-"));
const smokePort = await getAvailablePort();
const servicePath = path.join(stage, "usr/local/lib/unraid-vm-backup/service.cjs");
const service = spawn(process.execPath, [servicePath], {
env: {
...process.env,
UBR_HOST: "127.0.0.1",
UBR_PORT: String(smokePort),
UBR_STATE_DIR: smokeState,
UBR_DIAGNOSTICS_DIR: path.join(smokeState, "diagnostics"),
},
stdio: ["ignore", "pipe", "pipe"],
});
let smokeOutput = "";
service.stdout.on("data", (chunk) => { smokeOutput += chunk; });
service.stderr.on("data", (chunk) => { smokeOutput += chunk; });
try {
let healthy = false;
for (let attempt = 0; attempt < 30; attempt += 1) {
if (service.exitCode !== null) break;
try {
const response = await fetch(`http://127.0.0.1:${smokePort}/api/v1/health`);
healthy = response.ok && (await response.json()).status === "ok";
if (healthy) break;
} catch {}
await new Promise((resolve) => setTimeout(resolve, 100));
}
if (!healthy) throw new Error(`Packaged service failed its startup smoke test:\n${smokeOutput}`);
} finally {
if (service.exitCode === null) {
service.kill("SIGTERM");
await new Promise((resolve) => service.once("exit", resolve));
}
await rm(smokeState, { recursive: true, force: true });
}
await rm(artifact, { force: true });
const pythonCandidates = process.platform === "win32" ? ["python", "python3"] : ["python3", "python"];
let packaged = false;
for (const python of pythonCandidates) {
try {
await exec(python, [path.join(root, "scripts/create-plugin-package.py"), stage, artifact], {
cwd: root,
env: {
...process.env,
SOURCE_DATE_EPOCH: process.env.SOURCE_DATE_EPOCH ?? String(sourceDateEpoch),
},
});
packaged = true;
break;
} catch (error) {
if (error?.code !== "ENOENT") throw error;
}
}
if (!packaged) throw new Error("Python 3 is required to create the permission-safe Unraid package");
const digest = createHash("sha256").update(await readFile(artifact)).digest("hex");
const assetBase = process.env.UBR_PACKAGE_BASE_URL
?? `https://github.com/MiranoVerhoef/Unraid-VM-Backup/releases/download/v${unraidVersion}`;
const pluginUrl = process.env.UBR_PLUGIN_URL
?? "https://raw.githubusercontent.com/MiranoVerhoef/Unraid-VM-Backup/main/unraid.vmbackup.plg";
const plg = `<?xml version="1.0"?>
<PLUGIN name="unraid.vmbackup" author="Mirano Verhoef" version="${unraidVersion}" min="7.2.0" launch="VMBackup" icon="unraid.vmbackup.png" pluginURL="${pluginUrl}">
<CHANGES>### ${unraidVersion}\n- Require an external NFS or SMB repository by default and verify destination access before use.\n- Add an explicitly confirmed advanced option for same-host repositories.\n- Keep Node.js type definitions on the supported major version.</CHANGES>
<FILE Run="/bin/bash" Method="install">
<INLINE><![CDATA[
set -e
for command in node virsh qemu-img php openssl; do
command -v "$command" >/dev/null 2>&1 || { echo "Required Unraid command missing: $command"; exit 1; }
done
node_major="$(node --version | sed -E 's/^v([0-9]+).*/\\1/')"
[ -n "$node_major" ] && [ "$node_major" -ge 22 ] || { echo "Node.js 22+ required"; exit 1; }
php -m | grep -qi '^curl$' || { echo "Required PHP cURL extension missing"; exit 1; }
]]></INLINE>
</FILE>
<FILE Name="/boot/config/plugins/unraid.vmbackup/${artifactName}" Run="upgradepkg --install-new">
<URL>${assetBase}/${artifactName}</URL>
<SHA256>${digest}</SHA256>
</FILE>
<FILE Run="/bin/bash" Method="install">
<INLINE><![CDATA[
set -e
echo "VM Backup: preparing persistent configuration..."
chmod 0755 /etc/rc.d/rc.unraid-vmbackup
find /usr/local/emhttp/plugins/unraid.vmbackup -type d -exec chmod 0755 {} +
find /usr/local/emhttp/plugins/unraid.vmbackup -type f -exec chmod 0644 {} +
find /usr/local/emhttp/plugins/unraid.vmbackup/event -type f -exec chmod 0755 {} +
if ! /bin/bash /etc/rc.d/rc.unraid-vmbackup configure; then
echo "VM Backup could not create /boot/config/plugins/unraid.vmbackup/unraid-vm-backup.env"
exit 1
fi
rm -f /usr/local/emhttp/plugins/unraid.vmbackup/unraid.vmbackup.page
echo "VM Backup: starting service..."
if ! /bin/bash /etc/rc.d/rc.unraid-vmbackup restart; then
echo "VM Backup failed to start. Service log:"
tail -n 100 /var/log/unraid-vmbackup.log 2>/dev/null || true
exit 1
fi
if ! /bin/bash /etc/rc.d/rc.unraid-vmbackup status; then
echo "VM Backup stopped during installation. Service log:"
tail -n 100 /var/log/unraid-vmbackup.log 2>/dev/null || true
exit 1
fi
echo "VM Backup service started successfully."
]]></INLINE>
</FILE>
<FILE Run="/bin/bash" Method="remove"><INLINE><![CDATA[
/bin/bash /etc/rc.d/rc.unraid-vmbackup stop || true
vm_storage="$(awk -F= '$1 == "DOMAINDIR" {value=substr($0, index($0, "=") + 1); gsub(/^"|"$/, "", value); print value; exit}' /boot/config/domain.cfg 2>/dev/null)"
case "$vm_storage" in
/mnt|/mnt/*) ;;
*) vm_storage="/mnt/user/domains" ;;
esac
scratch_root="\${vm_storage%/}/.unraid-vm-backup-tmp"
case "$scratch_root" in
/mnt/.unraid-vm-backup-tmp|/mnt/*/.unraid-vm-backup-tmp) rm -rf -- "$scratch_root" ;;
esac
removepkg unraid.vmbackup || true
rm -rf -- /boot/config/plugins/unraid.vmbackup
rm -rf -- /usr/local/lib/unraid-vm-backup
rm -rf -- /usr/local/emhttp/plugins/unraid.vmbackup
rm -f -- /usr/local/emhttp/unraid.vmbackup
rm -f -- /etc/rc.d/rc.unraid-vmbackup
rm -f -- /var/run/unraid-vmbackup.pid /var/log/unraid-vmbackup.log
rm -rf -- /var/log/unraid-vmbackup
rm -rf -- /tmp/unraid-vmbackup-control-*
rm -rf -- /tmp/unraid-vmbackup-drill-*
rm -rf -- /tmp/unraid-vmbackup-recovery-test-*
rm -f -- /var/log/packages/unraid.vmbackup-* /var/log/scripts/unraid.vmbackup-*
rm -f -- /boot/config/plugins-error/unraid.vmbackup.plg /boot/config/plugins-stale/unraid.vmbackup.plg
residue=0
for path in \
/boot/config/plugins/unraid.vmbackup \
/usr/local/lib/unraid-vm-backup \
/usr/local/emhttp/plugins/unraid.vmbackup \
/usr/local/emhttp/unraid.vmbackup \
/etc/rc.d/rc.unraid-vmbackup \
/var/run/unraid-vmbackup.pid \
/var/log/unraid-vmbackup.log; do
if [ -e "$path" ] || [ -L "$path" ]; then
echo "VM Backup uninstall residue: $path"
residue=1
fi
done
for path in /var/log/packages/unraid.vmbackup-* /var/log/scripts/unraid.vmbackup-*; do
if [ -e "$path" ] || [ -L "$path" ]; then
echo "VM Backup uninstall residue: $path"
residue=1
fi
done
if [ "$residue" -eq 0 ]; then
echo "No VM Backup plugin residue detected."
else
echo "VM Backup local cleanup completed with the residue listed above."
fi
echo "External backup repositories were not modified."
]]></INLINE></FILE>
</PLUGIN>
`;
await writeFile(path.join(build, "unraid.vmbackup.plg"), plg);
await writeFile(path.join(root, "unraid.vmbackup.plg"), plg);
console.log(`${artifact}\nsha256 ${digest}`);