@synopackageland/cli 0.52.8 → 0.52.9
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/CHANGELOG.md +11 -0
- package/assets/go/compose-admin/go.mod +22 -0
- package/assets/go/compose-admin/go.sum +40 -0
- package/assets/go/compose-admin/main.go +443 -0
- package/assets/go/compose-admin/main_test.go +173 -0
- package/dist/build-spk/resource-worker.d.ts +3 -0
- package/dist/build-spk/resource-worker.js +20 -1
- package/dist/cli.js +9 -0
- package/dist/host/catalog-install.d.ts +1 -0
- package/dist/host/catalog-install.js +113 -6
- package/dist/host/compose-admin-build.d.ts +6 -0
- package/dist/host/compose-admin-build.js +17 -0
- package/dist/host/compose-admin.d.ts +22 -0
- package/dist/host/compose-admin.js +119 -0
- package/dist/host/compose-project-recovery.d.ts +2 -0
- package/dist/host/compose-project-recovery.js +2 -0
- package/dist/host/package-commands.d.ts +1 -1
- package/dist/host/package-commands.js +32 -2
- package/dist/load-env.js +1 -1
- package/dist/native-http-schema/source.json +1 -1
- package/dist/runtime/sdk-source.d.ts +1 -1
- package/dist/runtime/sdk-source.js +1 -1
- package/dist/standalone/inspect-spk.js +2 -1
- package/docs/compose-admin.md +82 -0
- package/package.json +3 -2
- package/schema/dsm-api-contract.json +23 -4
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
package main
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"context"
|
|
5
|
+
"errors"
|
|
6
|
+
"github.com/synopackageland/syno-pkg-land-sdk/compose"
|
|
7
|
+
"os"
|
|
8
|
+
"path/filepath"
|
|
9
|
+
"strings"
|
|
10
|
+
"testing"
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
func TestProfileEvidence(t *testing.T) {
|
|
14
|
+
if os.Getuid() != 0 {
|
|
15
|
+
t.Skip("root-owned profile evidence")
|
|
16
|
+
}
|
|
17
|
+
d := t.TempDir()
|
|
18
|
+
p := filepath.Join(d, "profile.config")
|
|
19
|
+
if id, e := readProfile(p); e != nil || id != "" {
|
|
20
|
+
t.Fatal(id, e)
|
|
21
|
+
}
|
|
22
|
+
want := strings.Repeat("a", 64)
|
|
23
|
+
for _, raw := range []string{`{}`, `{"id":"short"}`, `{"id":"` + want + `"}{}`, `invalid`} {
|
|
24
|
+
os.WriteFile(p, []byte(raw), 0600)
|
|
25
|
+
if _, e := readProfile(p); e == nil {
|
|
26
|
+
t.Fatal("unknown profile admitted")
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
os.WriteFile(p, []byte(`{"id":"`+want+`","private":"never exported"}`), 0600)
|
|
30
|
+
if id, e := readProfile(p); e != nil || id != want {
|
|
31
|
+
t.Fatal(id, e)
|
|
32
|
+
}
|
|
33
|
+
os.Chmod(p, 0666)
|
|
34
|
+
if _, e := readProfile(p); e == nil {
|
|
35
|
+
t.Fatal("writable profile")
|
|
36
|
+
}
|
|
37
|
+
os.Chmod(p, 0600)
|
|
38
|
+
link := filepath.Join(d, "link.config")
|
|
39
|
+
os.Symlink(p, link)
|
|
40
|
+
if _, e := readProfile(link); e == nil {
|
|
41
|
+
t.Fatal("symlink")
|
|
42
|
+
}
|
|
43
|
+
if _, e := readProfile(d); e == nil {
|
|
44
|
+
t.Fatal("directory")
|
|
45
|
+
}
|
|
46
|
+
os.Link(p, filepath.Join(d, "hardlink"))
|
|
47
|
+
if _, e := readProfile(p); e == nil {
|
|
48
|
+
t.Fatal("hardlink")
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
func TestContainerOwnership(t *testing.T) {
|
|
52
|
+
a := adapter{owner: compose.WorkerOwner{Package: "ExampleApp", Project: "exampleapp", Path: "/volume1/@appstore/ExampleApp/compose", Services: []string{"web"}}}
|
|
53
|
+
v := compose.WorkerContainer{ID: strings.Repeat("a", 64), State: "exited", Name: "exampleapp-web-1", Project: "exampleapp", Service: "web", WorkingDir: a.owner.Path, ConfigFiles: a.owner.Path + "/docker-compose.yml"}
|
|
54
|
+
if !a.validateContainer(v) {
|
|
55
|
+
t.Fatal("owned")
|
|
56
|
+
}
|
|
57
|
+
for _, edit := range []func(*compose.WorkerContainer){func(v *compose.WorkerContainer) { v.Project = "foreign" }, func(v *compose.WorkerContainer) { v.Name = "foreign" }, func(v *compose.WorkerContainer) { v.WorkingDir += "/../compose" }, func(v *compose.WorkerContainer) { v.Service = "foreign" }, func(v *compose.WorkerContainer) { v.ID = "short" }, func(v *compose.WorkerContainer) { v.ConfigFiles = "/foreign/docker-compose.yml" }} {
|
|
58
|
+
c := v
|
|
59
|
+
edit(&c)
|
|
60
|
+
if a.validateContainer(c) {
|
|
61
|
+
t.Fatal("foreign admitted")
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if got := a.canonical("/var/packages/ExampleApp/target/compose"); got != a.owner.Path {
|
|
65
|
+
t.Fatal(got)
|
|
66
|
+
}
|
|
67
|
+
for _, path := range []string{"/var/packages/OtherApp/target/compose", a.owner.Path + "/../compose"} {
|
|
68
|
+
if a.canonical(path) == a.owner.Path {
|
|
69
|
+
t.Fatal("arbitrary alias admitted")
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
func TestNativeAdapterCallsSDKReconciliation(t *testing.T) {
|
|
75
|
+
if os.Getuid() != 0 {
|
|
76
|
+
t.Skip("root-owned profile evidence")
|
|
77
|
+
}
|
|
78
|
+
for _, mode := range []string{"remove", "refresh", "unknown-write", "foreign", "get-2105", "running", "orphan", "foreign-orphan"} {
|
|
79
|
+
t.Run(mode, func(t *testing.T) {
|
|
80
|
+
root := t.TempDir()
|
|
81
|
+
id := strings.Repeat("a", 64)
|
|
82
|
+
name := "exampleapp-web-1"
|
|
83
|
+
a := adapter{owner: compose.WorkerOwner{Package: "ExampleApp", Project: "exampleapp", Path: "/volume1/@appstore/ExampleApp/compose", Services: []string{"web"}}, id: "owned", profileRoot: root}
|
|
84
|
+
ids := []any{id}
|
|
85
|
+
state := "exited"
|
|
86
|
+
project := "exampleapp"
|
|
87
|
+
writes := []string{}
|
|
88
|
+
if mode == "running" {
|
|
89
|
+
state = "running"
|
|
90
|
+
}
|
|
91
|
+
if mode == "foreign" {
|
|
92
|
+
project = "foreign"
|
|
93
|
+
}
|
|
94
|
+
profile := filepath.Join(root, name+".config")
|
|
95
|
+
if mode != "refresh" {
|
|
96
|
+
os.WriteFile(profile, []byte(`{"id":"`+id+`"}`), 0600)
|
|
97
|
+
}
|
|
98
|
+
oldCall := callAPI
|
|
99
|
+
t.Cleanup(func() { callAPI = oldCall })
|
|
100
|
+
callAPI = func(_ context.Context, apiName, method string, args map[string]any) (map[string]any, error) {
|
|
101
|
+
if apiName == "SYNO.Docker.Project" {
|
|
102
|
+
if mode == "get-2105" {
|
|
103
|
+
return nil, errors.New("2105")
|
|
104
|
+
}
|
|
105
|
+
containers := []any{}
|
|
106
|
+
for range ids {
|
|
107
|
+
containers = append(containers, map[string]any{"Id": id, "Name": "/" + name, "Config": map[string]any{"Labels": map[string]any{"com.docker.compose.project": project, "com.docker.compose.service": "web", "com.docker.compose.project.working_dir": a.owner.Path, "com.docker.compose.project.config_files": a.owner.Path + "/docker-compose.admin.yaml"}}, "State": map[string]any{"Status": state}})
|
|
108
|
+
}
|
|
109
|
+
return map[string]any{"id": "owned", "name": "exampleapp", "path": a.owner.Path, "is_package": true, "containerIds": ids, "containers": containers}, nil
|
|
110
|
+
}
|
|
111
|
+
if apiName != "SYNO.Docker.Container" {
|
|
112
|
+
t.Fatal(apiName)
|
|
113
|
+
}
|
|
114
|
+
if method == "list" {
|
|
115
|
+
if args["type"] != "all" || args["limit"] != -1 || args["offset"] != 0 {
|
|
116
|
+
t.Fatal(args)
|
|
117
|
+
}
|
|
118
|
+
rows := []any{}
|
|
119
|
+
if mode == "foreign-orphan" {
|
|
120
|
+
rows = append(rows, map[string]any{"name": name, "id": strings.Repeat("b", 64)})
|
|
121
|
+
}
|
|
122
|
+
return map[string]any{"containers": rows, "total": float64(len(rows))}, nil
|
|
123
|
+
}
|
|
124
|
+
if args["name"] != name {
|
|
125
|
+
t.Fatal("unowned mutation", args)
|
|
126
|
+
}
|
|
127
|
+
writes = append(writes, method)
|
|
128
|
+
if mode == "unknown-write" {
|
|
129
|
+
return nil, errors.New("private error")
|
|
130
|
+
}
|
|
131
|
+
if method == "delete" {
|
|
132
|
+
if args["force"] != false || args["preserve_profile"] != false {
|
|
133
|
+
t.Fatal(args)
|
|
134
|
+
}
|
|
135
|
+
ids = []any{}
|
|
136
|
+
os.Remove(profile)
|
|
137
|
+
} else if method == "stop" {
|
|
138
|
+
state = "exited"
|
|
139
|
+
os.WriteFile(profile, []byte(`{"id":"`+id+`"}`), 0600)
|
|
140
|
+
} else {
|
|
141
|
+
t.Fatal(method)
|
|
142
|
+
}
|
|
143
|
+
return map[string]any{}, nil
|
|
144
|
+
}
|
|
145
|
+
action := compose.RemoveStoppedWorkerContainers
|
|
146
|
+
if mode == "refresh" {
|
|
147
|
+
action = compose.RefreshWorkerProfiles
|
|
148
|
+
}
|
|
149
|
+
var err error
|
|
150
|
+
if strings.Contains(mode, "orphan") {
|
|
151
|
+
a.snapshot = []compose.WorkerContainer{{ID: id, Name: name}}
|
|
152
|
+
ids = []any{}
|
|
153
|
+
err = a.cleanupOrphans(context.Background())
|
|
154
|
+
} else {
|
|
155
|
+
err = compose.ReconcileWorkerContainers(context.Background(), &a, a.id, a.owner, action)
|
|
156
|
+
}
|
|
157
|
+
switch mode {
|
|
158
|
+
case "remove", "refresh", "orphan":
|
|
159
|
+
if err != nil || len(writes) != 1 {
|
|
160
|
+
t.Fatal(err, writes)
|
|
161
|
+
}
|
|
162
|
+
case "unknown-write":
|
|
163
|
+
if err == nil || len(writes) != 1 || strings.Contains(err.Error(), "private") {
|
|
164
|
+
t.Fatal(err, writes)
|
|
165
|
+
}
|
|
166
|
+
default:
|
|
167
|
+
if err == nil || len(writes) != 0 {
|
|
168
|
+
t.Fatal(err, writes)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -6,3 +6,6 @@ export declare function composeProjectName(packageId: string): string;
|
|
|
6
6
|
* needed (and kept, to preserve upgrade behaviour) while a tag is unpinned.
|
|
7
7
|
*/
|
|
8
8
|
export declare function renderDockerProjectResource(packageId: string, projectPath?: string, forcePull?: boolean, projectNameOverride?: string): Record<string, unknown>;
|
|
9
|
+
/** Accept the previous generator's explicit recreation flag during inspection.
|
|
10
|
+
* Only this known legacy field may differ; new builds always emit false. */
|
|
11
|
+
export declare function matchesComposeWorkerResource(actual: string | undefined, expected: string | undefined): boolean;
|
|
@@ -21,7 +21,7 @@ export function renderDockerProjectResource(packageId, projectPath = "compose",
|
|
|
21
21
|
path: projectPath,
|
|
22
22
|
build_params: {
|
|
23
23
|
force_pull: forcePull,
|
|
24
|
-
force_recreate:
|
|
24
|
+
force_recreate: false,
|
|
25
25
|
build: false,
|
|
26
26
|
},
|
|
27
27
|
},
|
|
@@ -29,3 +29,22 @@ export function renderDockerProjectResource(packageId, projectPath = "compose",
|
|
|
29
29
|
},
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
+
/** Accept the previous generator's explicit recreation flag during inspection.
|
|
33
|
+
* Only this known legacy field may differ; new builds always emit false. */
|
|
34
|
+
export function matchesComposeWorkerResource(actual, expected) {
|
|
35
|
+
if (actual === expected)
|
|
36
|
+
return true;
|
|
37
|
+
if (!actual || !expected)
|
|
38
|
+
return false;
|
|
39
|
+
try {
|
|
40
|
+
const value = JSON.parse(actual);
|
|
41
|
+
const projects = value['docker-project']?.projects;
|
|
42
|
+
if (!Array.isArray(projects) || projects.length !== 1 || projects[0]?.build_params?.force_recreate !== true)
|
|
43
|
+
return false;
|
|
44
|
+
projects[0].build_params.force_recreate = false;
|
|
45
|
+
return JSON.stringify(value) === expected;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -361,6 +361,15 @@ async function runCliWithin(argv) {
|
|
|
361
361
|
.option("--dry-run", "Print the removal plan without writing to DSM")
|
|
362
362
|
.option("--json", "Print a single JSON object")
|
|
363
363
|
.action(async (id, options) => { const { uninstallPackage } = await import('./host/package-commands.js'); const result = await uninstallPackage(id, options); emit('uninstall', result, JSON.stringify(result, null, 2)); });
|
|
364
|
+
program.command("compose-admin-helper")
|
|
365
|
+
.description("Build the administrator-only Compose adapter for a trusted NAS channel")
|
|
366
|
+
.requiredOption("--arch <arch>", "x86_64 or aarch64")
|
|
367
|
+
.requiredOption("--output <path>", "Output native executable")
|
|
368
|
+
.action(async (options) => {
|
|
369
|
+
const { buildComposeAdminHelper } = await import('./host/compose-admin-build.js');
|
|
370
|
+
const result = buildComposeAdminHelper(options.arch, options.output);
|
|
371
|
+
emit('compose-admin-helper', result, JSON.stringify(result, null, 2));
|
|
372
|
+
});
|
|
364
373
|
program.command("ctl").description("Control registered NAS Apps using described AI commands (ctl --help)");
|
|
365
374
|
program.command("audit-entry <main>")
|
|
366
375
|
.description("Audit one custom Go payload's target import graph without executing it")
|
|
@@ -57,6 +57,7 @@ export interface InstallWaitOptions {
|
|
|
57
57
|
}
|
|
58
58
|
export declare function waitForInstalledVersion(readState: (remainingMs: number) => InstalledPackageState | undefined | Promise<InstalledPackageState | undefined>, options: InstallWaitOptions): Promise<InstalledPackageState>;
|
|
59
59
|
export interface UninstallPackageOptions {
|
|
60
|
+
composeProject?: string;
|
|
60
61
|
dsmOrigin: string;
|
|
61
62
|
cookieHeader: string;
|
|
62
63
|
packageId: string;
|
|
@@ -2,12 +2,13 @@ import { CtlError } from '../ctl/errors.js';
|
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { progressReporter } from '../terminal-output.js';
|
|
4
4
|
import { pullContainerImages } from './container-pull.js';
|
|
5
|
+
import { openComposeAdmin, withComposeLifecycleLock, composeAdminConfigured, composeAdminWarning, COMPOSE_ADMIN_GUIDANCE } from './compose-admin.js';
|
|
5
6
|
import { reclaimOwnedComposeProject } from './compose-project-recovery.js';
|
|
6
7
|
import { savePullFailure } from './package-diagnostics.js';
|
|
7
8
|
import { readPackageOperation, operationOwnerAlive, savePackageOperation, clearPackageOperation, releasePackageOperation } from './package-operation.js';
|
|
8
9
|
import { cancelableInstall, installDelay, installWorkload, installCanceled } from './install-control.js';
|
|
9
10
|
import { dsmFetch } from "./dsm-http.js";
|
|
10
|
-
import { assertDsmCompoundResponse } from "./dsm-compound.js";
|
|
11
|
+
import { assertDsmCompoundResponse, DsmCompoundError } from "./dsm-compound.js";
|
|
11
12
|
import { dsmRequestTimeoutMs, dsmOperationTimeoutMs, dsmUninstallTimeoutMs, dsmPollIntervalMs, isHostTimeout } from '../nas/timeouts.js';
|
|
12
13
|
function normalizeDeppkgs(deppkgs) {
|
|
13
14
|
if (typeof deppkgs === "string") {
|
|
@@ -267,12 +268,16 @@ function uninstallFailure(packageId, error) {
|
|
|
267
268
|
return failure;
|
|
268
269
|
}
|
|
269
270
|
export async function uninstallPackageFromDsm(options) {
|
|
271
|
+
return withComposeLifecycleLock(options.dsmOrigin, options.packageId, () => uninstallPackageLocked(options));
|
|
272
|
+
}
|
|
273
|
+
async function uninstallPackageLocked(options) {
|
|
270
274
|
const deadline = Date.now() + (options.deadlineMs ?? dsmUninstallTimeoutMs());
|
|
271
275
|
const requestMs = dsmRequestTimeoutMs(), operationMs = dsmOperationTimeoutMs();
|
|
272
276
|
const pollMs = options.pollMs ?? dsmPollIntervalMs();
|
|
273
277
|
const progress = progressReporter(options.onProgress);
|
|
274
278
|
let phase = 'checking package state';
|
|
275
279
|
let previousFailure;
|
|
280
|
+
let composeAdmin;
|
|
276
281
|
const expired = () => new CtlError('DSM_UNINSTALL_TIMEOUT', `Package ${options.packageId}: overall uninstall budget exhausted while ${phase}; DSM may still be stopping/uninstalling.`, 'Check Package Center before retrying; stop/uninstall requests were not replayed');
|
|
277
282
|
const remaining = (limit) => {
|
|
278
283
|
if (Date.now() >= deadline)
|
|
@@ -335,18 +340,27 @@ export async function uninstallPackageFromDsm(options) {
|
|
|
335
340
|
throw new CtlError('PACKAGE_BUSY', `Package ${options.packageId} has an unresolved operation`, 'Wait for DSM to finish before uninstalling');
|
|
336
341
|
if (before.installed === false)
|
|
337
342
|
return;
|
|
343
|
+
if (options.composeProject) {
|
|
344
|
+
if (composeAdminConfigured())
|
|
345
|
+
composeAdmin = await openComposeAdmin({ packageId: options.packageId,
|
|
346
|
+
origin: options.dsmOrigin, project: options.composeProject });
|
|
347
|
+
else
|
|
348
|
+
progress(composeAdminWarning(options.packageId));
|
|
349
|
+
}
|
|
338
350
|
const broken = packageIsBroken(before) && !installInProgress(before);
|
|
339
351
|
if (broken) {
|
|
340
352
|
previousFailure = failureDetail(before);
|
|
341
|
-
progress(`${options.packageId}: broken package (${previousFailure || before.status}); uninstalling directly without stop…`);
|
|
353
|
+
progress(`${options.packageId}: broken package (${previousFailure || before.status}); ${composeAdmin ? 'verifying stopped Compose containers' : 'uninstalling directly without stop'}…`);
|
|
342
354
|
}
|
|
343
|
-
if (!broken && !packageStatusIsStopped(before)) {
|
|
355
|
+
if ((!broken || composeAdmin) && !packageStatusIsStopped(before)) {
|
|
344
356
|
phase = 'stopping';
|
|
345
357
|
await dispatch('SYNO.Core.Package.Control', 'stop');
|
|
346
358
|
const stopped = await wait(state => state.installed === false || packageStatusIsStopped(state));
|
|
347
359
|
if (stopped.installed === false)
|
|
348
360
|
return;
|
|
349
361
|
}
|
|
362
|
+
if (composeAdmin)
|
|
363
|
+
await composeAdmin.remove();
|
|
350
364
|
phase = 'uninstalling';
|
|
351
365
|
await dispatch('SYNO.Core.Package.Uninstallation', 'uninstall');
|
|
352
366
|
await wait(state => state.installed === false);
|
|
@@ -354,6 +368,9 @@ export async function uninstallPackageFromDsm(options) {
|
|
|
354
368
|
catch (error) {
|
|
355
369
|
throw uninstallFailure(options.packageId, error);
|
|
356
370
|
}
|
|
371
|
+
finally {
|
|
372
|
+
await composeAdmin?.close();
|
|
373
|
+
}
|
|
357
374
|
}
|
|
358
375
|
export function catalogInstallationRequests(entry, installed, sid, volumePath) {
|
|
359
376
|
const install = {
|
|
@@ -456,6 +473,9 @@ async function uploadLocalSpk(options, sid, timeoutMs) {
|
|
|
456
473
|
return { id: body.data.id, taskId: body.data.task_id };
|
|
457
474
|
}
|
|
458
475
|
export async function installPackageFromLocalSpk(options) {
|
|
476
|
+
return withComposeLifecycleLock(options.dsmOrigin, options.packageId, () => installPackageLocked(options));
|
|
477
|
+
}
|
|
478
|
+
async function installPackageLocked(options) {
|
|
459
479
|
const deadline = options.deadlineMs === undefined ? Infinity : Date.now() + options.deadlineMs;
|
|
460
480
|
const consumePoll = installWorkload(options.packageId, options.maxPolls);
|
|
461
481
|
const controller = new AbortController();
|
|
@@ -464,6 +484,7 @@ export async function installPackageFromLocalSpk(options) {
|
|
|
464
484
|
options = { ...options, signal };
|
|
465
485
|
let operation;
|
|
466
486
|
let verified = false;
|
|
487
|
+
let composeAdmin;
|
|
467
488
|
const requestMs = dsmRequestTimeoutMs(), operationMs = dsmOperationTimeoutMs();
|
|
468
489
|
const pollMs = options.pollMs ?? dsmPollIntervalMs();
|
|
469
490
|
const progress = progressReporter(options.onProgress);
|
|
@@ -479,6 +500,35 @@ export async function installPackageFromLocalSpk(options) {
|
|
|
479
500
|
process.once('SIGTERM', cancel);
|
|
480
501
|
try {
|
|
481
502
|
const sid = extractSid(options.cookieHeader);
|
|
503
|
+
const adminEnabled = composeAdminConfigured();
|
|
504
|
+
const profileWorkerFailure = (state) => Boolean(options.composeProject && state?.installed === true && state.version === options.version &&
|
|
505
|
+
!state.state && state.error?.code === 272 && /docker-project/i.test(JSON.stringify(state.error.workerMsg ?? [])));
|
|
506
|
+
const recoveryError = (error, state) => {
|
|
507
|
+
if (!adminEnabled && profileWorkerFailure(state) && error instanceof Error) {
|
|
508
|
+
const detail = failureDetail(state);
|
|
509
|
+
if (!error.message.includes(detail))
|
|
510
|
+
error.message += ` (DSM worker error: ${detail})`;
|
|
511
|
+
error.message += ` ${COMPOSE_ADMIN_GUIDANCE}`;
|
|
512
|
+
if (error instanceof CtlError)
|
|
513
|
+
error.hint += ` ${COMPOSE_ADMIN_GUIDANCE}`;
|
|
514
|
+
}
|
|
515
|
+
return error;
|
|
516
|
+
};
|
|
517
|
+
let recoveryAttempted = false;
|
|
518
|
+
const recoverProfile = async (state) => {
|
|
519
|
+
if (recoveryAttempted || !adminEnabled || !profileWorkerFailure(state))
|
|
520
|
+
return;
|
|
521
|
+
recoveryAttempted = true;
|
|
522
|
+
composeAdmin ??= await openComposeAdmin({ packageId: options.packageId, origin: options.dsmOrigin,
|
|
523
|
+
project: options.composeProject, signal });
|
|
524
|
+
if (!await composeAdmin.refresh())
|
|
525
|
+
return;
|
|
526
|
+
progress(`${options.packageId}: verified worker profile repaired; starting this version once…`);
|
|
527
|
+
await dsmWebApi(options.dsmOrigin, options.cookieHeader, { api: 'SYNO.Core.Package.Control', method: 'start',
|
|
528
|
+
version: '1', id: jsonApiParam(options.packageId), _sid: sid }, { timeoutMs: remaining(operationMs), signal });
|
|
529
|
+
return waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget), { signal, ignoreOperation: true }), { packageId: options.packageId, expectedVersion: options.version, requireRunning: true, repairing: true,
|
|
530
|
+
deadlineMs: Number.isFinite(deadline) ? remaining(Number.MAX_SAFE_INTEGER) : undefined, pollMs, consumePoll, signal, onProgress: progress });
|
|
531
|
+
};
|
|
482
532
|
let before;
|
|
483
533
|
while (!before) {
|
|
484
534
|
consumePoll();
|
|
@@ -499,8 +549,39 @@ export async function installPackageFromLocalSpk(options) {
|
|
|
499
549
|
throw new CtlError('PACKAGE_BUSY', `Package ${options.packageId} already has an unresolved operation`, 'Check package status before installing again');
|
|
500
550
|
if (options.composeProject) {
|
|
501
551
|
phase = 'checking Compose project ownership';
|
|
552
|
+
if (!adminEnabled)
|
|
553
|
+
progress(composeAdminWarning(options.packageId));
|
|
502
554
|
await reclaimOwnedComposeProject({ ...options, projectName: options.composeProject,
|
|
503
|
-
reclaim: !before.installed || packageIsBroken(before),
|
|
555
|
+
reclaim: adminEnabled ? false : !before.installed || packageIsBroken(before),
|
|
556
|
+
requireAbsent: adminEnabled && !before.installed, onProgress: progress });
|
|
557
|
+
if (adminEnabled && before.installed) {
|
|
558
|
+
// Capture installed inventory while the native NAS lock is held, before STOP.
|
|
559
|
+
composeAdmin = await openComposeAdmin({ packageId: options.packageId, origin: options.dsmOrigin,
|
|
560
|
+
project: options.composeProject, signal });
|
|
561
|
+
const recovered = await recoverProfile(before);
|
|
562
|
+
if (recovered) {
|
|
563
|
+
verified = true;
|
|
564
|
+
return recovered;
|
|
565
|
+
}
|
|
566
|
+
if (recoveryAttempted)
|
|
567
|
+
throw new CtlError('COMPOSE_WORKER_PROFILE_UNAVAILABLE', 'No verified profile repair was available; package install was not replayed', 'Inspect this App in Container Manager');
|
|
568
|
+
if (!packageStatusIsStopped(before)) {
|
|
569
|
+
phase = 'stopping';
|
|
570
|
+
await dsmWebApi(options.dsmOrigin, options.cookieHeader, { api: 'SYNO.Core.Package.Control',
|
|
571
|
+
method: 'stop', version: '1', id: jsonApiParam(options.packageId), _sid: sid }, { timeoutMs: remaining(operationMs), signal });
|
|
572
|
+
while (true) {
|
|
573
|
+
consumePoll();
|
|
574
|
+
const state = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal, ignoreOperation: true });
|
|
575
|
+
if (packageStatusIsStopped(state))
|
|
576
|
+
break;
|
|
577
|
+
if (state && packageIsBroken(state))
|
|
578
|
+
throw new CtlError('DSM_STOP_FAILED', 'Package stop failed; no containers were removed', 'Check DSM package status');
|
|
579
|
+
await installDelay(Math.min(pollMs, remaining(requestMs)), signal);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
// Broken packages are not assumed stopped: SDK validates every container.
|
|
583
|
+
await composeAdmin.remove();
|
|
584
|
+
}
|
|
504
585
|
}
|
|
505
586
|
if (options.containerImages?.length) {
|
|
506
587
|
phase = 'pulling container images';
|
|
@@ -531,17 +612,40 @@ export async function installPackageFromLocalSpk(options) {
|
|
|
531
612
|
assertDsmCompoundResponse(response);
|
|
532
613
|
}
|
|
533
614
|
catch (error) {
|
|
534
|
-
if (!isHostTimeout(error))
|
|
615
|
+
if (!isHostTimeout(error)) {
|
|
616
|
+
if (error instanceof DsmCompoundError && error.api === 'SYNO.Core.Package.Installation' && error.method === 'install') {
|
|
617
|
+
const state = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal, ignoreOperation: true });
|
|
618
|
+
const recovered = await recoverProfile(state);
|
|
619
|
+
if (recovered) {
|
|
620
|
+
verified = true;
|
|
621
|
+
return recovered;
|
|
622
|
+
}
|
|
623
|
+
throw recoveryError(error, state);
|
|
624
|
+
}
|
|
535
625
|
throw error;
|
|
626
|
+
}
|
|
536
627
|
timedOut = true;
|
|
537
628
|
progress(`${options.packageId}: install/upgrade request timed out; DSM may still be installing/starting; checking state…`);
|
|
538
629
|
}
|
|
539
|
-
const
|
|
630
|
+
const waitForCompletion = () => waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget), { signal, ignoreOperation: true }), { packageId: options.packageId, expectedVersion: options.version,
|
|
540
631
|
deadlineMs: Number.isFinite(deadline) ? remaining(Number.MAX_SAFE_INTEGER) : undefined, pollMs, requireRunning: true, consumePoll, signal,
|
|
541
632
|
// A lost same-version reinstall reply must not accept the old running instance.
|
|
542
633
|
requireTransition: timedOut && !packageIsBroken(before) && before.installed === true && before.version === options.version,
|
|
543
634
|
repairing: options.repair && packageIsBroken(before),
|
|
544
635
|
onProgress: progress });
|
|
636
|
+
let completed;
|
|
637
|
+
try {
|
|
638
|
+
completed = await waitForCompletion();
|
|
639
|
+
}
|
|
640
|
+
catch (error) {
|
|
641
|
+
if (!(error instanceof CtlError) || error.code !== 'DSM_INSTALL_FAILED' || timedOut || !options.composeProject)
|
|
642
|
+
throw error;
|
|
643
|
+
const failed = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal, ignoreOperation: true });
|
|
644
|
+
const recovered = await recoverProfile(failed);
|
|
645
|
+
if (!recovered)
|
|
646
|
+
throw recoveryError(error, failed);
|
|
647
|
+
completed = recovered;
|
|
648
|
+
}
|
|
545
649
|
verified = true;
|
|
546
650
|
progress(`${options.packageId}: ${phase} complete (${completed.version}, DSM status ${completed.status})`);
|
|
547
651
|
return completed;
|
|
@@ -552,11 +656,14 @@ export async function installPackageFromLocalSpk(options) {
|
|
|
552
656
|
if (isHostTimeout(error)) {
|
|
553
657
|
if (Date.now() >= deadline)
|
|
554
658
|
throw installBudgetExpired(options);
|
|
659
|
+
if (phase !== 'uploading')
|
|
660
|
+
throw new CtlError('HOST_TIMEOUT', `Package request timed out while ${phase}; DSM state is unconfirmed`, 'Inspect DSM before retrying; no write was replayed');
|
|
555
661
|
throw new CtlError('HOST_TIMEOUT', 'SPK upload request timed out; no install request was sent', 'Check the NAS connection and DSM_OPERATION_TIMEOUT_SECONDS before retrying');
|
|
556
662
|
}
|
|
557
663
|
throw error;
|
|
558
664
|
}
|
|
559
665
|
finally {
|
|
666
|
+
await composeAdmin?.close();
|
|
560
667
|
process.removeListener('SIGINT', cancel);
|
|
561
668
|
process.removeListener('SIGTERM', cancel);
|
|
562
669
|
if (operation) {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { pinnedGoBuildEnv } from '../build-spk/go-toolchain.js';
|
|
5
|
+
/** Build the CLI-owned adapter from its locked Go module, never App sources. */
|
|
6
|
+
export function buildComposeAdminHelper(arch, output) {
|
|
7
|
+
if (arch !== 'x86_64' && arch !== 'aarch64')
|
|
8
|
+
throw new Error('Compose administrator helper supports x86_64 or aarch64');
|
|
9
|
+
const path = resolve(output);
|
|
10
|
+
const result = spawnSync('go', ['build', '-mod=readonly', '-trimpath', '-buildvcs=false', '-ldflags=-s -w', '-o', path, '.'], {
|
|
11
|
+
cwd: fileURLToPath(new URL('../../assets/go/compose-admin', import.meta.url)),
|
|
12
|
+
env: { ...process.env, ...pinnedGoBuildEnv(arch) }, encoding: 'utf8', timeout: 120_000
|
|
13
|
+
});
|
|
14
|
+
if (result.status !== 0)
|
|
15
|
+
throw new Error('COMPOSE_ADMIN_BUILD_FAILED: ' + (result.stderr || result.error?.message || 'go build failed'));
|
|
16
|
+
return { sdk: '0.53.11', path, arch };
|
|
17
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export declare const COMPOSE_ADMIN_GUIDANCE = "Configure SYNOPKGLAND_COMPOSE_ADMIN_COMMAND as a JSON argv array for the CLI native helper on this NAS (see docs/compose-admin.md).";
|
|
2
|
+
/** An absent/empty command keeps normal DSM lifecycle behavior. A configured
|
|
3
|
+
* command, including an invalid one, must pass the strict adapter checks. */
|
|
4
|
+
export declare const composeAdminConfigured: (command?: string | undefined) => boolean;
|
|
5
|
+
export declare const composeAdminWarning: (pkg: string) => string;
|
|
6
|
+
export interface ComposeAdminSession {
|
|
7
|
+
remove(): Promise<void>;
|
|
8
|
+
refresh(): Promise<boolean>;
|
|
9
|
+
close(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/** Explicit trusted root channel; never run an App-supplied executable. The
|
|
12
|
+
* configured command receives the origin and package, but no DSM credentials. */
|
|
13
|
+
export declare function openComposeAdmin(options: {
|
|
14
|
+
packageId: string;
|
|
15
|
+
origin: string;
|
|
16
|
+
project?: string;
|
|
17
|
+
command?: string;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}): Promise<ComposeAdminSession>;
|
|
20
|
+
/** Excludes CLI races for every package operation. The NAS helper additionally
|
|
21
|
+
* holds its flock across installed inventory capture, stop, reconcile and write. */
|
|
22
|
+
export declare function withComposeLifecycleLock<T>(origin: string, pkg: string, work: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { CtlError } from '../ctl/errors.js';
|
|
8
|
+
import { dsmOperationTimeoutMs } from '../nas/timeouts.js';
|
|
9
|
+
export const COMPOSE_ADMIN_GUIDANCE = 'Configure SYNOPKGLAND_COMPOSE_ADMIN_COMMAND as a JSON argv array for the CLI native helper on this NAS (see docs/compose-admin.md).';
|
|
10
|
+
const failure = (code) => new CtlError(code, code, COMPOSE_ADMIN_GUIDANCE);
|
|
11
|
+
/** An absent/empty command keeps normal DSM lifecycle behavior. A configured
|
|
12
|
+
* command, including an invalid one, must pass the strict adapter checks. */
|
|
13
|
+
export const composeAdminConfigured = (command = process.env.SYNOPKGLAND_COMPOSE_ADMIN_COMMAND) => Boolean(command);
|
|
14
|
+
export const composeAdminWarning = (pkg) => `Warning: ${pkg}: continuing the standard DSM lifecycle without verified container/profile cleanup; stale Container Manager profiles may remain. ${COMPOSE_ADMIN_GUIDANCE}`;
|
|
15
|
+
/** Explicit trusted root channel; never run an App-supplied executable. The
|
|
16
|
+
* configured command receives the origin and package, but no DSM credentials. */
|
|
17
|
+
export async function openComposeAdmin(options) {
|
|
18
|
+
const configured = options.command ?? process.env.SYNOPKGLAND_COMPOSE_ADMIN_COMMAND;
|
|
19
|
+
if (!configured)
|
|
20
|
+
throw failure('COMPOSE_ADMIN_REQUIRED');
|
|
21
|
+
let argv;
|
|
22
|
+
try {
|
|
23
|
+
argv = JSON.parse(configured);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw failure('COMPOSE_ADMIN_REQUIRED');
|
|
27
|
+
}
|
|
28
|
+
if (!Array.isArray(argv) || !argv.length || argv.some(v => typeof v !== 'string' || !v || /[\r\n\0]/.test(v)))
|
|
29
|
+
throw failure('COMPOSE_ADMIN_REQUIRED');
|
|
30
|
+
const child = spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
|
|
31
|
+
// Never print administrator output, which may include private diagnostics.
|
|
32
|
+
child.stderr.resume();
|
|
33
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
34
|
+
let pending;
|
|
35
|
+
let closed = false;
|
|
36
|
+
const fail = () => { closed = true; pending?.reject(failure('COMPOSE_ADMIN_UNCONFIRMED')); pending = undefined; };
|
|
37
|
+
child.on('error', fail);
|
|
38
|
+
child.on('exit', fail);
|
|
39
|
+
child.stdin.on('error', fail);
|
|
40
|
+
lines.on('line', line => {
|
|
41
|
+
if (!pending || line.length > 1 << 20) {
|
|
42
|
+
fail();
|
|
43
|
+
child.kill();
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const p = pending;
|
|
47
|
+
pending = undefined;
|
|
48
|
+
try {
|
|
49
|
+
const value = JSON.parse(line);
|
|
50
|
+
if (value.ok !== true) {
|
|
51
|
+
const code = typeof value.error === 'string' ? /\b(COMPOSE_[A-Z_]+|PACKAGE_BUSY)\b/.exec(value.error)?.[1] : undefined;
|
|
52
|
+
p.reject(failure(code ?? 'COMPOSE_ADMIN_UNCONFIRMED'));
|
|
53
|
+
}
|
|
54
|
+
else
|
|
55
|
+
p.resolve(value.data);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
p.reject(failure('COMPOSE_ADMIN_UNCONFIRMED'));
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
const abort = () => { fail(); child.kill(); };
|
|
62
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
63
|
+
const call = async (action) => {
|
|
64
|
+
if (closed || pending || options.signal?.aborted)
|
|
65
|
+
throw failure('COMPOSE_ADMIN_UNCONFIRMED');
|
|
66
|
+
let timer;
|
|
67
|
+
try {
|
|
68
|
+
return await new Promise((resolve, reject) => {
|
|
69
|
+
pending = { resolve, reject };
|
|
70
|
+
timer = setTimeout(abort, dsmOperationTimeoutMs());
|
|
71
|
+
child.stdin.write(JSON.stringify({ action, package: options.packageId, project: options.project ?? '', origin: new URL(options.origin).origin }) + '\n');
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
if (timer)
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
const dispose = () => { options.signal?.removeEventListener('abort', abort); lines.close(); child.stdin.end(); child.kill(); };
|
|
80
|
+
try {
|
|
81
|
+
const opened = await call('open');
|
|
82
|
+
if (opened?.compose !== true || opened?.sdk !== '0.53.11')
|
|
83
|
+
throw failure('COMPOSE_ADMIN_UNCONFIRMED');
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
dispose();
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
return { remove: async () => { await call('remove'); }, refresh: async () => { const value = await call('refresh'); if (typeof value?.changed !== 'boolean')
|
|
90
|
+
throw failure('COMPOSE_ADMIN_UNCONFIRMED'); return value.changed; }, close: async () => { try {
|
|
91
|
+
if (!closed)
|
|
92
|
+
await call('close');
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
dispose();
|
|
96
|
+
} } };
|
|
97
|
+
}
|
|
98
|
+
/** Excludes CLI races for every package operation. The NAS helper additionally
|
|
99
|
+
* holds its flock across installed inventory capture, stop, reconcile and write. */
|
|
100
|
+
export async function withComposeLifecycleLock(origin, pkg, work) {
|
|
101
|
+
const root = process.env.SYNOPKGLAND_OPERATIONS_DIR ?? join(homedir(), '.cache/synopkgland/operations');
|
|
102
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
103
|
+
const key = createHash('sha256').update(new URL(origin).origin + '\0' + pkg).digest('hex');
|
|
104
|
+
const path = join(root, key + '.lock');
|
|
105
|
+
try {
|
|
106
|
+
mkdirSync(path, { mode: 0o700 });
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
throw failure('PACKAGE_BUSY');
|
|
110
|
+
}
|
|
111
|
+
// Deliberately do not steal stale locks automatically after uncertain writes.
|
|
112
|
+
writeFileSync(join(path, 'owner.json'), JSON.stringify({ pid: process.pid, package: pkg }), { mode: 0o600 });
|
|
113
|
+
try {
|
|
114
|
+
return await work();
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
rmSync(path, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -6,6 +6,8 @@ interface RecoveryOptions {
|
|
|
6
6
|
projectName: string;
|
|
7
7
|
/** Healthy upgrades retain the worker's existing registration. */
|
|
8
8
|
reclaim: boolean;
|
|
9
|
+
/** A fresh install has no trusted prior installed-container inventory. */
|
|
10
|
+
requireAbsent?: boolean;
|
|
9
11
|
signal?: AbortSignal;
|
|
10
12
|
onProgress?: (message: string) => void;
|
|
11
13
|
}
|
|
@@ -36,6 +36,8 @@ export async function reclaimOwnedComposeProject(options) {
|
|
|
36
36
|
return;
|
|
37
37
|
if (found.length !== 1 || !owned(found[0]))
|
|
38
38
|
throw fail('COMPOSE_PROJECT_CONFLICT', `Container Manager project ${projectName} cannot be proved to belong to ${packageId}; it was left untouched`);
|
|
39
|
+
if (options.requireAbsent)
|
|
40
|
+
throw fail('COMPOSE_PROJECT_INVENTORY_REQUIRED', 'An existing Compose registration needs trusted installed inventory before cleanup; no install request was sent');
|
|
39
41
|
if (!options.reclaim)
|
|
40
42
|
return;
|
|
41
43
|
const project = found[0];
|