Skip to content
Closed
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
8 changes: 8 additions & 0 deletions images/container-client-test/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ const server = createServer(function (req, res) {
return;
}

// Endpoint to get the PID of the current process
if (req.url === '/pid') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write(String(process.pid));
res.end();
return;
}

res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Hello World!');
res.end();
Expand Down
20 changes: 16 additions & 4 deletions src/workerd/api/container.c++
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,28 @@ void Container::start(jsg::Lock& js, jsg::Optional<StartupOptions> maybeOptions)
}
}

IoContext::current().addTask(req.sendIgnoringResult());

running = true;

if (flags.getWorkerdExperimental()) {
KJ_IF_SOME(hardTimeoutMs, options.hardTimeout) {
JSG_REQUIRE(hardTimeoutMs > 0, RangeError, "Hard timeout must be greater than 0");
req.setHardTimeoutMs(hardTimeoutMs);
}

auto& hostNamespaces = options.hostNamespaces.orDefault(kj::arr(kj::str("pid")));
auto list = req.initHostNamespaces(hostNamespaces.size());
for (auto i: kj::indices(hostNamespaces)) {
auto& ns = hostNamespaces[i];
if (ns == "pid") {
list.set(i, rpc::Container::StartParams::Namespace::PID);
} else {
JSG_FAIL_REQUIRE(
TypeError, "Invalid hostNamespace value: \"", ns, "\". Valid values are: \"pid\"");
}
}
}

IoContext::current().addTask(req.sendIgnoringResult());

running = true;
}

jsg::Promise<void> Container::setInactivityTimeout(jsg::Lock& js, int64_t durationMs) {
Expand Down
5 changes: 4 additions & 1 deletion src/workerd/api/container.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,19 @@ class Container: public jsg::Object {
bool enableInternet = false;
jsg::Optional<jsg::Dict<kj::String>> env;
jsg::Optional<int64_t> hardTimeout;
jsg::Optional<kj::Array<kj::String>> hostNamespaces;

// TODO(containers): Allow intercepting stdin/stdout/stderr by specifying streams here.

JSG_STRUCT(entrypoint, enableInternet, env, hardTimeout);
JSG_STRUCT(entrypoint, enableInternet, env, hardTimeout, hostNamespaces);
JSG_STRUCT_TS_OVERRIDE_DYNAMIC(CompatibilityFlags::Reader flags) {
if (flags.getWorkerdExperimental()) {
JSG_TS_OVERRIDE(ContainerStartupOptions {
entrypoint?: string[];
enableInternet: boolean;
env?: Record<string, string>;
hardTimeout?: number | bigint;
hostNamespaces?: HostNamespace[];
});
} else {
JSG_TS_OVERRIDE(ContainerStartupOptions {
Expand Down Expand Up @@ -73,6 +75,7 @@ class Container: public jsg::Object {
JSG_METHOD(signal);
JSG_METHOD(getTcpPort);
JSG_METHOD(setInactivityTimeout);
JSG_TS_DEFINE(type HostNamespace = "pid");
}

void visitForMemoryInfo(jsg::MemoryTracker& tracker) const {
Expand Down
9 changes: 9 additions & 0 deletions src/workerd/io/container.capnp
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ interface Container @0x9aaceefc06523bca {
# The container will be forcefully terminated when this timeout expires, regardless of activity.
# Unlike inactivity timeout, this is a hard deadline from container startup.
# If 0 (default), no hard timeout is applied.

hostNamespaces @4 :List(Namespace);
# Configure which namespaces to share with the host

enum Namespace {
pid @0;
# Sharing the host PID namespace will make processes running outside of
# the container visible inside of the container.
}
}

monitor @2 () -> (exitCode: Int32);
Expand Down
13 changes: 11 additions & 2 deletions src/workerd/server/container-client.c++
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,8 @@ kj::Promise<ContainerClient::InspectResponse> ContainerClient::inspectContainer(

kj::Promise<void> ContainerClient::createContainer(
kj::Maybe<capnp::List<capnp::Text>::Reader> entrypoint,
kj::Maybe<capnp::List<capnp::Text>::Reader> environment) {
kj::Maybe<capnp::List<capnp::Text>::Reader> environment,
capnp::List<rpc::Container::StartParams::Namespace>::Reader hostNamespaces) {
// Docker API: POST /containers/create
capnp::JsonCodec codec;
codec.handleByAnnotation<docker_api::Docker::ContainerCreateRequest>();
Expand Down Expand Up @@ -300,6 +301,14 @@ kj::Promise<void> ContainerClient::createContainer(
// We need to set a restart policy to avoid having ambiguous states
// where the container we're managing is stuck at "exited" state.
hostConfig.initRestartPolicy().setName("on-failure");
// Configure host namespace sharing
for (auto ns: hostNamespaces) {
switch (ns) {
case rpc::Container::StartParams::Namespace::PID:
hostConfig.setPidMode("host");
break;
}
}

auto response = co_await dockerApiRequest(network, kj::str(dockerPath), kj::HttpMethod::POST,
kj::str("/containers/create?name=", containerName), codec.encode(jsonRoot));
Expand Down Expand Up @@ -397,7 +406,7 @@ kj::Promise<void> ContainerClient::start(StartContext context) {
environment = params.getEnvironmentVariables();
}

co_await createContainer(entrypoint, environment);
co_await createContainer(entrypoint, environment, params.getHostNamespaces());
co_await startContainer();
}

Expand Down
3 changes: 2 additions & 1 deletion src/workerd/server/container-client.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ class ContainerClient final: public rpc::Container::Server, public kj::Refcounte
kj::Maybe<kj::String> body = kj::none);
kj::Promise<InspectResponse> inspectContainer();
kj::Promise<void> createContainer(kj::Maybe<capnp::List<capnp::Text>::Reader> entrypoint,
kj::Maybe<capnp::List<capnp::Text>::Reader> environment);
kj::Maybe<capnp::List<capnp::Text>::Reader> environment,
capnp::List<rpc::Container::StartParams::Namespace>::Reader hostNamespaces);
kj::Promise<void> startContainer();
kj::Promise<void> stopContainer();
kj::Promise<void> killContainer(uint32_t signal);
Expand Down
82 changes: 82 additions & 0 deletions src/workerd/server/tests/container-client/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,70 @@ export class DurableObjectExample extends DurableObject {
getStatus() {
return this.ctx.container.running;
}

async testHostNamespaces() {
const container = this.ctx.container;
if (container.running) {
let monitor = container.monitor().catch((_err) => {});
await container.destroy();
await monitor;
}
assert.strictEqual(container.running, false);

// Test with valid hostNamespaces - should share host PID namespace
container.start({
hostNamespaces: ['pid'],
});

assert.strictEqual(container.running, true);

// Verify the container process is NOT PID 1 (indicating host PID namespace is shared)
let resp;
const maxRetries = 6;
for (let i = 1; i <= maxRetries; i++) {
try {
resp = await container.getTcpPort(8080).fetch('http://foo/pid');
break;
} catch (e) {
if (!e.message.includes('container port not found')) {
throw e;
}
if (i === maxRetries) {
throw e;
}
await scheduler.wait(500);
}
}

assert.strictEqual(resp.status, 200);
const pid = parseInt(await resp.text(), 10);

// With host PID namespace, the entrypoint process should NOT be PID 1
assert.notStrictEqual(
pid,
1,
'Expected pid != 1 when host PID namespace is shared'
);

await container.destroy();
}

async testHostNamespacesInvalid() {
const container = this.ctx.container;
if (container.running) {
let monitor = container.monitor().catch((_err) => {});
await container.destroy();
await monitor;
}
assert.strictEqual(container.running, false);

// Test with invalid hostNamespaces
assert.throws(() => {
container.start({
hostNamespaces: ['invalid'],
});
}, /Invalid hostNamespace value/);
}
}

export class DurableObjectExample2 extends DurableObjectExample {}
Expand Down Expand Up @@ -394,3 +458,21 @@ export const testSetInactivityTimeout = {
}
},
};

// Test hostNamespaces with valid value
export const testHostNamespaces = {
async test(_ctrl, env) {
const id = env.MY_CONTAINER.idFromName('testHostNamespaces');
const stub = env.MY_CONTAINER.get(id);
await stub.testHostNamespaces();
},
};

// Test hostNamespaces with invalid value
export const testHostNamespacesInvalid = {
async test(_ctrl, env) {
const id = env.MY_CONTAINER.idFromName('testHostNamespacesInvalid');
const stub = env.MY_CONTAINER.get(id);
await stub.testHostNamespacesInvalid();
},
};
Loading