Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,30 @@ public async IAsyncEnumerable<ServerStreamEvent> RunStreamAsync(
RunCommandOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (options?.Gid.HasValue == true && options.Uid.HasValue != true)
{
throw new InvalidArgumentException("uid is required when gid is provided");
}
if (options?.Uid.HasValue == true && options.Uid.Value < 0)
{
throw new InvalidArgumentException("uid must be >= 0");
}
if (options?.Gid.HasValue == true && options.Gid.Value < 0)
{
throw new InvalidArgumentException("gid must be >= 0");
}

var url = $"{_baseUrl}/command";
_logger.LogDebug("Running command stream (commandLength={CommandLength})", command.Length);
var requestBody = new RunCommandRequest
{
Command = command,
Cwd = options?.WorkingDirectory,
Background = options?.Background,
Timeout = options?.TimeoutSeconds.HasValue == true ? options.TimeoutSeconds.Value * 1000L : null
Timeout = options?.TimeoutSeconds.HasValue == true ? options.TimeoutSeconds.Value * 1000L : null,
Uid = options?.Uid,
Gid = options?.Gid,
Envs = options?.Envs
};

var json = JsonSerializer.Serialize(requestBody, JsonOptions);
Expand Down
35 changes: 35 additions & 0 deletions sdks/sandbox/csharp/src/OpenSandbox/Models/Execd.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,25 @@ public class RunCommandRequest
/// </summary>
[JsonPropertyName("timeout")]
public long? Timeout { get; set; }

/// <summary>
/// Gets or sets the Unix user ID used to run the command process.
/// </summary>
[JsonPropertyName("uid")]
public int? Uid { get; set; }

/// <summary>
/// Gets or sets the Unix group ID used to run the command process.
/// Requires <see cref="Uid"/> to be set.
/// </summary>
[JsonPropertyName("gid")]
public int? Gid { get; set; }

/// <summary>
/// Gets or sets environment variables injected into the command process.
/// </summary>
[JsonPropertyName("envs")]
public Dictionary<string, string>? Envs { get; set; }
}

/// <summary>
Expand All @@ -155,6 +174,22 @@ public class RunCommandOptions
/// The server terminates the command when this duration is reached.
/// </summary>
public int? TimeoutSeconds { get; set; }

/// <summary>
/// Gets or sets the Unix user ID used to run the command process.
/// </summary>
public int? Uid { get; set; }

/// <summary>
/// Gets or sets the Unix group ID used to run the command process.
/// Requires <see cref="Uid"/> to be set.
/// </summary>
public int? Gid { get; set; }

/// <summary>
/// Gets or sets environment variables injected into the command process.
/// </summary>
public Dictionary<string, string>? Envs { get; set; }
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using System.Text.Json;
using FluentAssertions;
using OpenSandbox.Adapters;
using OpenSandbox.Core;
using OpenSandbox.Internal;
using OpenSandbox.Models;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -116,6 +117,70 @@ public async Task RunStreamAsync_ShouldSendTimeoutInMilliseconds()
}
}

[Fact]
public async Task RunStreamAsync_ShouldSendUidGidAndEnvs()
{
var handler = new StubHttpMessageHandler(async (request, _) =>
{
request.Content.Should().NotBeNull();
var body = await request.Content!.ReadAsStringAsync().ConfigureAwait(false);
using var doc = JsonDocument.Parse(body);
doc.RootElement.GetProperty("uid").GetInt32().Should().Be(1000);
doc.RootElement.GetProperty("gid").GetInt32().Should().Be(1000);
var envs = doc.RootElement.GetProperty("envs");
envs.GetProperty("APP_ENV").GetString().Should().Be("test");
envs.GetProperty("LOG_LEVEL").GetString().Should().Be("debug");

return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("data: {\"type\":\"init\",\"text\":\"cmd-1\"}\n\n", Encoding.UTF8, "text/event-stream")
};
});
var adapter = CreateAdapter(handler);

var options = new RunCommandOptions
{
Uid = 1000,
Gid = 1000,
Envs = new Dictionary<string, string>
{
["APP_ENV"] = "test",
["LOG_LEVEL"] = "debug"
}
};

await foreach (var _ in adapter.RunStreamAsync("id", options))
{
// Drain events.
}
}

[Fact]
public async Task RunStreamAsync_ShouldRejectGidWithoutUid()
{
var handler = new StubHttpMessageHandler((_, _) =>
{
throw new InvalidOperationException("HTTP should not be called when options are invalid.");
});
var adapter = CreateAdapter(handler);

var options = new RunCommandOptions
{
Gid = 1000
};

var act = async () =>
{
await foreach (var _ in adapter.RunStreamAsync("id", options))
{
// Drain events.
}
};

await act.Should().ThrowAsync<InvalidArgumentException>()
.WithMessage("*uid is required when gid is provided*");
}

private static CommandsAdapter CreateAdapter(HttpMessageHandler httpHandler)
{
var baseUrl = "http://execd.local";
Expand Down
11 changes: 10 additions & 1 deletion sdks/sandbox/csharp/tests/OpenSandbox.Tests/ModelsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,22 @@ public void RunCommandOptions_ShouldStoreProperties()
{
WorkingDirectory = "/home/user",
Background = true,
TimeoutSeconds = 30
TimeoutSeconds = 30,
Uid = 1000,
Gid = 1000,
Envs = new Dictionary<string, string>
{
["APP_ENV"] = "test"
}
};

// Assert
options.WorkingDirectory.Should().Be("/home/user");
options.Background.Should().BeTrue();
options.TimeoutSeconds.Should().Be(30);
options.Uid.Should().Be(1000);
options.Gid.Should().Be(1000);
options.Envs.Should().ContainKey("APP_ENV");
}

[Fact]
Expand Down
20 changes: 19 additions & 1 deletion sdks/sandbox/javascript/src/adapters/commandsAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,38 @@ function joinUrl(baseUrl: string, pathname: string): string {

type ApiRunCommandRequest =
ExecdPaths["/command"]["post"]["requestBody"]["content"]["application/json"];
type ApiRunCommandRequestWithExtensions = ApiRunCommandRequest & {
uid?: number;
gid?: number;
envs?: Record<string, string>;
};
type ApiCommandStatusOk =
ExecdPaths["/command/status/{id}"]["get"]["responses"][200]["content"]["application/json"];
type ApiCommandLogsOk =
ExecdPaths["/command/{id}/logs"]["get"]["responses"][200]["content"]["text/plain"];

function toRunCommandRequest(command: string, opts?: RunCommandOpts): ApiRunCommandRequest {
const body: ApiRunCommandRequest = {
if (opts?.gid != null && opts.uid == null) {
throw new Error("uid is required when gid is provided");
}

const body: ApiRunCommandRequestWithExtensions = {
command,
cwd: opts?.workingDirectory,
background: !!opts?.background,
};
if (opts?.timeoutSeconds != null) {
body.timeout = Math.round(opts.timeoutSeconds * 1000);
}
if (opts?.uid != null) {
body.uid = opts.uid;
}
if (opts?.gid != null) {
body.gid = opts.gid;
}
if (opts?.envs != null) {
body.envs = opts.envs;
}
return body;
}

Expand Down
12 changes: 12 additions & 0 deletions sdks/sandbox/javascript/src/models/execd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ export interface RunCommandOpts {
* If omitted, the server will not enforce any timeout.
*/
timeoutSeconds?: number;
/**
* Unix user ID used to run the command process.
*/
uid?: number;
/**
* Unix group ID used to run the command process. Requires `uid`.
*/
gid?: number;
/**
* Environment variables injected into the command process.
*/
envs?: Record<string, string>;
}

export interface CommandStatus {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,19 @@ import kotlin.time.Duration
* @property background Whether to run in background (detached)
* @property workingDirectory Directory to execute command in
* @property timeout Maximum execution time; server will terminate when reached. Null means the server will not enforce any timeout.
* @property uid Unix user ID used to run the command process
* @property gid Unix group ID used to run the command process. Requires uid.
* @property envs Environment variables injected into the command process
* @property handlers Optional execution handlers
*/
class RunCommandRequest private constructor(
val command: String,
val background: Boolean,
val workingDirectory: String?,
val timeout: Duration?,
val uid: Int?,
val gid: Int?,
val envs: Map<String, String>,
val handlers: ExecutionHandlers?,
) {
companion object {
Expand All @@ -44,6 +50,9 @@ class RunCommandRequest private constructor(
private var background: Boolean = false
private var workingDirectory: String? = null
private var timeout: Duration? = null
private var uid: Int? = null
private var gid: Int? = null
private val envs: MutableMap<String, String> = mutableMapOf()
private var handlers: ExecutionHandlers? = null

fun command(command: String): Builder {
Expand Down Expand Up @@ -71,18 +80,51 @@ class RunCommandRequest private constructor(
return this
}

fun uid(uid: Int?): Builder {
require(uid == null || uid >= 0) { "Uid must be >= 0" }
this.uid = uid
return this
}

fun gid(gid: Int?): Builder {
require(gid == null || gid >= 0) { "Gid must be >= 0" }
this.gid = gid
return this
}

fun env(
key: String,
value: String,
): Builder {
require(key.isNotBlank()) { "Environment variable key cannot be blank" }
this.envs[key] = value
return this
}

fun envs(envs: Map<String, String>): Builder {
envs.keys.forEach { key ->
require(key.isNotBlank()) { "Environment variable key cannot be blank" }
}
this.envs.putAll(envs)
return this
}

fun handlers(handlers: ExecutionHandlers?): Builder {
this.handlers = handlers
return this
}

fun build(): RunCommandRequest {
val commandValue = command ?: throw IllegalArgumentException("Command must be specified")
require(gid == null || uid != null) { "Uid is required when gid is provided" }
return RunCommandRequest(
command = commandValue,
background = background,
workingDirectory = workingDirectory,
timeout = timeout,
uid = uid,
gid = gid,
envs = envs.toMap(),
handlers = handlers,
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,33 @@ package com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.CommandStatus
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.RunCommandRequest
import com.alibaba.opensandbox.sandbox.api.models.execd.CommandStatusResponse as ApiCommandStatusResponse
import com.alibaba.opensandbox.sandbox.api.models.execd.RunCommandRequest as ApiRunCommandRequest
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

object ExecutionConverter {
fun RunCommandRequest.toApiRunCommandRequest(): ApiRunCommandRequest {
return ApiRunCommandRequest(
command = command,
background = background,
cwd = workingDirectory,
timeout = timeout?.inWholeMilliseconds,
)
fun RunCommandRequest.toApiRunCommandPayload(): JsonObject {
return buildJsonObject {
put("command", JsonPrimitive(command))
if (background) {
put("background", JsonPrimitive(background))
}
workingDirectory?.let { put("cwd", JsonPrimitive(it)) }
timeout?.let { put("timeout", JsonPrimitive(it.inWholeMilliseconds)) }
uid?.let { put("uid", JsonPrimitive(it)) }
gid?.let { put("gid", JsonPrimitive(it)) }
if (envs.isNotEmpty()) {
put(
"envs",
buildJsonObject {
envs.forEach { (key, value) ->
put(key, JsonPrimitive(value))
}
},
)
}
}
}

fun ApiCommandStatusResponse.toCommandStatus(): CommandStatus {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.RunCommandRequest
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.SandboxEndpoint
import com.alibaba.opensandbox.sandbox.domain.services.Commands
import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.ExecutionConverter.toApiRunCommandRequest
import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.ExecutionConverter.toApiRunCommandPayload
import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.ExecutionConverter.toCommandStatus
import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.ExecutionEventDispatcher
import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.jsonParser
Expand Down Expand Up @@ -85,7 +85,7 @@ internal class CommandsAdapter(
Request.Builder()
.url("${httpClientProvider.config.protocol}://${execdEndpoint.endpoint}$RUN_COMMAND_PATH")
.post(
jsonParser.encodeToString(request.toApiRunCommandRequest()).toRequestBody("application/json".toMediaType()),
jsonParser.encodeToString(request.toApiRunCommandPayload()).toRequestBody("application/json".toMediaType()),
)
.headers(execdEndpoint.headers.toHeaders())
.build()
Expand Down
Loading