Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -1991,11 +1991,32 @@ fetch all compute environments
{ "id": "disk", "max": 1000000000, "inUse": 0 }
]
},
"runningfreeJobs": 0
"runningfreeJobs": 0,
"serviceOnDemand": {
"nodeHost": "node1.example.com",
"hostPortRange": [30000, 32767],
"usedHostPorts": [30000, 30500],
"maxPortsPerService": 64
}
}
]
```

`serviceOnDemand` is the **per-daemon service-port discovery** block (additive; absent on older
nodes and on daemons without a `serviceOnDemand` config). A client reads it to pin a host port on
SERVICE_START / SERVICE_RESTART: pick any value inside `hostPortRange` that is **not** in
`usedHostPorts`.

- `nodeHost` — host/IP the forwarded service ports are reachable on.
- `hostPortRange` — inclusive `[start, end]` a pinned `hostPort` must fall within.
- `usedHostPorts` — host ports in range already reserved or bound, **daemon-wide** and ascending.
Because ports belong to the host the Docker engine runs on (not to one environment), **every
environment on the same daemon carries an identical `serviceOnDemand` block**, and a port is
listed as used even when the service holding it runs in a different environment of that daemon.
It is a best-effort snapshot — a port can be claimed between this read and the start — so the
charge-safe reservation in the start handler remains the real guarantee.
- `maxPortsPerService` — cap on how many ports a single start/restart command may declare.

`maxJobDuration` / `minJobDuration` apply to **compute jobs**. Services have their own pair,
and SERVICE_START rejects a `duration` outside it:

Expand Down
37 changes: 37 additions & 0 deletions docs/services.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,43 @@ Two request shapes, both optional:
> (Typesense `8108` / Elasticsearch `9200`). The schema already forbids privileged ports
> (`< 1024`) and the default `[30000, 32767]` is clear of all node ports; the OS-freeness check is
> only a last line of defence, so pick a range that cannot collide with the node's own services.
>
> **Multiple daemons must use disjoint ranges.** Host-port reservations live in one process-wide
> pool, so when a node runs several service-enabled docker daemons (multiple
> `DOCKER_COMPUTE_ENVIRONMENTS` entries) their `hostPortRange`s **must not overlap** — otherwise a
> reservation on one daemon would block the same port on another and corrupt the per-daemon
> `usedHostPorts` snapshot below. This is **enforced at startup**: the node **refuses to boot** if
> two service-enabled daemons have overlapping ranges (two daemons that both omit `hostPortRange`
> share the default `[30000, 32767]` and so overlap — give each an explicit disjoint range).

**Discovering the range and the ports already in use.** Before pinning a host port, a client needs
to know (1) which range it may pin inside, and (2) which ports are already taken. Both are
surfaced on each environment returned by `getComputeEnvironments`, in a per-daemon
`serviceOnDemand` block:

```jsonc
"serviceOnDemand": {
"nodeHost": "node1.example.com", // where forwarded ports are reachable
"hostPortRange": [30000, 32767], // the inclusive range a pin must fall inside
"usedHostPorts": [30000, 30500], // host ports in range already reserved or bound
"maxPortsPerService": 64 // cap on ports per start/restart command
}
```

To pick a host port to pin, choose any value inside `hostPortRange` that is **not** in
`usedHostPorts`. Because **ports belong to the host the Docker engine runs on, not to a single
environment**, every environment on the same daemon carries an **identical** `serviceOnDemand`
block and a **daemon-wide** `usedHostPorts` union — so an environment reports a port as used even
when the service holding it runs in a *different* environment of the same daemon. A node that
exposes several daemons (several `DOCKER_COMPUTE_ENVIRONMENTS` entries) reports a separate block
per daemon, each with its own range and used set. Environments on a daemon that has no
Service-on-Demand config omit the block entirely.

`usedHostPorts` is a **best-effort snapshot**: a port can be claimed between reading it and
starting a service, so a pin you believed free can still lose the race. That is harmless — the
authoritative, charge-safe reservation stays in the start handler (a lost race returns a no-charge
`400`, or a `Starting` job that becomes `Error`). Treat the block as a hint that makes conflicts
rare, not a guarantee.

`serviceRestart` accepts `ports` too — independent of REUSE/RESPEC, exactly like `metadata`
(a port change does **not** require `image`). Send `ports` to change the service's ports; omit it
Expand Down
20 changes: 20 additions & 0 deletions src/@types/C2D/C2D.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,22 @@ export interface C2DEnvironmentFreeConfig {
allowImageBuild?: boolean
buildTimeoutSeconds?: number // max image-build runtime; unset → runtime default (DEFAULT_BUILD_TIMEOUT_SECONDS)
}
// Daemon-level Service-on-Demand port discovery, surfaced on every environment that belongs
// to the same Docker engine. Ports are a property of the HOST the Docker socket runs on, not
// of a single environment, so every env on one daemon carries an IDENTICAL copy of this block
// (the `usedHostPorts` union spans the whole daemon). A client uses it to pick a free host
// port to PIN on SERVICE_START / SERVICE_RESTART (see `ServicePortRequest`): choose any value
// inside `hostPortRange` that is not in `usedHostPorts`. It is a best-effort snapshot — a port
// can be claimed between this read and the start — so the authoritative, charge-safe guarantee
// stays the start handler's reservation (a lost race returns a no-charge 400 / Starting→Error).
// Present only when the daemon has Service-on-Demand enabled with a reachable `nodeHost`.
export interface ComputeEnvironmentServiceOnDemand {
nodeHost: string // host/IP clients use to reach forwarded ports (from serviceOnDemand.nodeHost)
hostPortRange: [number, number] // inclusive [start, end] a pinned host port must fall within
usedHostPorts: number[] // host ports in range already reserved or bound, daemon-wide, ascending
maxPortsPerService: number // max ports a single SERVICE_START / SERVICE_RESTART may declare
}

export interface ComputeEnvironmentBaseConfig {
description?: string // v1
storageExpiry?: number // amount of seconds for storage
Expand All @@ -171,6 +187,10 @@ export interface ComputeEnvironmentBaseConfig {
platform: RunningPlatform
enableNetwork?: boolean // whether network is enabled for algorithm containers
features?: ComputeEnvFeatures // always populated at runtime construction; gates compute/service starts
// Daemon-level service port discovery (range + in-use host ports), stamped identically on
// every env of the daemon at getComputeEnvironments() time. Absent when the daemon has no
// Service-on-Demand config. See ComputeEnvironmentServiceOnDemand.
serviceOnDemand?: ComputeEnvironmentServiceOnDemand
}

export interface ComputeRuntimes {
Expand Down
14 changes: 14 additions & 0 deletions src/@types/C2D/ServiceOnDemand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,20 @@ export const DEFAULT_SERVICE_MIN_DURATION_SECONDS = 0
// the daemon busy. Always capped by the job/service maxDuration so it can never exceed it.
export const DEFAULT_BUILD_TIMEOUT_SECONDS = 300 // 5 min

// Max number of ports a single SERVICE_START / SERVICE_RESTART may declare (via `ports` or the
// legacy `exposedPorts`). Bounds the host-port range a single request can consume and the size
// of the validation work. Advertised to clients as `maxPortsPerService` on each environment's
// serviceOnDemand block. Single source of truth for the request validators and that field.
export const MAX_SERVICE_PORTS = 64

// Default host-port range used when a daemon's `serviceOnDemand` block omits `hostPortRange`.
// MUST be the single source of truth: the range the start/restart handlers reserve a pinned
// port within, the range they auto-allocate from, AND the range advertised by
// getComputeEnvironments must all agree — otherwise the discovery block would advertise a range
// the handler does not actually enforce. `[30000, 32767]` is the IANA ephemeral/dynamic range
// and is clear of the ports the node itself binds (HTTP 8000, P2P 9000-9005, DB 8108/9200).
export const DEFAULT_SERVICE_HOST_PORT_RANGE: [number, number] = [30000, 32767]

export interface ServiceOnDemandConfig {
enabled: boolean
nodeHost: string // host (or IP) clients use to reach forwarded service ports; e.g. 'localhost'
Expand Down
81 changes: 75 additions & 6 deletions src/components/c2d/compute_engine_docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import type {
C2DClusterInfo,
ComputeEnvironment,
ComputeEnvironmentServiceOnDemand,
ComputeAlgorithm,
ComputeOutput,
ComputeAsset,
Expand Down Expand Up @@ -90,7 +91,9 @@ import {
ServiceStatusText,
SERVICE_START_PENDING_STATUSES,
isStoppedLike,
DEFAULT_BUILD_TIMEOUT_SECONDS
DEFAULT_BUILD_TIMEOUT_SECONDS,
MAX_SERVICE_PORTS,
DEFAULT_SERVICE_HOST_PORT_RANGE
} from '../../@types/C2D/ServiceOnDemand.js'
import type {
ServiceJob,
Expand Down Expand Up @@ -163,6 +166,7 @@ import {
reserveSpecificHostPort,
HostPortUnavailableError,
seedAllocatedPorts,
reservedHostPortsInRange,
userDataToEnv,
decryptUserData
} from '../core/service/utils.js'
Expand Down Expand Up @@ -824,8 +828,11 @@ export class C2DEngineDocker extends C2DEngine {
await this.rebuildCpuAllocations()
await this.rebuildServiceCpuAllocations()

// Re-seed the in-memory allocated-host-port set from running service jobs (handles node restart)
await seedAllocatedPorts(this.db, this.getC2DConfig().hash).catch((e) => {
// Re-seed the in-memory allocated-host-port set from running service jobs (handles node
// restart). Host-wide (all clusters) so a reservation held by a daemon that was removed from
// config is still honored for its paid window — see seedAllocatedPorts. Idempotent, so it is
// harmless that each engine runs it at boot.
await seedAllocatedPorts(this.db).catch((e) => {
CORE_LOGGER.error(`Could not seed allocated service ports: ${e.message}`)
})

Expand Down Expand Up @@ -1400,13 +1407,66 @@ export class C2DEngineDocker extends C2DEngine {
}
}

// Build the daemon-level Service-on-Demand port-discovery block (range + in-use host ports)
// ONCE per getComputeEnvironments call. Returned undefined when this daemon has no
// Service-on-Demand config (or it is disabled / has no reachable nodeHost), in which case the
// field is simply omitted from the environments. `usedHostPorts` is the union of two sources:
// 1. running service jobs' endpoint host ports (persisted, authoritative — includes every
// status that still holds a reservation, Starting through Stopped),
// 2. in-memory reservations (covers the brief in-flight window after a start reserves a port
// but before its job endpoints are persisted).
// Both are filtered to this daemon's hostPortRange. The DB read is intentionally host-wide
// (ALL clusters, not just this cluster's hash) and then range-filtered: a host port is a
// host-wide resource, and because ranges are guaranteed disjoint across active daemons
// (assertNoOverlappingServiceHostPortRanges), everything a job holds inside THIS range belongs
// to this daemon — INCLUDING a port still held by a paid service of a daemon that was since
// disabled or re-ranged onto a range this daemon now owns. Scoping to clusterHash would miss
// that stale port and advertise it as free. (The allocator's own OS-freeness check in
// reserveSpecificHostPort / allocateHostPort is the authoritative backstop that still prevents
// a double-bind in that transition; this only keeps the advertised snapshot honest.)
// Best-effort snapshot: the start handler's charge-safe reservation remains the real guarantee.
private async buildServiceOnDemandPortInfo(): Promise<
ComputeEnvironmentServiceOnDemand | undefined
> {
const sod = this.getC2DConfig().connection?.serviceOnDemand
if (!sod?.enabled || !sod.nodeHost) return undefined
const range: [number, number] = sod.hostPortRange ?? DEFAULT_SERVICE_HOST_PORT_RANGE
const used = new Set<number>()
try {
const jobs = await this.db.getRunningServiceJobs() // host-wide; range-filtered below
// Every non-terminal job (getRunningServiceJobs excludes Expired) still holds its reservation
// until it is finalized — same rule as seedAllocatedPorts — so the advertised snapshot and
// the allocator's in-memory set stay aligned.
for (const job of jobs)
for (const ep of job.endpoints ?? [])
if (ep.hostPort >= range[0] && ep.hostPort <= range[1]) used.add(ep.hostPort)
} catch (e) {
// Degrade gracefully: a DB hiccup must not fail the whole environments response. The
// in-memory reservations below still give a partial, safe-side view.
CORE_LOGGER.warn(
`buildServiceOnDemandPortInfo: could not read running service jobs for ` +
`${this.getC2DConfig().hash}: ${e?.message}`
)
}
for (const port of reservedHostPortsInRange(range)) used.add(port)
Comment thread
alexcos20 marked this conversation as resolved.
Resolved
return {
nodeHost: sod.nodeHost,
hostPortRange: range,
usedHostPorts: [...used].sort((a, b) => a - b),
maxPortsPerService: MAX_SERVICE_PORTS
}
}

public override async getComputeEnvironments(
chainId?: number
): Promise<ComputeEnvironment[]> {
/**
* Returns all cluster's compute environments, filtered by a specific chainId if needed. Env's id already contains the cluster hash
*/
if (!this.docker) return []
// Daemon-wide, computed once and stamped identically onto every env below: ports belong to
// the host the Docker socket runs on, not to a single environment.
const serviceOnDemandPortInfo = await this.buildServiceOnDemandPortInfo()
const filteredEnvs = []
// Rebuilt fresh each call from the inUse/total this method already stamps below — read
// by the OTel compute gauge callback (`telemetry/computeGauges.ts`), never written there.
Expand Down Expand Up @@ -1491,6 +1551,15 @@ export class C2DEngineDocker extends C2DEngine {
)
}

// Stamp the daemon-level port-discovery block. Each env gets its own copy so a later
// consumer mutating one env's block cannot bleed into another's.
if (serviceOnDemandPortInfo)
computeEnv.serviceOnDemand = {
...serviceOnDemandPortInfo,
hostPortRange: [...serviceOnDemandPortInfo.hostPortRange],
usedHostPorts: [...serviceOnDemandPortInfo.usedHostPorts]
}

filteredEnvs.push(computeEnv)
}
}
Expand Down Expand Up @@ -4991,7 +5060,7 @@ export class C2DEngineDocker extends C2DEngine {
// failure (image-failure return + outer catch) and cleared once job.endpoints is committed.
const reservedPinned: number[] = []
if (job.requestedHostPorts && Object.keys(job.requestedHostPorts).length) {
const [rs, re] = sod?.hostPortRange ?? [30000, 32767]
const [rs, re] = sod?.hostPortRange ?? DEFAULT_SERVICE_HOST_PORT_RANGE
try {
for (const hp of Object.values(job.requestedHostPorts)) {
await reserveSpecificHostPort(hp, rs, re)
Expand Down Expand Up @@ -5160,7 +5229,7 @@ export class C2DEngineDocker extends C2DEngine {
// mid-way failure must release BOTH the auto ports allocated here AND the pre-lock pinned
// ones — otherwise they leak (the outer catch only releases on !claimTx, and the claim has
// already succeeded by this point, so it would never free them).
const [rangeStart, rangeEnd] = sod?.hostPortRange ?? [30000, 32767]
const [rangeStart, rangeEnd] = sod?.hostPortRange ?? DEFAULT_SERVICE_HOST_PORT_RANGE
const hostPorts: number[] = []
const autoAllocated: number[] = []
try {
Expand Down Expand Up @@ -6652,7 +6721,7 @@ export class C2DEngineDocker extends C2DEngine {
// host ports are released later, after teardown, by doRestartService.
if (newExposedPorts !== undefined) {
const sodPorts = this.getC2DConfig().connection?.serviceOnDemand
const [rs, re] = sodPorts?.hostPortRange ?? [30000, 32767]
const [rs, re] = sodPorts?.hostPortRange ?? DEFAULT_SERVICE_HOST_PORT_RANGE
const nodeHost = sodPorts?.nodeHost ?? 'localhost'
const ownHostPorts = new Set(job.endpoints.map((e) => e.hostPort))
// Current containerPort → hostPort map, so an unpinned container port that already exists
Expand Down
11 changes: 11 additions & 0 deletions src/components/core/admin/pushConfigHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import { ReadableString } from '../../P2P/handleProtocolCommands.js'
import { getConfiguration, getConfigFilePath } from '../../../utils/config/index.js'
import { OceanNodeConfigSchema } from '../../../utils/config/schemas.js'
import { assertNoOverlappingServiceHostPortRanges } from '../../../utils/config/builder.js'
import fs from 'fs'

export class PushConfigHandler extends AdminCommandHandler {
Expand All @@ -29,6 +30,16 @@
const mergedConfig = { ...currentConfig, ...command.config }

const parsedConfig = OceanNodeConfigSchema.parse(mergedConfig)

// Overlap is enforced at config build (buildC2DClusters), which runs AFTER the handler has
// already written the file — so a config that passes the Zod schema but has overlapping
// service host-port ranges would be persisted and then crash the next startup. Run the same
// check here, before any save, so a bad push is rejected and the on-disk config is left
// intact. Field name mirrors builder.ts (OceanNodeConfig.dockerComputeEnvironments).
assertNoOverlappingServiceHostPortRanges(
(mergedConfig as any).dockerComputeEnvironments
)

// isEnterprise picks the escrow contract. Core would switch on reload, but the running
// indexers keep tracking the old one, and jobs locked on it would be claimed on the new
// one, so it only changes with a restart.
Expand Down Expand Up @@ -60,7 +71,7 @@

try {
const configPath = getConfigFilePath()
const configContent = await fs.promises.readFile(configPath, 'utf-8')

Check warning on line 74 in src/components/core/admin/pushConfigHandler.ts

View workflow job for this annotation

GitHub Actions / lint

Found readFile from package "fs" with non literal argument at index 0
const currentConfig = JSON.parse(configContent)

const mergedConfig = { ...currentConfig, ...task.config }
Expand Down Expand Up @@ -99,7 +110,7 @@
private async saveConfigToFile(config: Record<string, any>): Promise<void> {
const configPath = getConfigFilePath()
const content = JSON.stringify(config, null, 4)
await fs.promises.writeFile(configPath, content, 'utf-8')

Check warning on line 113 in src/components/core/admin/pushConfigHandler.ts

View workflow job for this annotation

GitHub Actions / lint

Found writeFile from package "fs" with non literal argument at index 0
CORE_LOGGER.debug(`Config saved to: ${configPath}`)
}
}
6 changes: 4 additions & 2 deletions src/components/core/service/startService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
ComputeEnvironment,
DBComputeJobPayment as Payment
} from '../../../@types/C2D/C2D.js'
import { DEFAULT_SERVICE_HOST_PORT_RANGE } from '../../../@types/C2D/ServiceOnDemand.js'
import { generateUniqueID, validateOutputBucket } from '../compute/utils.js'
import { validateAccess } from '../compute/startCompute.js'
import { isJobMetadataSizeValid, INVALID_JOB_METADATA_MESSAGE } from '../../c2d/index.js'
Expand Down Expand Up @@ -229,8 +230,9 @@ export class ServiceStartHandler extends CommandHandler {
task.exposedPorts
)
if (requestedHostPorts) {
const range = engine.getC2DConfig().connection?.serviceOnDemand
?.hostPortRange ?? [30000, 32767]
const range =
engine.getC2DConfig().connection?.serviceOnDemand?.hostPortRange ??
DEFAULT_SERVICE_HOST_PORT_RANGE
for (const hp of Object.values(requestedHostPorts)) {
if (!portInRange(hp, range))
return buildInvalidParametersResponse(
Expand Down
Loading
Loading