Installation
Gradle (Kotlin DSL)
Maven
dependencies {
implementation ( "com.alibaba.opensandbox:sandbox:{latest_version}" )
}
< dependency >
< groupId > com.alibaba.opensandbox </ groupId >
< artifactId > sandbox </ artifactId >
< version > {latest_version} </ version >
</ dependency >
Quick Start
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;
public class QuickStart {
public static void main ( String [] args ) {
// 1. Configure connection
ConnectionConfig config = ConnectionConfig . builder ()
. domain ( "api.opensandbox.io" )
. apiKey ( "your-api-key" )
. build ();
// 2. Create a Sandbox using try-with-resources
try ( Sandbox sandbox = Sandbox . builder ()
. connectionConfig (config)
. image ( "ubuntu" )
. build ()) {
// 3. Execute a shell command
Execution execution = sandbox
. commands ()
. run ( "echo 'Hello Sandbox!'" );
// 4. Print output
System . out . println ( execution . getLogs (). getStdout (). get ( 0 ). getText ());
// 5. Cleanup (sandbox.close() called automatically)
// Note: kill() must be called explicitly if you want to terminate
// the remote sandbox instance immediately
sandbox . kill ();
} catch ( SandboxException e ) {
// Handle Sandbox specific exceptions
System . err . println ( "Sandbox Error: [" + e . getError (). getCode () + "] "
+ e . getError (). getMessage ());
} catch ( Exception e ) {
e . printStackTrace ();
}
}
}
Core Features
Lifecycle Management
Manage the sandbox lifecycle, including renewal, pausing, and resuming.
import java.time.Duration;
// Renew the sandbox
// This resets the expiration time to (current time + duration)
sandbox . renew ( Duration . ofMinutes ( 30 ));
// Pause execution (suspends all processes)
sandbox . pause ();
// Resume execution
sandbox . resume ();
// Get current status
SandboxInfo info = sandbox . getInfo ();
System . out . println ( "State: " + info . getStatus (). getState ());
Custom Health Check
Define custom logic to determine if the sandbox is healthy. This overrides the default ping check.
Sandbox sandbox = Sandbox . builder ()
. connectionConfig (config)
. image ( "nginx:latest" )
// Custom check: Wait for port 80 to be accessible
. healthCheck (sbx -> {
try {
// 1. Get the external mapped address for port 80
SandboxEndpoint endpoint = sbx . getEndpoint ( 80 );
// 2. Perform your connection check (e.g. HTTP request, Socket connect)
// return checkConnection(endpoint.getEndpoint());
return true ;
} catch ( Exception e ) {
return false ;
}
})
. build ();
Command Execution & Streaming
Execute commands and handle output streams in real-time.
import com.alibaba.opensandbox.sandbox.domain.models.execd.ExecutionHandlers;
import com.alibaba.opensandbox.sandbox.domain.models.execd.RunCommandRequest;
// Create handlers for streaming output
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 ();
// Execute command with handlers
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);
File Operations
Manage files and directories, including read, write, list, delete, and search.
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.WriteEntry;
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.SearchEntry;
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.EntryInfo;
import java.util.List;
// 1. Write file
sandbox . files (). write ( List . of (
WriteEntry . builder ()
. path ( "/tmp/hello.txt" )
. data ( "Hello World" )
. mode ( 644 )
. build ()
));
// 2. Read file
String content = sandbox . files (). readFile ( "/tmp/hello.txt" , "UTF-8" , null );
System . out . println ( "Content: " + content);
// 3. List/Search files
List < EntryInfo > files = sandbox . files (). search (
SearchEntry . builder ()
. path ( "/tmp" )
. pattern ( "*.txt" )
. build ()
);
files . forEach (f -> System . out . println ( "Found: " + f . getPath ()));
// 4. Delete file
sandbox . files (). deleteFiles ( List . of ( "/tmp/hello.txt" ));
Sandbox Management (Admin)
Use SandboxManager for administrative tasks and finding existing sandboxes.
import com.alibaba.opensandbox.sandbox.SandboxManager;
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.SandboxState;
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.SandboxFilter;
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.PagedSandboxInfos;
SandboxManager manager = SandboxManager . builder ()
. connectionConfig (config)
. build ();
// List running sandboxes
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 ());
// Perform admin actions
manager . killSandbox ( info . getId ());
});
// Try-with-resources will automatically call manager.close()
// manager.close();
Configuration
Connection Configuration
The ConnectionConfig class manages API server connection settings.
Parameter Description Default Environment Variable apiKeyAPI Key for authentication Required OPEN_SANDBOX_API_KEYdomainThe endpoint domain of the sandbox service Required (or localhost:8080) OPEN_SANDBOX_DOMAINprotocolHTTP protocol (http/https) http- requestTimeoutTimeout for API requests 30 seconds - debugEnable debug logging for HTTP requests false- headersCustom HTTP headers Empty - connectionPoolShared OKHttp ConnectionPool SDK-created per instance - useServerProxyUse sandbox server as proxy for execd/endpoint requests false-
import java.time.Duration;
ConnectionConfig config = ConnectionConfig . builder ()
. apiKey ( "your-key" )
. domain ( "api.opensandbox.io" )
. requestTimeout ( Duration . ofSeconds ( 60 ))
. build ();
import okhttp3.ConnectionPool;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
// Shared Connection Pool
// If you create many Sandbox instances, sharing a connection pool
// is recommended to save resources.
ConnectionPool sharedPool = new ConnectionPool ( 50 , 30 , TimeUnit . SECONDS );
ConnectionConfig sharedConfig = ConnectionConfig . builder ()
. apiKey ( "your-key" )
. domain ( "api.opensandbox.io" )
. connectionPool (sharedPool) // Inject shared pool
. build ();
Sandbox Creation Configuration
The Sandbox.builder() allows configuring the sandbox environment.
Parameter Description Default imageDocker image to use Required timeoutAutomatic termination timeout 10 minutes entrypointContainer entrypoint command ["tail", "-f", "/dev/null"]resourceCPU and memory limits {"cpu": "1", "memory": "2Gi"}envEnvironment variables Empty metadataCustom metadata tags Empty networkPolicyOptional outbound network policy (egress) - readyTimeoutMax time to wait for sandbox to be ready 30 seconds
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.NetworkPolicy;
import com.alibaba.opensandbox.sandbox.domain.models.sandboxes.NetworkRule;
import java.time.Duration;
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" , "/app" )
. metadata ( "project" , "demo" )
. networkPolicy (
NetworkPolicy . builder ()
. defaultAction ( NetworkPolicy . DefaultAction . DENY )
. addEgress (
NetworkRule . builder ()
. action ( NetworkRule . Action . ALLOW )
. target ( "pypi.org" )
. build ()
)
. build ()
)
. build ();
API Reference
Sandbox
Main class for interacting with sandboxes.
Methods
Returns a builder for creating a new sandbox instance. Returns: Sandbox.Builder
Access to command execution operations. Returns: CommandsClient
Access to file system operations. Returns: FilesClient
Extends the sandbox expiration time. Parameters:
duration (Duration): Extension duration
Pauses the sandbox (suspends all processes).
Resumes the paused sandbox.
Terminates the sandbox immediately.
Retrieves current sandbox information. Returns: SandboxInfo
Gets the external endpoint for a port. Parameters:
port (int): Internal port number
Returns: SandboxEndpoint
Implements AutoCloseable for try-with-resources.
Examples
Running a Java Application
import com.alibaba.opensandbox.sandbox.domain.models.filesystem.WriteEntry;
// Write a Java file
sandbox . files (). write ( List . of (
WriteEntry . builder ()
. path ( "/app/Hello.java" )
. data ( """
public class Hello {
public static void main(String[] args) {
System.out.println("Hello from OpenSandbox!");
System.out.println("Java version: " + System.getProperty("java.version"));
}
}
""" )
. mode ( 644 )
. build ()
));
// Compile and run
sandbox . commands (). run ( "javac /app/Hello.java" );
Execution execution = sandbox . commands (). run ( "java -cp /app Hello" );
execution . getLogs (). getStdout (). forEach (line ->
System . out . println ( line . getText ())
);
Network Policy Example
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 ( "maven:3.9-eclipse-temurin-17" )
. networkPolicy (
NetworkPolicy . builder ()
. defaultAction ( NetworkPolicy . DefaultAction . DENY )
. addEgress (
NetworkRule . builder ()
. action ( NetworkRule . Action . ALLOW )
. target ( "repo.maven.apache.org" )
. build ()
)
. build ()
)
. build ();
Port Forwarding
// Start a web server in the sandbox
sandbox . commands (). run (
"java -jar /app/server.jar" ,
RunCommandRequest . builder ()
. background ( true )
. build ()
);
// Get the external endpoint
SandboxEndpoint endpoint = sandbox . getEndpoint ( 8080 );
System . out . println ( "Access your server at: http://" + endpoint . getEndpoint ());
Error Handling
import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxException;
import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxNotFoundException;
import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxTimeoutException;
try {
Sandbox sandbox = Sandbox . builder ()
. connectionConfig (config)
. image ( "ubuntu" )
. build ();
Execution execution = sandbox . commands (). run ( "ls -la" );
} catch ( SandboxTimeoutException e ) {
System . err . println ( "Timeout: " + e . getError (). getMessage ());
} catch ( SandboxNotFoundException e ) {
System . err . println ( "Not found: " + e . getError (). getMessage ());
} catch ( SandboxException e ) {
System . err . println ( "Error [" + e . getError (). getCode () + "]: "
+ e . getError (). getMessage ());
}
Next Steps
Python SDK Explore the Python SDK
API Reference Detailed API documentation
Examples Browse more code examples