Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4a76e520e7 | |||
| d9e1fc17f8 | |||
| 3b179075a8 | |||
| a3327cdd98 | |||
| 432a5c2264 | |||
| f36d20b8dd | |||
| baba892353 | |||
| d2c1bed82c |
@@ -3,6 +3,33 @@
|
||||
## Pending
|
||||
|
||||
|
||||
## 2026-05-25 - 2.1.2
|
||||
|
||||
### Fixes
|
||||
|
||||
- keep self-upgrades alive after stopping the service (upgrade)
|
||||
- Launch dashboard-triggered upgrades as transient systemd units outside the service cgroup.
|
||||
- Download and validate installer binaries before stopping the running service.
|
||||
- Restart the previous service if installation fails after it was stopped.
|
||||
|
||||
## 2026-05-25 - 2.1.1
|
||||
|
||||
### Fixes
|
||||
|
||||
- disable dees-catalog build scripts in workspace config (pnpm-workspace)
|
||||
- Adds @design.estate/dees-catalog to pnpm allowBuilds with a false value to explicitly prevent its build scripts from running.
|
||||
|
||||
## 2026-05-25 - 2.1.0
|
||||
|
||||
### Features
|
||||
|
||||
- add App Store upgrade progress tracking and interactive workspace processes (appstore,workspace)
|
||||
- Track App Store upgrade operations with async start/list requests and streamed progress updates.
|
||||
- Show running and failed upgrade status in App Store and service detail views while preventing duplicate upgrade actions.
|
||||
- Route App Store upgrades through the shared service update flow to restore service routes before gateway sync.
|
||||
- Add backend workspace shell discovery plus interactive process start/input/kill/output/exit APIs backed by Docker exec streams.
|
||||
- Bump Docker and workspace UI dependencies for interactive stdin streaming and shell selection support.
|
||||
|
||||
## 2026-05-25 - 2.0.0
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@serve.zone/onebox",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.2",
|
||||
"exports": "./mod.ts",
|
||||
"tasks": {
|
||||
"test": "deno test --allow-all test/",
|
||||
@@ -15,7 +15,7 @@
|
||||
"@std/assert": "jsr:@std/assert@^1.0.19",
|
||||
"@std/encoding": "jsr:@std/encoding@^1.0.10",
|
||||
"@db/sqlite": "jsr:@db/sqlite@0.13.0",
|
||||
"@apiclient.xyz/docker": "npm:@apiclient.xyz/docker@^5.1.4",
|
||||
"@apiclient.xyz/docker": "npm:@apiclient.xyz/docker@^5.1.5",
|
||||
"@apiclient.xyz/cloudflare": "npm:@apiclient.xyz/cloudflare@7.1.0",
|
||||
"@push.rocks/smartacme": "npm:@push.rocks/smartacme@^9.5.0",
|
||||
"@push.rocks/smartregistry": "npm:@push.rocks/smartregistry@^2.9.2",
|
||||
|
||||
+50
-40
@@ -170,14 +170,55 @@ DOWNLOAD_URL="${GITEA_BASE_URL}/${GITEA_REPO}/releases/download/${VERSION}/${BIN
|
||||
echo "Download URL: $DOWNLOAD_URL"
|
||||
echo ""
|
||||
|
||||
# Check if service is running and stop it
|
||||
# Check whether the service should be restarted after a successful install.
|
||||
SERVICE_WAS_RUNNING=0
|
||||
if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null || systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
||||
SERVICE_WAS_RUNNING=1
|
||||
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
||||
fi
|
||||
|
||||
# Download and validate the new binary before touching the running service.
|
||||
echo "Downloading Onebox binary..."
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
TEMP_FILE="$TEMP_DIR/$BINARY_NAME"
|
||||
cleanup_temp() {
|
||||
rm -rf "$TEMP_DIR"
|
||||
}
|
||||
trap cleanup_temp EXIT
|
||||
|
||||
if ! curl -fSL "$DOWNLOAD_URL" -o "$TEMP_FILE"; then
|
||||
echo "Error: Failed to download binary from $DOWNLOAD_URL"
|
||||
echo ""
|
||||
echo "Please check:"
|
||||
echo " 1. Your internet connection"
|
||||
echo " 2. The specified version exists: ${GITEA_BASE_URL}/${GITEA_REPO}/releases"
|
||||
echo " 3. The platform binary is available for this release"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -s "$TEMP_FILE" ]; then
|
||||
echo "Error: Downloaded file is empty or does not exist"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "$TEMP_FILE"
|
||||
if ! "$TEMP_FILE" --version >/dev/null 2>&1; then
|
||||
echo "Error: Downloaded file is not an executable Onebox binary"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SERVICE_STOPPED=0
|
||||
restart_previous_service_on_error() {
|
||||
if [ $SERVICE_STOPPED -eq 1 ]; then
|
||||
echo "Installation failed after stopping Onebox; restarting previous service..."
|
||||
systemctl start "$SERVICE_NAME" || true
|
||||
fi
|
||||
}
|
||||
trap 'restart_previous_service_on_error; cleanup_temp' ERR
|
||||
|
||||
if [ $SERVICE_WAS_RUNNING -eq 1 ] && systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
||||
echo "Stopping Onebox service..."
|
||||
systemctl stop "$SERVICE_NAME"
|
||||
fi
|
||||
SERVICE_STOPPED=1
|
||||
fi
|
||||
|
||||
# Clean installation directory - ensure only binary exists
|
||||
@@ -190,44 +231,10 @@ fi
|
||||
echo "Creating installation directory: $INSTALL_DIR"
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
|
||||
# Download binary
|
||||
echo "Downloading Onebox binary..."
|
||||
TEMP_FILE="$INSTALL_DIR/onebox.download"
|
||||
curl -sSL "$DOWNLOAD_URL" -o "$TEMP_FILE"
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Error: Failed to download binary from $DOWNLOAD_URL"
|
||||
echo ""
|
||||
echo "Please check:"
|
||||
echo " 1. Your internet connection"
|
||||
echo " 2. The specified version exists: ${GITEA_BASE_URL}/${GITEA_REPO}/releases"
|
||||
echo " 3. The platform binary is available for this release"
|
||||
rm -f "$TEMP_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if download was successful (file exists and not empty)
|
||||
if [ ! -s "$TEMP_FILE" ]; then
|
||||
echo "Error: Downloaded file is empty or does not exist"
|
||||
rm -f "$TEMP_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Move to final location
|
||||
# Install binary
|
||||
BINARY_PATH="$INSTALL_DIR/onebox"
|
||||
mv "$TEMP_FILE" "$BINARY_PATH"
|
||||
|
||||
if [ $? -ne 0 ] || [ ! -f "$BINARY_PATH" ]; then
|
||||
echo "Error: Failed to move binary to $BINARY_PATH"
|
||||
rm -f "$TEMP_FILE" 2>/dev/null
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Make executable
|
||||
chmod +x "$BINARY_PATH"
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Error: Failed to make binary executable"
|
||||
if ! install -m 0755 "$TEMP_FILE" "$BINARY_PATH" || [ ! -f "$BINARY_PATH" ]; then
|
||||
echo "Error: Failed to install binary to $BINARY_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -256,10 +263,13 @@ if [ $SERVICE_WAS_RUNNING -eq 1 ]; then
|
||||
onebox systemd enable
|
||||
echo "Restarting Onebox service..."
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
SERVICE_STOPPED=0
|
||||
echo "Service restarted successfully."
|
||||
echo ""
|
||||
fi
|
||||
|
||||
trap - ERR
|
||||
|
||||
echo "================================================"
|
||||
echo " Onebox Installation Complete!"
|
||||
echo "================================================"
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@serve.zone/onebox",
|
||||
"version": "2.0.0",
|
||||
"version": "2.1.2",
|
||||
"description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers",
|
||||
"main": "mod.ts",
|
||||
"type": "module",
|
||||
@@ -56,7 +56,7 @@
|
||||
"dependencies": {
|
||||
"@api.global/typedrequest-interfaces": "^3.0.19",
|
||||
"@api.global/typedsocket": "^4.1.3",
|
||||
"@design.estate/dees-catalog": "^3.81.0",
|
||||
"@design.estate/dees-catalog": "^3.82.0",
|
||||
"@design.estate/dees-element": "^2.2.4",
|
||||
"@serve.zone/appstore": "^0.2.0",
|
||||
"@serve.zone/catalog": "^2.12.6",
|
||||
|
||||
Generated
+42
-3
@@ -15,8 +15,8 @@ importers:
|
||||
specifier: ^4.1.3
|
||||
version: 4.1.3(@push.rocks/smartserve@2.0.4)
|
||||
'@design.estate/dees-catalog':
|
||||
specifier: ^3.81.0
|
||||
version: 3.81.0(@tiptap/pm@2.27.2)
|
||||
specifier: ^3.82.0
|
||||
version: 3.82.0(@tiptap/pm@2.27.2)
|
||||
'@design.estate/dees-element':
|
||||
specifier: ^2.2.4
|
||||
version: 2.2.4
|
||||
@@ -81,6 +81,9 @@ packages:
|
||||
'@design.estate/dees-catalog@3.81.0':
|
||||
resolution: {integrity: sha512-N7ocwSKVdjDQWmVV2XWiyg3dotGEuxP4/jhyB6duH8zJ3k63wmGm8+FeoP+LzRc8/U0Bl8w7UZrewlkIEMstUA==}
|
||||
|
||||
'@design.estate/dees-catalog@3.82.0':
|
||||
resolution: {integrity: sha512-OvPglDHI8J8K8+hmtxHyvVLzKMr8rQSFXVxf6xT60q/om3QoQacwS8cPI/RmnEKT+mzvDk/vnNpt9/Tw0cTmWA==}
|
||||
|
||||
'@design.estate/dees-comms@1.0.30':
|
||||
resolution: {integrity: sha512-KchMlklJfKAjQiJiR0xmofXtQ27VgZtBIxcMwPE9d+h3jJRv+lPZxzBQVOM0eyM0uS44S5vJMZ11IeV4uDXSHg==}
|
||||
|
||||
@@ -2546,6 +2549,42 @@ snapshots:
|
||||
- supports-color
|
||||
- vue
|
||||
|
||||
'@design.estate/dees-catalog@3.82.0(@tiptap/pm@2.27.2)':
|
||||
dependencies:
|
||||
'@design.estate/dees-domtools': 2.5.6
|
||||
'@design.estate/dees-element': 2.2.4
|
||||
'@design.estate/dees-wcctools': 3.9.0
|
||||
'@fortawesome/fontawesome-svg-core': 7.2.0
|
||||
'@fortawesome/free-brands-svg-icons': 7.2.0
|
||||
'@fortawesome/free-regular-svg-icons': 7.2.0
|
||||
'@fortawesome/free-solid-svg-icons': 7.2.0
|
||||
'@push.rocks/smarti18n': 1.1.0
|
||||
'@push.rocks/smartpromise': 4.2.4
|
||||
'@push.rocks/smartstring': 4.1.1
|
||||
'@tempfix/webcontainer__api': 1.6.1
|
||||
'@tiptap/core': 2.27.2(@tiptap/pm@2.27.2)
|
||||
'@tiptap/extension-link': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))(@tiptap/pm@2.27.2)
|
||||
'@tiptap/extension-text-align': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
|
||||
'@tiptap/extension-typography': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
|
||||
'@tiptap/extension-underline': 2.27.2(@tiptap/core@2.27.2(@tiptap/pm@2.27.2))
|
||||
'@tiptap/starter-kit': 2.27.2
|
||||
'@tsclass/tsclass': 9.5.1
|
||||
echarts: 5.6.0
|
||||
highlight.js: 11.11.1
|
||||
ibantools: 4.5.4
|
||||
lightweight-charts: 5.2.0
|
||||
lucide: 1.14.0
|
||||
monaco-editor: 0.55.1
|
||||
pdfjs-dist: 4.10.38
|
||||
xterm: 5.3.0
|
||||
xterm-addon-fit: 0.8.0(xterm@5.3.0)
|
||||
transitivePeerDependencies:
|
||||
- '@nuxt/kit'
|
||||
- '@tiptap/pm'
|
||||
- react
|
||||
- supports-color
|
||||
- vue
|
||||
|
||||
'@design.estate/dees-comms@1.0.30':
|
||||
dependencies:
|
||||
'@api.global/typedrequest': 3.3.0
|
||||
@@ -2555,7 +2594,7 @@ snapshots:
|
||||
|
||||
'@design.estate/dees-domtools@2.5.6':
|
||||
dependencies:
|
||||
'@api.global/typedrequest': 3.3.0
|
||||
'@api.global/typedrequest': 3.3.1
|
||||
'@design.estate/dees-comms': 1.0.30
|
||||
'@push.rocks/lik': 6.4.1
|
||||
'@push.rocks/smartdelay': 3.1.0
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
allowBuilds:
|
||||
'@design.estate/dees-catalog': false
|
||||
esbuild: true
|
||||
ignoredBuiltDependencies:
|
||||
- '@design.estate/dees-catalog'
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/onebox',
|
||||
version: '2.0.0',
|
||||
version: '2.1.2',
|
||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||
}
|
||||
|
||||
+15
-25
@@ -47,6 +47,10 @@ export interface IMigrationResult {
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface IAppStoreUpgradeApplyOptions {
|
||||
onProgress?: (progressArg: { step: string; message: string }) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export class AppStoreManager {
|
||||
private appStoreCache: IAppStoreIndex | null = null;
|
||||
private appStoreResolver: plugins.servezoneAppstore.AppStoreResolver;
|
||||
@@ -297,16 +301,13 @@ export class AppStoreManager {
|
||||
serviceNameArg: string,
|
||||
migrationResultArg: IMigrationResult,
|
||||
newVersionArg: string,
|
||||
optionsArg: IAppStoreUpgradeApplyOptions = {},
|
||||
): Promise<IService> {
|
||||
const service = this.oneboxRef.database.getServiceByName(serviceNameArg);
|
||||
if (!service) {
|
||||
throw new Error(`Service not found: ${serviceNameArg}`);
|
||||
}
|
||||
|
||||
if (service.containerID && service.status === 'running') {
|
||||
await this.oneboxRef.services.stopService(serviceNameArg);
|
||||
}
|
||||
|
||||
const updates: Partial<IService> = {
|
||||
appTemplateVersion: newVersionArg,
|
||||
};
|
||||
@@ -336,29 +337,18 @@ export class AppStoreManager {
|
||||
updates.envVars = mergedEnvVars;
|
||||
}
|
||||
|
||||
this.oneboxRef.database.updateService(service.id!, updates);
|
||||
|
||||
const newImage = migrationResultArg.image || service.image;
|
||||
if (migrationResultArg.image && migrationResultArg.image !== service.image) {
|
||||
await this.oneboxRef.docker.pullImage(newImage);
|
||||
}
|
||||
|
||||
const updatedService = this.oneboxRef.database.getServiceByName(serviceNameArg)!;
|
||||
if (service.containerID) {
|
||||
try {
|
||||
await this.oneboxRef.docker.removeContainer(service.containerID, true);
|
||||
} catch {
|
||||
// Container might already be gone.
|
||||
}
|
||||
}
|
||||
|
||||
const containerID = await this.oneboxRef.docker.createContainer(updatedService);
|
||||
this.oneboxRef.database.updateService(service.id!, { containerID, status: 'starting' });
|
||||
await this.oneboxRef.docker.startContainer(containerID);
|
||||
this.oneboxRef.database.updateService(service.id!, { status: 'running' });
|
||||
const updatedService = await this.oneboxRef.services.updateService(
|
||||
serviceNameArg,
|
||||
updates,
|
||||
{
|
||||
onProgress: async (progressArg) => {
|
||||
await optionsArg.onProgress?.(progressArg);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
logger.success(`Service '${serviceNameArg}' upgraded to App Store version ${newVersionArg}`);
|
||||
return this.oneboxRef.database.getServiceByName(serviceNameArg)!;
|
||||
return updatedService;
|
||||
}
|
||||
|
||||
public normalizeVolumes(volumesArg: IAppStoreVersionConfig['volumes'] = []): IServiceVolume[] {
|
||||
|
||||
+31
-7
@@ -14,6 +14,12 @@ type TExpandedPublishedPort = Required<Pick<
|
||||
'targetPort' | 'publishedPort' | 'protocol' | 'hostIp'
|
||||
>>;
|
||||
|
||||
export interface IInteractiveContainerExec {
|
||||
stream: plugins.nodeStream.Duplex;
|
||||
close: () => Promise<void>;
|
||||
inspect: () => Promise<{ ExitCode?: number | null; Running?: boolean }>;
|
||||
}
|
||||
|
||||
export class OneboxDockerManager {
|
||||
private dockerClient: InstanceType<typeof plugins.docker.Docker> | null = null;
|
||||
private networkName = 'onebox-network';
|
||||
@@ -1128,16 +1134,12 @@ export class OneboxDockerManager {
|
||||
/**
|
||||
* Execute a command in a running container
|
||||
*/
|
||||
async execInContainer(
|
||||
containerID: string,
|
||||
cmd: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
try {
|
||||
private async resolveContainer(containerID: string): Promise<any> {
|
||||
let container: any = null;
|
||||
try {
|
||||
container = await this.dockerClient!.getContainerById(containerID);
|
||||
} catch {
|
||||
// Not a direct container ID — try Swarm service lookup
|
||||
// Not a direct container ID — try Swarm service lookup.
|
||||
}
|
||||
|
||||
if (!container) {
|
||||
@@ -1146,7 +1148,7 @@ export class OneboxDockerManager {
|
||||
try {
|
||||
container = await this.dockerClient!.getContainerById(serviceContainerId);
|
||||
} catch {
|
||||
// Service container also not found
|
||||
// Service container also not found.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1154,6 +1156,15 @@ export class OneboxDockerManager {
|
||||
if (!container) {
|
||||
throw new Error(`Container not found: ${containerID}`);
|
||||
}
|
||||
return container;
|
||||
}
|
||||
|
||||
async execInContainer(
|
||||
containerID: string,
|
||||
cmd: string[]
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
try {
|
||||
const container = await this.resolveContainer(containerID);
|
||||
|
||||
const { stream, inspect } = await container.exec(cmd, {
|
||||
attachStdout: true,
|
||||
@@ -1190,6 +1201,19 @@ export class OneboxDockerManager {
|
||||
}
|
||||
}
|
||||
|
||||
async startInteractiveExecInContainer(
|
||||
containerID: string,
|
||||
cmd: string[],
|
||||
): Promise<IInteractiveContainerExec> {
|
||||
const container = await this.resolveContainer(containerID);
|
||||
return await container.exec(cmd, {
|
||||
tty: true,
|
||||
attachStdin: true,
|
||||
attachStdout: true,
|
||||
attachStderr: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a platform service container (MongoDB, MinIO, etc.)
|
||||
* Platform containers are long-running infrastructure services
|
||||
|
||||
+48
-1
@@ -11,6 +11,26 @@ import { OneboxDatabase } from './database.ts';
|
||||
import { OneboxDockerManager } from './docker.ts';
|
||||
import type { PlatformServicesManager } from './platform-services/index.ts';
|
||||
|
||||
export type TServiceUpdateProgressStep =
|
||||
| 'stopping'
|
||||
| 'pulling-image'
|
||||
| 'updating-record'
|
||||
| 'removing-container'
|
||||
| 'creating-container'
|
||||
| 'starting'
|
||||
| 'restoring-route'
|
||||
| 'syncing-gateway'
|
||||
| 'complete';
|
||||
|
||||
export interface IServiceUpdateProgress {
|
||||
step: TServiceUpdateProgressStep;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface IServiceUpdateOptions {
|
||||
onProgress?: (progressArg: IServiceUpdateProgress) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export class OneboxServicesManager {
|
||||
private oneboxRef: any; // Will be Onebox instance
|
||||
private database: OneboxDatabase;
|
||||
@@ -583,9 +603,15 @@ export class OneboxServicesManager {
|
||||
envVars?: Record<string, string>;
|
||||
volumes?: IService['volumes'];
|
||||
publishedPorts?: IService['publishedPorts'];
|
||||
}
|
||||
imageDigest?: string;
|
||||
appTemplateVersion?: string;
|
||||
},
|
||||
optionsArg: IServiceUpdateOptions = {},
|
||||
): Promise<IService> {
|
||||
try {
|
||||
const emitProgress = async (step: TServiceUpdateProgressStep, message: string) => {
|
||||
await optionsArg.onProgress?.({ step, message });
|
||||
};
|
||||
const service = this.database.getServiceByName(name);
|
||||
if (!service) {
|
||||
throw new Error(`Service not found: ${name}`);
|
||||
@@ -599,6 +625,7 @@ export class OneboxServicesManager {
|
||||
// Stop the container if running
|
||||
if (wasRunning && oldContainerID) {
|
||||
logger.info(`Stopping service ${name} for updates...`);
|
||||
await emitProgress('stopping', `Stopping ${name} before updating its container`);
|
||||
try {
|
||||
await this.docker.stopContainer(oldContainerID);
|
||||
} catch (error) {
|
||||
@@ -609,10 +636,12 @@ export class OneboxServicesManager {
|
||||
// Pull new image if changed
|
||||
if (updates.image && updates.image !== service.image) {
|
||||
logger.info(`Pulling new image: ${updates.image}`);
|
||||
await emitProgress('pulling-image', `Pulling image ${updates.image}`);
|
||||
await this.docker.pullImage(updates.image, updates.registry || service.registry);
|
||||
}
|
||||
|
||||
// Update service in database
|
||||
await emitProgress('updating-record', `Updating service record for ${name}`);
|
||||
const updateData: any = {
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
@@ -623,6 +652,8 @@ export class OneboxServicesManager {
|
||||
if (updates.envVars !== undefined) updateData.envVars = updates.envVars;
|
||||
if (updates.volumes !== undefined) updateData.volumes = updates.volumes;
|
||||
if (updates.publishedPorts !== undefined) updateData.publishedPorts = updates.publishedPorts;
|
||||
if (updates.imageDigest !== undefined) updateData.imageDigest = updates.imageDigest;
|
||||
if (updates.appTemplateVersion !== undefined) updateData.appTemplateVersion = updates.appTemplateVersion;
|
||||
|
||||
this.database.updateService(service.id!, updateData);
|
||||
|
||||
@@ -631,6 +662,7 @@ export class OneboxServicesManager {
|
||||
|
||||
// Remove old container
|
||||
if (oldContainerID) {
|
||||
await emitProgress('removing-container', `Removing old container for ${name}`);
|
||||
try {
|
||||
await this.docker.removeContainer(oldContainerID, true);
|
||||
logger.info(`Removed old container for ${name}`);
|
||||
@@ -641,6 +673,7 @@ export class OneboxServicesManager {
|
||||
|
||||
// Create new container with updated config
|
||||
logger.info(`Creating new container for ${name}...`);
|
||||
await emitProgress('creating-container', `Creating replacement container for ${name}`);
|
||||
const containerID = await this.docker.createContainer(updatedService);
|
||||
this.database.updateService(service.id!, { containerID });
|
||||
|
||||
@@ -674,6 +707,7 @@ export class OneboxServicesManager {
|
||||
// Restart the container if it was running
|
||||
if (wasRunning) {
|
||||
logger.info(`Starting updated service ${name}...`);
|
||||
await emitProgress('starting', `Starting updated service ${name}`);
|
||||
this.database.updateService(service.id!, { status: 'starting' });
|
||||
await this.docker.startContainer(containerID);
|
||||
this.database.updateService(service.id!, { status: 'running' });
|
||||
@@ -685,8 +719,21 @@ export class OneboxServicesManager {
|
||||
|
||||
const refreshedService = this.database.getServiceByName(name)!;
|
||||
if (refreshedService.domain && refreshedService.status === 'running') {
|
||||
await emitProgress('restoring-route', `Restoring route ${refreshedService.domain} -> ${refreshedService.port}`);
|
||||
try {
|
||||
await this.oneboxRef.reverseProxy.addRoute(
|
||||
refreshedService.id!,
|
||||
refreshedService.domain,
|
||||
refreshedService.port,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to restore reverse proxy route for ${refreshedService.domain}: ${getErrorMessage(error)}`);
|
||||
throw error;
|
||||
}
|
||||
await emitProgress('syncing-gateway', `Syncing external gateway route for ${refreshedService.domain}`);
|
||||
await this.syncExternalGatewayRoute(refreshedService);
|
||||
}
|
||||
await emitProgress('complete', `Service ${name} update completed`);
|
||||
await this.broadcastServiceUpdate(name, 'updated');
|
||||
return refreshedService;
|
||||
} catch (error) {
|
||||
|
||||
@@ -66,24 +66,43 @@ export class OneboxUpdateManager {
|
||||
};
|
||||
}
|
||||
|
||||
const command = new Deno.Command('bash', {
|
||||
args: ['-c', this.createDetachedUpgradeScript()],
|
||||
const unitName = `onebox-upgrade-${Date.now()}`;
|
||||
const command = new Deno.Command('systemd-run', {
|
||||
args: [
|
||||
'--unit',
|
||||
unitName,
|
||||
'--description',
|
||||
`Onebox upgrade to ${targetVersion}`,
|
||||
'--collect',
|
||||
'--property=Type=oneshot',
|
||||
'--setenv=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||
'bash',
|
||||
'-lc',
|
||||
this.createDetachedUpgradeScript(),
|
||||
],
|
||||
stdin: 'null',
|
||||
stdout: 'null',
|
||||
stderr: 'null',
|
||||
detached: true,
|
||||
stdout: 'piped',
|
||||
stderr: 'piped',
|
||||
});
|
||||
const child = command.spawn();
|
||||
child.unref();
|
||||
const result = await command.output();
|
||||
if (!result.success) {
|
||||
const stderr = new TextDecoder().decode(result.stderr).trim();
|
||||
const stdout = new TextDecoder().decode(result.stdout).trim();
|
||||
throw new Error(
|
||||
`Failed to start Onebox upgrade systemd unit: ${
|
||||
stderr || stdout || `exit code ${result.code}`
|
||||
}`,
|
||||
);
|
||||
}
|
||||
this.upgradeStartedAt = Date.now();
|
||||
|
||||
logger.info(`Started detached Onebox upgrade process ${child.pid}`);
|
||||
logger.info(`Started Onebox upgrade systemd unit ${unitName}`);
|
||||
return {
|
||||
accepted: true,
|
||||
currentVersion: status.currentVersion,
|
||||
targetVersion,
|
||||
message: 'Onebox upgrade started. The service will restart automatically.',
|
||||
pid: child.pid,
|
||||
unitName,
|
||||
logPath: UPGRADE_LOG_PATH,
|
||||
};
|
||||
}
|
||||
@@ -107,7 +126,7 @@ export class OneboxUpdateManager {
|
||||
}
|
||||
|
||||
const installCommand = new Deno.Command('bash', {
|
||||
args: ['-c', `curl -sSL ${ONEBOX_INSTALL_SCRIPT_URL} | bash`],
|
||||
args: ['-c', `set -o pipefail; curl -fsSL ${ONEBOX_INSTALL_SCRIPT_URL} | bash`],
|
||||
stdin: 'inherit',
|
||||
stdout: 'inherit',
|
||||
stderr: 'inherit',
|
||||
@@ -202,11 +221,12 @@ export class OneboxUpdateManager {
|
||||
private createDetachedUpgradeScript(): string {
|
||||
return `
|
||||
set -e
|
||||
set -o pipefail
|
||||
mkdir -p /var/log
|
||||
{
|
||||
echo "==== Onebox upgrade started $(date -Is) ===="
|
||||
sleep 2
|
||||
curl -sSL ${ONEBOX_INSTALL_SCRIPT_URL} | bash
|
||||
curl -fsSL ${ONEBOX_INSTALL_SCRIPT_URL} | bash
|
||||
echo "==== Onebox upgrade finished $(date -Is) ===="
|
||||
} >> ${UPGRADE_LOG_PATH} 2>&1
|
||||
`;
|
||||
|
||||
@@ -3,15 +3,205 @@ import { logger } from '../../logging.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||
import { getErrorMessage } from '../../utils/error.ts';
|
||||
|
||||
type IAppStoreUpgradeOperation = interfaces.requests.IAppStoreUpgradeOperation;
|
||||
type TAppStoreUpgradeStep = interfaces.requests.TAppStoreUpgradeStep;
|
||||
|
||||
export class AppStoreHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
private upgradeOperations = new Map<string, IAppStoreUpgradeOperation>();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private getUpgradeOperations(): IAppStoreUpgradeOperation[] {
|
||||
return Array.from(this.upgradeOperations.values())
|
||||
.sort((a, b) => b.startedAt - a.startedAt)
|
||||
.slice(0, 25);
|
||||
}
|
||||
|
||||
private getRunningUpgrade(serviceNameArg: string): IAppStoreUpgradeOperation | null {
|
||||
for (const operation of this.upgradeOperations.values()) {
|
||||
if (operation.serviceName === serviceNameArg && operation.status === 'running') {
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async createUpgradeOperation(
|
||||
serviceNameArg: string,
|
||||
targetVersionArg: string,
|
||||
): Promise<IAppStoreUpgradeOperation> {
|
||||
const existingRunning = this.getRunningUpgrade(serviceNameArg);
|
||||
if (existingRunning) {
|
||||
throw new plugins.typedrequest.TypedResponseError(
|
||||
`An upgrade is already running for ${serviceNameArg}`,
|
||||
);
|
||||
}
|
||||
|
||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(serviceNameArg);
|
||||
if (!existingService) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Service not found: ${serviceNameArg}`);
|
||||
}
|
||||
if (!existingService.appTemplateId) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service was not deployed from an app template');
|
||||
}
|
||||
if (!existingService.appTemplateVersion) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service has no tracked template version');
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const operation: IAppStoreUpgradeOperation = {
|
||||
id: crypto.randomUUID(),
|
||||
serviceName: existingService.name,
|
||||
appTemplateId: existingService.appTemplateId,
|
||||
fromVersion: existingService.appTemplateVersion,
|
||||
targetVersion: targetVersionArg,
|
||||
status: 'running',
|
||||
step: 'queued',
|
||||
progressLines: [`Queued upgrade ${existingService.appTemplateVersion} -> ${targetVersionArg}`],
|
||||
warnings: [],
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.upgradeOperations.set(operation.id, operation);
|
||||
await this.pushUpgradeProgress(operation);
|
||||
return operation;
|
||||
}
|
||||
|
||||
private async updateUpgradeOperation(
|
||||
operationIdArg: string,
|
||||
stepArg: TAppStoreUpgradeStep,
|
||||
messageArg: string,
|
||||
updatesArg: Partial<IAppStoreUpgradeOperation> = {},
|
||||
): Promise<IAppStoreUpgradeOperation> {
|
||||
const existing = this.upgradeOperations.get(operationIdArg);
|
||||
if (!existing) {
|
||||
throw new Error(`Upgrade operation not found: ${operationIdArg}`);
|
||||
}
|
||||
|
||||
const nextOperation: IAppStoreUpgradeOperation = {
|
||||
...existing,
|
||||
...updatesArg,
|
||||
step: stepArg,
|
||||
updatedAt: Date.now(),
|
||||
progressLines: [...existing.progressLines, messageArg].slice(-200),
|
||||
};
|
||||
this.upgradeOperations.set(operationIdArg, nextOperation);
|
||||
await this.pushUpgradeProgress(nextOperation);
|
||||
return nextOperation;
|
||||
}
|
||||
|
||||
private async pushUpgradeProgress(operationArg: IAppStoreUpgradeOperation): Promise<void> {
|
||||
await this.opsServerRef.pushDashboardEvent('pushAppStoreUpgradeProgress', {
|
||||
operation: operationArg,
|
||||
});
|
||||
}
|
||||
|
||||
private async performUpgrade(operationIdArg: string): Promise<interfaces.data.IService> {
|
||||
let operation = this.upgradeOperations.get(operationIdArg);
|
||||
if (!operation) {
|
||||
throw new Error(`Upgrade operation not found: ${operationIdArg}`);
|
||||
}
|
||||
|
||||
try {
|
||||
operation = await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'validating',
|
||||
`Validating ${operation.serviceName} for App Store upgrade`,
|
||||
);
|
||||
|
||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(operation.serviceName);
|
||||
if (!existingService) {
|
||||
throw new Error(`Service not found: ${operation.serviceName}`);
|
||||
}
|
||||
if (!existingService.appTemplateId || !existingService.appTemplateVersion) {
|
||||
throw new Error('Service is missing App Store template metadata');
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Upgrading service '${operation.serviceName}' from v${operation.fromVersion} to v${operation.targetVersion}`,
|
||||
);
|
||||
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'migration',
|
||||
`Resolving migration for ${operation.appTemplateId} ${operation.fromVersion} -> ${operation.targetVersion}`,
|
||||
);
|
||||
|
||||
const migrationResult = await this.opsServerRef.oneboxRef.appStore.executeMigration(
|
||||
existingService,
|
||||
operation.fromVersion,
|
||||
operation.targetVersion,
|
||||
);
|
||||
|
||||
if (!migrationResult.success) {
|
||||
throw new Error(`Migration failed: ${migrationResult.warnings.join('; ')}`);
|
||||
}
|
||||
|
||||
if (migrationResult.warnings.length > 0) {
|
||||
operation = await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'migration',
|
||||
`Migration completed with ${migrationResult.warnings.length} warning(s)`,
|
||||
{ warnings: migrationResult.warnings },
|
||||
);
|
||||
}
|
||||
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'applying',
|
||||
`Applying upgrade to ${operation.serviceName}`,
|
||||
);
|
||||
|
||||
const updatedService = await this.opsServerRef.oneboxRef.appStore.applyUpgrade(
|
||||
operation.serviceName,
|
||||
migrationResult,
|
||||
operation.targetVersion,
|
||||
{
|
||||
onProgress: async (progressArg) => {
|
||||
await this.updateUpgradeOperation(
|
||||
operation!.id,
|
||||
progressArg.step as TAppStoreUpgradeStep,
|
||||
progressArg.message,
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'complete',
|
||||
`Upgrade completed for ${operation.serviceName}`,
|
||||
{
|
||||
status: 'success',
|
||||
completedAt: Date.now(),
|
||||
service: updatedService,
|
||||
warnings: migrationResult.warnings,
|
||||
},
|
||||
);
|
||||
|
||||
return updatedService;
|
||||
} catch (error) {
|
||||
await this.updateUpgradeOperation(
|
||||
operation.id,
|
||||
'failed',
|
||||
`Upgrade failed: ${getErrorMessage(error)}`,
|
||||
{
|
||||
status: 'failed',
|
||||
completedAt: Date.now(),
|
||||
error: getErrorMessage(error),
|
||||
},
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreTemplates>(
|
||||
@@ -66,44 +256,38 @@ export class AppStoreHandler {
|
||||
'upgradeAppStoreService',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
|
||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(dataArg.serviceName);
|
||||
if (!existingService) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Service not found: ${dataArg.serviceName}`);
|
||||
}
|
||||
if (!existingService.appTemplateId) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service was not deployed from an app template');
|
||||
}
|
||||
if (!existingService.appTemplateVersion) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Service has no tracked template version');
|
||||
}
|
||||
|
||||
logger.info(`Upgrading service '${dataArg.serviceName}' from v${existingService.appTemplateVersion} to v${dataArg.targetVersion}`);
|
||||
|
||||
const migrationResult = await this.opsServerRef.oneboxRef.appStore.executeMigration(
|
||||
existingService,
|
||||
existingService.appTemplateVersion,
|
||||
dataArg.targetVersion,
|
||||
);
|
||||
|
||||
if (!migrationResult.success) {
|
||||
throw new plugins.typedrequest.TypedResponseError(
|
||||
`Migration failed: ${migrationResult.warnings.join('; ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
const updatedService = await this.opsServerRef.oneboxRef.appStore.applyUpgrade(
|
||||
dataArg.serviceName,
|
||||
migrationResult,
|
||||
dataArg.targetVersion,
|
||||
);
|
||||
const operation = await this.createUpgradeOperation(dataArg.serviceName, dataArg.targetVersion);
|
||||
const updatedService = await this.performUpgrade(operation.id);
|
||||
const completedOperation = this.upgradeOperations.get(operation.id)!;
|
||||
|
||||
return {
|
||||
service: updatedService,
|
||||
warnings: migrationResult.warnings,
|
||||
warnings: completedOperation.warnings,
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartAppStoreServiceUpgrade>(
|
||||
'startAppStoreServiceUpgrade',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const operation = await this.createUpgradeOperation(dataArg.serviceName, dataArg.targetVersion);
|
||||
void this.performUpgrade(operation.id).catch(() => {});
|
||||
return { operation };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreUpgradeOperations>(
|
||||
'getAppStoreUpgradeOperations',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
return { operations: this.getUpgradeOperations() };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,21 @@ import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||
import { getErrorMessage } from '../../utils/error.ts';
|
||||
|
||||
interface IWorkspaceProcessSession {
|
||||
processId: string;
|
||||
serviceName: string;
|
||||
userId: string;
|
||||
stream: plugins.nodeStream.Duplex;
|
||||
close: () => Promise<void>;
|
||||
inspect: () => Promise<{ ExitCode?: number | null; Running?: boolean }>;
|
||||
finalized: boolean;
|
||||
}
|
||||
|
||||
const getWorkspaceProcessTag = (processIdArg: string) => `workspaceProcess:${processIdArg}`;
|
||||
|
||||
export class WorkspaceHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
private workspaceProcesses = new Map<string, IWorkspaceProcessSession>();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
@@ -24,6 +37,111 @@ export class WorkspaceHandler {
|
||||
return service.containerID;
|
||||
}
|
||||
|
||||
private validateProcessId(processIdArg: string): void {
|
||||
if (!/^[a-zA-Z0-9_-]{8,80}$/.test(processIdArg)) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Invalid workspace process id');
|
||||
}
|
||||
}
|
||||
|
||||
private async getShellCommandForContainer(
|
||||
containerIdArg: string,
|
||||
): Promise<interfaces.requests.IWorkspaceShellCommand> {
|
||||
const candidates: interfaces.requests.IWorkspaceShellCommand[] = [
|
||||
{ command: '/bin/bash', args: ['-il'], label: 'bash', prompt: '# ' },
|
||||
{ command: 'bash', args: ['-il'], label: 'bash', prompt: '# ' },
|
||||
{ command: '/bin/sh', args: ['-i'], label: 'sh', prompt: '# ' },
|
||||
{ command: 'sh', args: ['-i'], label: 'sh', prompt: '# ' },
|
||||
{ command: '/bin/ash', args: ['-i'], label: 'ash', prompt: '# ' },
|
||||
{ command: 'ash', args: ['-i'], label: 'ash', prompt: '# ' },
|
||||
{ command: '/usr/bin/zsh', args: ['-il'], label: 'zsh', prompt: '# ' },
|
||||
{ command: 'zsh', args: ['-il'], label: 'zsh', prompt: '# ' },
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const result = await this.opsServerRef.oneboxRef.docker.execInContainer(
|
||||
containerIdArg,
|
||||
[candidate.command, '-c', 'printf onebox-shell'],
|
||||
);
|
||||
if (result.exitCode === 0 && result.stdout.includes('onebox-shell')) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new plugins.typedrequest.TypedResponseError(
|
||||
'No supported interactive shell found in the target container',
|
||||
);
|
||||
}
|
||||
|
||||
private async getProcessSession(
|
||||
dataArg: { identity: interfaces.data.IIdentity; processId: string },
|
||||
): Promise<IWorkspaceProcessSession> {
|
||||
const identity = await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
this.validateProcessId(dataArg.processId);
|
||||
const session = this.workspaceProcesses.get(dataArg.processId);
|
||||
if (!session) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Workspace process not found: ${dataArg.processId}`);
|
||||
}
|
||||
if (session.userId !== identity.userId) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Workspace process belongs to another session');
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private async pushWorkspaceProcessOutput(processIdArg: string, outputArg: string): Promise<void> {
|
||||
const typedsocket = (this.opsServerRef.server as any)?.typedserver?.typedsocket;
|
||||
if (!typedsocket) return;
|
||||
|
||||
const connections = await typedsocket.findAllTargetConnectionsByTag(getWorkspaceProcessTag(processIdArg));
|
||||
await Promise.allSettled(
|
||||
connections.map((connection: any) => typedsocket
|
||||
.createTypedRequest(
|
||||
'pushWorkspaceProcessOutput',
|
||||
connection,
|
||||
)
|
||||
.fire({ processId: processIdArg, output: outputArg })),
|
||||
);
|
||||
}
|
||||
|
||||
private async pushWorkspaceProcessExit(processIdArg: string, exitCodeArg: number): Promise<void> {
|
||||
const typedsocket = (this.opsServerRef.server as any)?.typedserver?.typedsocket;
|
||||
if (!typedsocket) return;
|
||||
|
||||
const connections = await typedsocket.findAllTargetConnectionsByTag(getWorkspaceProcessTag(processIdArg));
|
||||
await Promise.allSettled(
|
||||
connections.map((connection: any) => typedsocket
|
||||
.createTypedRequest(
|
||||
'pushWorkspaceProcessExit',
|
||||
connection,
|
||||
)
|
||||
.fire({ processId: processIdArg, exitCode: exitCodeArg })),
|
||||
);
|
||||
}
|
||||
|
||||
private async finalizeWorkspaceProcess(processIdArg: string, fallbackExitCodeArg = -1): Promise<void> {
|
||||
const session = this.workspaceProcesses.get(processIdArg);
|
||||
if (!session || session.finalized) return;
|
||||
session.finalized = true;
|
||||
|
||||
let exitCode = fallbackExitCodeArg;
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const inspectResult = await session.inspect();
|
||||
if (typeof inspectResult.ExitCode === 'number') {
|
||||
exitCode = inspectResult.ExitCode;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.debug(`Failed to inspect workspace process ${processIdArg}: ${getErrorMessage(error)}`);
|
||||
}
|
||||
|
||||
this.workspaceProcesses.delete(processIdArg);
|
||||
await this.pushWorkspaceProcessExit(processIdArg, exitCode);
|
||||
try {
|
||||
await session.close();
|
||||
} catch {
|
||||
// The hijacked connection may already be closed by Docker.
|
||||
}
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Read file from container
|
||||
this.typedrouter.addTypedHandler(
|
||||
@@ -176,6 +294,108 @@ export class WorkspaceHandler {
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceGetShellCommand>(
|
||||
'workspaceGetShellCommand',
|
||||
async (dataArg) => {
|
||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const containerId = await this.resolveContainerId(dataArg.serviceName);
|
||||
const shellCommand = await this.getShellCommandForContainer(containerId);
|
||||
return { shellCommand };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceStartProcess>(
|
||||
'workspaceStartProcess',
|
||||
async (dataArg) => {
|
||||
const identity = await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
this.validateProcessId(dataArg.processId);
|
||||
if (this.workspaceProcesses.has(dataArg.processId)) {
|
||||
throw new plugins.typedrequest.TypedResponseError(`Workspace process already exists: ${dataArg.processId}`);
|
||||
}
|
||||
|
||||
const containerId = await this.resolveContainerId(dataArg.serviceName);
|
||||
const command = dataArg.args ? [dataArg.command, ...dataArg.args] : [dataArg.command];
|
||||
const interactiveExec = await this.opsServerRef.oneboxRef.docker.startInteractiveExecInContainer(
|
||||
containerId,
|
||||
command,
|
||||
);
|
||||
|
||||
const session: IWorkspaceProcessSession = {
|
||||
processId: dataArg.processId,
|
||||
serviceName: dataArg.serviceName,
|
||||
userId: identity.userId,
|
||||
stream: interactiveExec.stream,
|
||||
close: interactiveExec.close,
|
||||
inspect: interactiveExec.inspect,
|
||||
finalized: false,
|
||||
};
|
||||
this.workspaceProcesses.set(dataArg.processId, session);
|
||||
|
||||
interactiveExec.stream.on('data', (chunk: Uint8Array | string) => {
|
||||
const output = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
|
||||
void this.pushWorkspaceProcessOutput(dataArg.processId, output);
|
||||
});
|
||||
interactiveExec.stream.on('error', (error: Error) => {
|
||||
void this.pushWorkspaceProcessOutput(
|
||||
dataArg.processId,
|
||||
`\r\n[workspace process error: ${getErrorMessage(error)}]\r\n`,
|
||||
);
|
||||
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
});
|
||||
interactiveExec.stream.on('end', () => {
|
||||
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
});
|
||||
interactiveExec.stream.on('close', () => {
|
||||
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
});
|
||||
|
||||
return { processId: dataArg.processId };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceProcessInput>(
|
||||
'workspaceProcessInput',
|
||||
async (dataArg) => {
|
||||
const session = await this.getProcessSession(dataArg);
|
||||
if (session.finalized || session.stream.writableEnded) {
|
||||
return {};
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
session.stream.write(dataArg.input, (error?: Error | null) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceKillProcess>(
|
||||
'workspaceKillProcess',
|
||||
async (dataArg) => {
|
||||
const session = await this.getProcessSession(dataArg);
|
||||
session.stream.destroy();
|
||||
try {
|
||||
await session.close();
|
||||
} catch {
|
||||
// The stream may already be closed.
|
||||
}
|
||||
await this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
logger.info('Workspace handler registered');
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
|
||||
* System status data shapes for Onebox
|
||||
*/
|
||||
|
||||
import type { TPlatformServiceType, TPlatformServiceStatus } from './platform.ts';
|
||||
import type { TPlatformServiceStatus, TPlatformServiceType } from './platform.ts';
|
||||
|
||||
export interface IOneboxUpdateStatus {
|
||||
currentVersion: string;
|
||||
@@ -20,6 +20,7 @@ export interface IOneboxUpgradeStartResult {
|
||||
targetVersion: string;
|
||||
message: string;
|
||||
pid?: number;
|
||||
unitName?: string;
|
||||
logPath?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,41 @@ export interface IAppStoreInstallOptions extends servezoneInterfaces.appstore.IA
|
||||
autoDNS?: boolean;
|
||||
}
|
||||
|
||||
export type TAppStoreUpgradeStatus = 'running' | 'success' | 'failed';
|
||||
|
||||
export type TAppStoreUpgradeStep =
|
||||
| 'queued'
|
||||
| 'validating'
|
||||
| 'migration'
|
||||
| 'applying'
|
||||
| 'stopping'
|
||||
| 'pulling-image'
|
||||
| 'updating-record'
|
||||
| 'removing-container'
|
||||
| 'creating-container'
|
||||
| 'starting'
|
||||
| 'restoring-route'
|
||||
| 'syncing-gateway'
|
||||
| 'complete'
|
||||
| 'failed';
|
||||
|
||||
export interface IAppStoreUpgradeOperation {
|
||||
id: string;
|
||||
serviceName: string;
|
||||
appTemplateId: string;
|
||||
fromVersion: string;
|
||||
targetVersion: string;
|
||||
status: TAppStoreUpgradeStatus;
|
||||
step: TAppStoreUpgradeStep;
|
||||
progressLines: string[];
|
||||
warnings: string[];
|
||||
error?: string;
|
||||
startedAt: number;
|
||||
updatedAt: number;
|
||||
completedAt?: number;
|
||||
service?: data.IService;
|
||||
}
|
||||
|
||||
export interface IReq_GetAppStoreTemplates extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetAppStoreTemplates
|
||||
@@ -82,3 +117,42 @@ export interface IReq_UpgradeAppStoreService extends plugins.typedrequestInterfa
|
||||
warnings: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_StartAppStoreServiceUpgrade extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_StartAppStoreServiceUpgrade
|
||||
> {
|
||||
method: 'startAppStoreServiceUpgrade';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
targetVersion: string;
|
||||
};
|
||||
response: {
|
||||
operation: IAppStoreUpgradeOperation;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_GetAppStoreUpgradeOperations extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_GetAppStoreUpgradeOperations
|
||||
> {
|
||||
method: 'getAppStoreUpgradeOperations';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
};
|
||||
response: {
|
||||
operations: IAppStoreUpgradeOperation[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_PushAppStoreUpgradeProgress extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_PushAppStoreUpgradeProgress
|
||||
> {
|
||||
method: 'pushAppStoreUpgradeProgress';
|
||||
request: {
|
||||
operation: IAppStoreUpgradeOperation;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import * as plugins from '../plugins.ts';
|
||||
import * as data from '../data/index.ts';
|
||||
|
||||
export interface IWorkspaceShellCommand {
|
||||
command: string;
|
||||
args?: string[];
|
||||
label?: string;
|
||||
prompt?: string;
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceReadFile extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceReadFile
|
||||
@@ -104,3 +111,83 @@ export interface IReq_WorkspaceExec extends plugins.typedrequestInterfaces.imple
|
||||
exitCode: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceGetShellCommand extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceGetShellCommand
|
||||
> {
|
||||
method: 'workspaceGetShellCommand';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
};
|
||||
response: {
|
||||
shellCommand: IWorkspaceShellCommand;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceStartProcess extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceStartProcess
|
||||
> {
|
||||
method: 'workspaceStartProcess';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
serviceName: string;
|
||||
processId: string;
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
response: {
|
||||
processId: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceProcessInput extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceProcessInput
|
||||
> {
|
||||
method: 'workspaceProcessInput';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
processId: string;
|
||||
input: string;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
export interface IReq_WorkspaceKillProcess extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_WorkspaceKillProcess
|
||||
> {
|
||||
method: 'workspaceKillProcess';
|
||||
request: {
|
||||
identity: data.IIdentity;
|
||||
processId: string;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
export interface IReq_PushWorkspaceProcessOutput extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_PushWorkspaceProcessOutput
|
||||
> {
|
||||
method: 'pushWorkspaceProcessOutput';
|
||||
request: {
|
||||
processId: string;
|
||||
output: string;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
export interface IReq_PushWorkspaceProcessExit extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_PushWorkspaceProcessExit
|
||||
> {
|
||||
method: 'pushWorkspaceProcessExit';
|
||||
request: {
|
||||
processId: string;
|
||||
exitCode: number;
|
||||
};
|
||||
response: {};
|
||||
}
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/onebox',
|
||||
version: '2.0.0',
|
||||
version: '2.1.2',
|
||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||
}
|
||||
|
||||
+66
-9
@@ -60,6 +60,7 @@ export interface ISettingsState {
|
||||
export interface IAppStoreState {
|
||||
apps: interfaces.requests.IAppStoreApp[];
|
||||
upgradeableServices: interfaces.requests.IUpgradeableAppStoreService[];
|
||||
upgradeOperations: interfaces.requests.IAppStoreUpgradeOperation[];
|
||||
}
|
||||
|
||||
export interface IUiState {
|
||||
@@ -154,6 +155,7 @@ export const appStoreStatePart = await appState.getStatePart<IAppStoreState>(
|
||||
{
|
||||
apps: [],
|
||||
upgradeableServices: [],
|
||||
upgradeOperations: [],
|
||||
},
|
||||
'soft',
|
||||
);
|
||||
@@ -1101,6 +1103,19 @@ const upsertService = (
|
||||
return updatedServices;
|
||||
};
|
||||
|
||||
const upsertUpgradeOperation = (
|
||||
operations: interfaces.requests.IAppStoreUpgradeOperation[],
|
||||
operation: interfaces.requests.IAppStoreUpgradeOperation,
|
||||
): interfaces.requests.IAppStoreUpgradeOperation[] => {
|
||||
const existingIndex = operations.findIndex((item) => item.id === operation.id);
|
||||
const updatedOperations = existingIndex === -1
|
||||
? [operation, ...operations]
|
||||
: operations.map((item) => item.id === operation.id ? operation : item);
|
||||
return updatedOperations
|
||||
.sort((a, b) => b.startedAt - a.startedAt)
|
||||
.slice(0, 25);
|
||||
};
|
||||
|
||||
socketRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushServiceUpdate>(
|
||||
'pushServiceUpdate',
|
||||
@@ -1137,6 +1152,33 @@ socketRouter.addTypedHandler(
|
||||
),
|
||||
);
|
||||
|
||||
socketRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushAppStoreUpgradeProgress>(
|
||||
'pushAppStoreUpgradeProgress',
|
||||
async (dataArg) => {
|
||||
const state = appStoreStatePart.getState();
|
||||
appStoreStatePart.setState({
|
||||
...state,
|
||||
upgradeOperations: upsertUpgradeOperation(state.upgradeOperations, dataArg.operation),
|
||||
upgradeableServices: dataArg.operation.status === 'success'
|
||||
? state.upgradeableServices.filter((service) => service.serviceName !== dataArg.operation.serviceName)
|
||||
: state.upgradeableServices,
|
||||
});
|
||||
if (dataArg.operation.service) {
|
||||
const servicesState = servicesStatePart.getState();
|
||||
servicesStatePart.setState({
|
||||
...servicesState,
|
||||
services: upsertService(servicesState.services, dataArg.operation.service),
|
||||
currentService: servicesState.currentService?.name === dataArg.operation.service.name
|
||||
? dataArg.operation.service
|
||||
: servicesState.currentService,
|
||||
});
|
||||
}
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Handle server-pushed platform service log entries
|
||||
socketRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushPlatformServiceLog>(
|
||||
@@ -1258,6 +1300,22 @@ export const fetchUpgradeableAppStoreServicesAction = appStoreStatePart.createAc
|
||||
},
|
||||
);
|
||||
|
||||
export const fetchAppStoreUpgradeOperationsAction = appStoreStatePart.createAction(
|
||||
async (statePartArg) => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetAppStoreUpgradeOperations
|
||||
>('/typedrequest', 'getAppStoreUpgradeOperations');
|
||||
const response = await typedRequest.fire({ identity: context.identity! });
|
||||
return { ...statePartArg.getState(), upgradeOperations: response.operations };
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch upgrade operations:', err);
|
||||
return statePartArg.getState();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const upgradeAppStoreServiceAction = appStoreStatePart.createAction<{
|
||||
serviceName: string;
|
||||
targetVersion: string;
|
||||
@@ -1265,19 +1323,18 @@ export const upgradeAppStoreServiceAction = appStoreStatePart.createAction<{
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_UpgradeAppStoreService
|
||||
>('/typedrequest', 'upgradeAppStoreService');
|
||||
await typedRequest.fire({
|
||||
interfaces.requests.IReq_StartAppStoreServiceUpgrade
|
||||
>('/typedrequest', 'startAppStoreServiceUpgrade');
|
||||
const response = await typedRequest.fire({
|
||||
identity: context.identity!,
|
||||
serviceName: dataArg.serviceName,
|
||||
targetVersion: dataArg.targetVersion,
|
||||
});
|
||||
// Re-fetch upgradeable services and services list
|
||||
const upgradeReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetUpgradeableAppStoreServices
|
||||
>('/typedrequest', 'getUpgradeableAppStoreServices');
|
||||
const upgradeResp = await upgradeReq.fire({ identity: context.identity! });
|
||||
return { ...statePartArg.getState(), upgradeableServices: upgradeResp.services };
|
||||
const state = statePartArg.getState();
|
||||
return {
|
||||
...state,
|
||||
upgradeOperations: upsertUpgradeOperation(state.upgradeOperations, response.operation),
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('Failed to upgrade service:', err);
|
||||
return statePartArg.getState();
|
||||
|
||||
@@ -19,6 +19,7 @@ export class ObViewAppStore extends DeesElement {
|
||||
accessor appStoreState: appstate.IAppStoreState = {
|
||||
apps: [],
|
||||
upgradeableServices: [],
|
||||
upgradeOperations: [],
|
||||
};
|
||||
|
||||
@state()
|
||||
@@ -331,7 +332,10 @@ export class ObViewAppStore extends DeesElement {
|
||||
|
||||
async connectedCallback() {
|
||||
super.connectedCallback();
|
||||
await appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreTemplatesAction, null);
|
||||
await Promise.all([
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreTemplatesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreUpgradeOperationsAction, null),
|
||||
]);
|
||||
}
|
||||
|
||||
public render(): TemplateResult {
|
||||
@@ -357,6 +361,7 @@ export class ObViewAppStore extends DeesElement {
|
||||
|
||||
return html`
|
||||
<ob-sectionheading>App Store</ob-sectionheading>
|
||||
${this.renderUpgradeOperations()}
|
||||
${appTemplates.length === 0
|
||||
? html`<div class="loading-spinner">Loading app templates...</div>`
|
||||
: html`
|
||||
@@ -369,6 +374,27 @@ export class ObViewAppStore extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderUpgradeOperations(): TemplateResult | '' {
|
||||
const visibleOperations = this.appStoreState.upgradeOperations
|
||||
.filter((operation) => operation.status === 'running' || operation.status === 'failed')
|
||||
.slice(0, 3);
|
||||
if (visibleOperations.length === 0) return '';
|
||||
|
||||
return html`
|
||||
<div class="detail-card">
|
||||
<div class="section-label">Recent Upgrade Operations</div>
|
||||
<div class="footprint-list">
|
||||
${visibleOperations.map((operation) => html`
|
||||
<div class="footprint-item">
|
||||
<span>${operation.serviceName}: ${operation.fromVersion} → ${operation.targetVersion}</span>
|
||||
<span class="footprint-meta">${operation.status} / ${operation.step}</span>
|
||||
</div>
|
||||
`)}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderDetailView(): TemplateResult {
|
||||
if (this.loading) {
|
||||
return html`
|
||||
|
||||
@@ -146,6 +146,7 @@ export class ObViewServices extends DeesElement {
|
||||
accessor appStoreState: appstate.IAppStoreState = {
|
||||
apps: [],
|
||||
upgradeableServices: [],
|
||||
upgradeOperations: [],
|
||||
};
|
||||
|
||||
constructor() {
|
||||
@@ -227,6 +228,7 @@ export class ObViewServices extends DeesElement {
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null),
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchPlatformServicesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchUpgradeableAppStoreServicesAction, null),
|
||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreUpgradeOperationsAction, null),
|
||||
]);
|
||||
|
||||
// If a platform service was selected from the dashboard, navigate to its detail
|
||||
@@ -471,9 +473,21 @@ export class ObViewServices extends DeesElement {
|
||||
const upgradeInfo = service
|
||||
? this.appStoreState.upgradeableServices.find((u) => u.serviceName === service.name)
|
||||
: null;
|
||||
const upgradeOperation = service
|
||||
? this.appStoreState.upgradeOperations.find((operation) => {
|
||||
return operation.serviceName === service.name && operation.status === 'running';
|
||||
})
|
||||
: null;
|
||||
const latestUpgradeOperation = service
|
||||
? this.appStoreState.upgradeOperations.find((operation) => operation.serviceName === service.name)
|
||||
: null;
|
||||
|
||||
return html`
|
||||
<ob-sectionheading>Service Details</ob-sectionheading>
|
||||
${upgradeOperation ? this.renderUpgradeOperation(upgradeOperation) : ''}
|
||||
${!upgradeOperation && latestUpgradeOperation?.status === 'failed'
|
||||
? this.renderUpgradeOperation(latestUpgradeOperation)
|
||||
: ''}
|
||||
${upgradeInfo ? html`
|
||||
<div style="
|
||||
background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(139, 92, 246, 0.1));
|
||||
@@ -496,18 +510,14 @@ export class ObViewServices extends DeesElement {
|
||||
<button
|
||||
class="deploy-button"
|
||||
style="padding: 8px 16px; font-size: 13px;"
|
||||
?disabled=${Boolean(upgradeOperation)}
|
||||
@click=${async () => {
|
||||
await appstate.appStoreStatePart.dispatchAction(appstate.upgradeAppStoreServiceAction, {
|
||||
serviceName: upgradeInfo.serviceName,
|
||||
targetVersion: upgradeInfo.latestVersion,
|
||||
});
|
||||
// Refresh service data
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServiceAction, {
|
||||
name: upgradeInfo.serviceName,
|
||||
});
|
||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null);
|
||||
}}
|
||||
>Upgrade</button>
|
||||
>${upgradeOperation ? 'Upgrading...' : 'Upgrade'}</button>
|
||||
</div>
|
||||
` : ''}
|
||||
<sz-service-detail-view
|
||||
@@ -544,6 +554,53 @@ export class ObViewServices extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderUpgradeOperation(
|
||||
operationArg: interfaces.requests.IAppStoreUpgradeOperation,
|
||||
): TemplateResult {
|
||||
const color = operationArg.status === 'failed' ? '#f87171' : '#60a5fa';
|
||||
return html`
|
||||
<div style="
|
||||
background: var(--ci-shade-1, #09090b);
|
||||
border: 1px solid ${color};
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
margin-bottom: 16px;
|
||||
">
|
||||
<div style="display: flex; justify-content: space-between; gap: 16px; align-items: flex-start;">
|
||||
<div>
|
||||
<div style="font-size: 14px; font-weight: 600; color: var(--ci-shade-7, #e4e4e7);">
|
||||
Upgrade ${operationArg.fromVersion} → ${operationArg.targetVersion}: ${operationArg.step}
|
||||
</div>
|
||||
<div style="font-size: 12px; color: var(--ci-shade-4, #71717a); margin-top: 4px;">
|
||||
${operationArg.status === 'running' ? 'Operation is running in the background.' : operationArg.error || 'Operation finished.'}
|
||||
</div>
|
||||
</div>
|
||||
<span style="font-size: 12px; color: ${color}; text-transform: uppercase; letter-spacing: 0.04em;">
|
||||
${operationArg.status}
|
||||
</span>
|
||||
</div>
|
||||
<div style="
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--ci-shade-0, #030305);
|
||||
border-radius: 6px;
|
||||
color: var(--ci-shade-5, #a1a1aa);
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
max-height: 130px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
">${operationArg.progressLines.slice(-8).join('\n')}</div>
|
||||
${operationArg.warnings.length > 0 ? html`
|
||||
<div style="margin-top: 10px; color: #fbbf24; font-size: 12px;">
|
||||
${operationArg.warnings.join(' | ')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderBackupsView(): TemplateResult {
|
||||
return html`
|
||||
<ob-sectionheading>Backups</ob-sectionheading>
|
||||
|
||||
@@ -12,19 +12,30 @@ type IExecutionEnvironment = import('@design.estate/dees-catalog').IExecutionEnv
|
||||
type IFileEntry = import('@design.estate/dees-catalog').IFileEntry;
|
||||
type IFileWatcher = import('@design.estate/dees-catalog').IFileWatcher;
|
||||
type IProcessHandle = import('@design.estate/dees-catalog').IProcessHandle;
|
||||
type IWorkspaceShellCommand = interfaces.requests.IWorkspaceShellCommand;
|
||||
|
||||
const domtools = plugins.deesElement.domtools;
|
||||
|
||||
interface IWorkspaceProcessState {
|
||||
outputController: ReadableStreamDefaultController<string>;
|
||||
resolveExit: (exitCodeArg: number) => void;
|
||||
}
|
||||
|
||||
export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||
readonly type = 'backend' as const;
|
||||
private _ready = false;
|
||||
private identity: interfaces.data.IIdentity;
|
||||
private processRouter = new plugins.domtools.plugins.typedrequest.TypedRouter();
|
||||
private processSocket: InstanceType<typeof plugins.typedsocket.TypedSocket> | null = null;
|
||||
private processSocketPromise: Promise<InstanceType<typeof plugins.typedsocket.TypedSocket>> | null = null;
|
||||
private processStates = new Map<string, IWorkspaceProcessState>();
|
||||
|
||||
constructor(
|
||||
private serviceName: string,
|
||||
identity: interfaces.data.IIdentity,
|
||||
) {
|
||||
this.identity = identity;
|
||||
this.registerProcessSocketHandlers();
|
||||
}
|
||||
|
||||
get ready(): boolean {
|
||||
@@ -44,6 +55,12 @@ export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
for (const processId of Array.from(this.processStates.keys())) {
|
||||
await this.killProcess(processId).catch(() => {});
|
||||
}
|
||||
await this.processSocket?.stop().catch(() => {});
|
||||
this.processSocket = null;
|
||||
this.processSocketPromise = null;
|
||||
this._ready = false;
|
||||
}
|
||||
|
||||
@@ -103,38 +120,142 @@ export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||
}
|
||||
|
||||
async spawn(command: string, args?: string[]): Promise<IProcessHandle> {
|
||||
// For interactive shell: execute the command via the workspace exec API
|
||||
// and return a process handle that bridges stdin/stdout
|
||||
const cmd = args ? [command, ...args] : [command];
|
||||
const fullCommand = cmd.join(' ');
|
||||
const socket = await this.ensureProcessSocket();
|
||||
const processId = crypto.randomUUID();
|
||||
await socket.setTag(`workspaceProcess:${processId}`, true);
|
||||
|
||||
// Use a non-interactive exec for now — full interactive shell would need
|
||||
// TypedSocket bidirectional streaming (to be implemented)
|
||||
const result = await this.fireRequest<interfaces.requests.IReq_WorkspaceExec>(
|
||||
'workspaceExec',
|
||||
{ command: cmd[0], args: cmd.slice(1) },
|
||||
);
|
||||
|
||||
// Create a ReadableStream from the exec output
|
||||
let resolveExit: (exitCodeArg: number) => void = () => {};
|
||||
const exit = new Promise<number>((resolve) => {
|
||||
resolveExit = resolve;
|
||||
});
|
||||
const output = new ReadableStream<string>({
|
||||
start(controller) {
|
||||
if (result.stdout) controller.enqueue(result.stdout);
|
||||
if (result.stderr) controller.enqueue(result.stderr);
|
||||
controller.close();
|
||||
start: (controller) => {
|
||||
this.processStates.set(processId, {
|
||||
outputController: controller,
|
||||
resolveExit,
|
||||
});
|
||||
},
|
||||
cancel: async () => {
|
||||
await this.killProcess(processId).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
// Create a writable stream (no-op for non-interactive)
|
||||
const inputStream = new WritableStream<string>();
|
||||
try {
|
||||
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceStartProcess>(
|
||||
'workspaceStartProcess',
|
||||
).fire({
|
||||
identity: this.identity,
|
||||
serviceName: this.serviceName,
|
||||
processId,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
} catch (error) {
|
||||
const processState = this.processStates.get(processId);
|
||||
this.processStates.delete(processId);
|
||||
await socket.removeTag(`workspaceProcess:${processId}`).catch(() => {});
|
||||
try {
|
||||
processState?.outputController.error(error);
|
||||
} catch {
|
||||
// The stream may already have been cancelled by the terminal.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const input = new WritableStream<string>({
|
||||
write: async (chunkArg) => {
|
||||
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceProcessInput>(
|
||||
'workspaceProcessInput',
|
||||
).fire({
|
||||
identity: this.identity,
|
||||
processId,
|
||||
input: chunkArg,
|
||||
});
|
||||
},
|
||||
abort: async () => {
|
||||
await this.killProcess(processId).catch(() => {});
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
output,
|
||||
input: inputStream,
|
||||
exit: Promise.resolve(result.exitCode),
|
||||
kill: () => {},
|
||||
input,
|
||||
exit,
|
||||
kill: () => {
|
||||
void this.killProcess(processId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getShellCommand(): Promise<IWorkspaceShellCommand> {
|
||||
const result = await this.fireRequest<interfaces.requests.IReq_WorkspaceGetShellCommand>(
|
||||
'workspaceGetShellCommand',
|
||||
{},
|
||||
);
|
||||
return result.shellCommand;
|
||||
}
|
||||
|
||||
private registerProcessSocketHandlers(): void {
|
||||
this.processRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushWorkspaceProcessOutput>(
|
||||
'pushWorkspaceProcessOutput',
|
||||
async (dataArg: interfaces.requests.IReq_PushWorkspaceProcessOutput['request']) => {
|
||||
this.processStates.get(dataArg.processId)?.outputController.enqueue(dataArg.output);
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
this.processRouter.addTypedHandler(
|
||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushWorkspaceProcessExit>(
|
||||
'pushWorkspaceProcessExit',
|
||||
async (dataArg: interfaces.requests.IReq_PushWorkspaceProcessExit['request']) => {
|
||||
this.completeProcessState(dataArg.processId, dataArg.exitCode);
|
||||
await this.processSocket?.removeTag(`workspaceProcess:${dataArg.processId}`).catch(() => {});
|
||||
return {};
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async ensureProcessSocket(): Promise<InstanceType<typeof plugins.typedsocket.TypedSocket>> {
|
||||
if (this.processSocket) return this.processSocket;
|
||||
if (!this.processSocketPromise) {
|
||||
this.processSocketPromise = plugins.typedsocket.TypedSocket.createClient(
|
||||
this.processRouter,
|
||||
plugins.typedsocket.TypedSocket.useWindowLocationOriginUrl(),
|
||||
{ autoReconnect: true },
|
||||
);
|
||||
}
|
||||
this.processSocket = await this.processSocketPromise;
|
||||
return this.processSocket;
|
||||
}
|
||||
|
||||
private completeProcessState(processIdArg: string, exitCodeArg: number): void {
|
||||
const processState = this.processStates.get(processIdArg);
|
||||
if (!processState) return;
|
||||
try {
|
||||
processState.outputController.close();
|
||||
} catch {
|
||||
// The terminal may already have cancelled the stream.
|
||||
}
|
||||
processState.resolveExit(exitCodeArg);
|
||||
this.processStates.delete(processIdArg);
|
||||
}
|
||||
|
||||
private async killProcess(processIdArg: string): Promise<void> {
|
||||
const socket = this.processSocket;
|
||||
if (!socket) return;
|
||||
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceKillProcess>(
|
||||
'workspaceKillProcess',
|
||||
).fire({
|
||||
identity: this.identity,
|
||||
processId: processIdArg,
|
||||
}).catch(() => {});
|
||||
this.completeProcessState(processIdArg, -1);
|
||||
await socket.removeTag(`workspaceProcess:${processIdArg}`).catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to fire TypedRequests to the workspace API
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user