The OpenSandbox Kotlin SDK provides secure, isolated execution environments with comprehensive file system access, command execution, and resource management capabilities.
Installation
dependencies {
implementation("com.alibaba.opensandbox:sandbox:{latest_version}")
}
Core Classes
Sandbox
Main class for creating and managing sandbox instances.
Builder Methods
build()
Create a new sandbox instance using the builder pattern.
import com.alibaba.opensandbox.sandbox.Sandbox;
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import java.time.Duration;
ConnectionConfig config = ConnectionConfig.builder()
.domain("api.opensandbox.io")
.apiKey("your-api-key")
.build();
try (Sandbox sandbox = Sandbox.builder()
.connectionConfig(config)
.image("python:3.11")
.timeout(Duration.ofMinutes(30))
.resource(map -> {
map.put("cpu", "2");
map.put("memory", "4Gi");
})
.env("PYTHONPATH", "/workspace")
.build()) {
// Use sandbox
sandbox.commands().run("python script.py");
}
Connection configuration for API server.
timeout
Duration
default:"Duration.ofMinutes(10)"
Automatic termination timeout.
entrypoint
List<String>
default:"[\"tail\", \"-f\", \"/dev/null\"]"
Container entrypoint command.
resource
Map<String, String>
default:"{\"cpu\": \"1\", \"memory\": \"2Gi\"}"
CPU and memory limits.
Optional outbound network policy (egress).
readyTimeout
Duration
default:"Duration.ofSeconds(30)"
Maximum time to wait for sandbox to be ready.
healthCheck
Function<Sandbox, Boolean>
Custom health check function.
Fully configured and ready Sandbox instance.
Instance Methods
getInfo()
Get the current status of the sandbox.
SandboxInfo info = sandbox.getInfo();
System.out.println("State: " + info.getStatus().getState());
Current sandbox status including state and metadata.
getEndpoint()
Get a specific network endpoint for the sandbox.
SandboxEndpoint endpoint = sandbox.getEndpoint(80);
System.out.println("Endpoint: " + endpoint.getEndpoint());
The port number to get the endpoint for.
Endpoint information including connection details.
renew()
Renew the sandbox expiration time.
sandbox.renew(Duration.ofMinutes(30));
Duration to add to the current time to set the new expiration.
Method completes when renewal is successful.
pause()
Pause the sandbox while preserving its state.
Method completes when sandbox is paused.
resume()
Resume a previously paused sandbox.
Method completes when sandbox is resumed.
kill()
Terminate the remote sandbox instance.
Method completes when sandbox is terminated.
close()
Close local resources associated with the sandbox.
Method completes when resources are closed.
Properties
commands()
Provides access to command execution operations.
Execution execution = sandbox.commands().run("echo 'Hello World'");
System.out.println(execution.getLogs().getStdout().get(0).getText());
Command execution interface.
files()
Provides access to file system operations.
sandbox.files().write(List.of(
WriteEntry.builder()
.path("/tmp/hello.txt")
.data("Hello World")
.mode(644)
.build()
));
String content = sandbox.files().readFile("/tmp/hello.txt", "UTF-8", null);
File system operations interface.
SandboxManager
Administrative interface for managing multiple sandbox instances.
Builder Methods
build()
Create a SandboxManager instance.
import com.alibaba.opensandbox.sandbox.SandboxManager;
SandboxManager manager = SandboxManager.builder()
.connectionConfig(config)
.build();
Connection configuration.
Configured sandbox manager instance.
Instance Methods
listSandboxInfos()
List sandboxes with filtering options.
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.SandboxState;
PagedSandboxInfos sandboxes = manager.listSandboxInfos(
SandboxFilter.builder()
.states(SandboxState.RUNNING)
.pageSize(10)
.page(1)
.build()
);
sandboxes.getSandboxInfos().forEach(info ->
System.out.println("Found sandbox: " + info.getId())
);
Filter criteria for sandbox listing.
Paged sandbox information matching the filter criteria.
killSandbox()
Terminate a single sandbox.
manager.killSandbox("sandbox-id");
Method completes when sandbox is terminated.
close()
Close local resources associated with the manager.
Method completes when resources are closed.
Service Interfaces
Commands
Command execution service for sandbox environments.
run()
Execute a shell command in the sandbox.
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution;
import com.alibaba.opensandbox.sandbox.domain.models.execd.ExecutionHandlers;
// Simple execution
Execution execution = sandbox.commands().run("echo 'Hello World'");
System.out.println(execution.getLogs().getStdout().get(0).getText());
// With handlers
ExecutionHandlers handlers = ExecutionHandlers.builder()
.onStdout(msg -> System.out.println("STDOUT: " + msg.getText()))
.onStderr(msg -> System.err.println("STDERR: " + msg.getText()))
.onExecutionComplete(complete ->
System.out.println("Command finished in " + complete.getExecutionTimeInMillis() + "ms")
)
.build();
RunCommandRequest request = RunCommandRequest.builder()
.command("for i in {1..5}; do echo \"Count $i\"; sleep 0.5; done")
.handlers(handlers)
.build();
sandbox.commands().run(request);
Shell command text to execute.
Command request with options and handlers.
Execution handle representing the running command.
Filesystem
Filesystem operations service for sandbox environments.
readFile()
Read the content of a file as a string.
String content = sandbox.files().readFile("/tmp/hello.txt", "UTF-8", null);
System.out.println("Content: " + content);
The absolute or relative path to the file to read.
Character encoding for the file content.
HTTP byte range to read (e.g., “bytes=0-1023”).
The file content as a string.
write()
Write content to files.
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.WriteEntry;
sandbox.files().write(List.of(
WriteEntry.builder()
.path("/tmp/hello.txt")
.data("Hello World")
.mode(644)
.build()
));
List of write entries specifying files and their content.
Method completes when files are written.
deleteFiles()
Delete the specified files.
sandbox.files().deleteFiles(List.of("/tmp/hello.txt"));
List of file paths to delete.
Method completes when files are deleted.
search()
Search for files and directories.
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.SearchEntry;
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.EntryInfo;
List<EntryInfo> files = sandbox.files().search(
SearchEntry.builder()
.path("/tmp")
.pattern("*.txt")
.build()
);
files.forEach(f -> System.out.println("Found: " + f.getPath()));
Search entry containing search parameters and criteria.
List of matching file/directory information.
Configuration
ConnectionConfig
Connection configuration for API server communication.
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import okhttp3.ConnectionPool;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
// Basic configuration
ConnectionConfig config = ConnectionConfig.builder()
.apiKey("your-key")
.domain("api.opensandbox.io")
.requestTimeout(Duration.ofSeconds(60))
.build();
// Advanced: Shared Connection Pool
ConnectionPool sharedPool = new ConnectionPool(50, 30, TimeUnit.SECONDS);
ConnectionConfig sharedConfig = ConnectionConfig.builder()
.apiKey("your-key")
.domain("api.opensandbox.io")
.connectionPool(sharedPool)
.build();
API Key for authentication (can also be set via OPEN_SANDBOX_API_KEY environment variable).
The endpoint domain of the sandbox service (can also be set via OPEN_SANDBOX_DOMAIN environment variable).
HTTP protocol (http/https).
requestTimeout
Duration
default:"Duration.ofSeconds(30)"
Timeout for API requests.
Enable debug logging for HTTP requests.
Shared OKHttp ConnectionPool.
Use sandbox server as proxy for execd/endpoint requests.
Network Policy
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.NetworkPolicy;
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.NetworkRule;
Sandbox sandbox = Sandbox.builder()
.connectionConfig(config)
.image("python:3.11")
.networkPolicy(
NetworkPolicy.builder()
.defaultAction(NetworkPolicy.DefaultAction.DENY)
.addEgress(
NetworkRule.builder()
.action(NetworkRule.Action.ALLOW)
.target("pypi.org")
.build()
)
.build()
)
.build();
Complete Example
import com.alibaba.opensandbox.sandbox.Sandbox;
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxException;
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution;
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.WriteEntry;
import java.time.Duration;
import java.util.List;
public class Example {
public static void main(String[] args) {
ConnectionConfig config = ConnectionConfig.builder()
.domain("api.opensandbox.io")
.apiKey("your-api-key")
.build();
try (Sandbox sandbox = Sandbox.builder()
.connectionConfig(config)
.image("python:3.11")
.timeout(Duration.ofMinutes(30))
.build()) {
// Write a file
sandbox.files().write(List.of(
WriteEntry.builder()
.path("/tmp/script.py")
.data("print('Hello World')")
.mode(644)
.build()
));
// Execute command
Execution execution = sandbox.commands().run("python /tmp/script.py");
System.out.println(execution.getLogs().getStdout().get(0).getText());
// Get info
SandboxInfo info = sandbox.getInfo();
System.out.println("State: " + info.getStatus().getState());
// Cleanup
sandbox.kill();
} catch (SandboxException e) {
System.err.println("Sandbox Error: [" + e.getError().getCode() + "] " + e.getError().getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}