Skip to content

Commit c2e2b97

Browse files
committed
add filesystem & example
1 parent d6864a5 commit c2e2b97

6 files changed

Lines changed: 862 additions & 0 deletions

File tree

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
package io.openkruise.agents.client.e2b.example;
2+
3+
import io.grpc.ManagedChannel;
4+
import io.openkruise.agents.client.e2b.config.ConnectionConfig;
5+
import io.openkruise.agents.client.e2b.sandbox.commands.CommandResult;
6+
import io.openkruise.agents.client.e2b.sandbox.commands.CommandHandle;
7+
import io.openkruise.agents.client.e2b.sandbox.commands.Commands;
8+
import io.openkruise.agents.client.e2b.sandbox.commands.Commands.RunOptions;
9+
import io.openkruise.agents.client.e2b.sandbox.commands.Commands.ProcessInfo;
10+
11+
import java.util.List;
12+
import java.util.HashMap;
13+
import java.util.Map;
14+
import java.util.function.Consumer;
15+
16+
public class CommandsExample {
17+
private static final String ACCESS_TOKEN = "sandbox-token";
18+
private static final String API_KEY = "key";
19+
private static final String SANDBOX_ID = "sandbox-id";
20+
private static final String SANDBOX_DOMAIN = "your.domain.com";
21+
22+
public void runHelloWorld() throws Exception {
23+
ConnectionConfig config = new ConnectionConfig.Builder()
24+
.accessToken(ACCESS_TOKEN)
25+
.apiKey(API_KEY)
26+
.domain(SANDBOX_DOMAIN)
27+
.debug(true)
28+
.requestTimeoutMs(30000)
29+
.build();
30+
31+
ManagedChannel channel = config.createChannel(SANDBOX_ID, SANDBOX_DOMAIN);
32+
33+
try {
34+
Commands commands = new Commands(channel, config);
35+
36+
System.out.println("=== Example 1: Execute Simple Command ===");
37+
CommandResult pwd = commands.run("pwd", new RunOptions().timeoutMs(10000));
38+
System.out.println("pwd command result: " + pwd);
39+
40+
System.out.println("\n=== Example 2: Execute Complex Command ===");
41+
CommandResult ls = commands.run("ls -la /tmp", new RunOptions().timeoutMs(10000));
42+
System.out.println("ls -la /tmp result: ");
43+
System.out.println(ls.getStdout());
44+
if (!ls.getStderr().isEmpty()) {
45+
System.out.println("Error output: " + ls.getStderr());
46+
}
47+
48+
System.out.println("\n=== Example 3: Execute Command With Environment Variables ===");
49+
Map<String, String> envs = new HashMap<>();
50+
envs.put("MY_VAR", "hello_world");
51+
RunOptions optionsWithEnv = new RunOptions()
52+
.envs(envs)
53+
.timeoutMs(10000);
54+
CommandResult envTest = commands.run("echo $MY_VAR", optionsWithEnv);
55+
System.out.println("Environment variable test result: " + envTest.getStdout().trim());
56+
57+
System.out.println("\n=== Example 4: Execute Background Command And Wait For Completion ===");
58+
CommandHandle bgHandle = commands.runBackground("sleep 3 && echo 'Background task completed'",
59+
new RunOptions().timeoutMs(10000));
60+
System.out.println("Background command PID: " + bgHandle.getPid());
61+
CommandResult bgResult = bgHandle.waitForCompletion();
62+
System.out.println("Background command result: " + bgResult.getStdout().trim());
63+
64+
System.out.println("\n=== Example 5: Execute Real-time Output Command ===");
65+
// Use callback function to handle output in real-time
66+
Consumer<String> stdoutHandler = output -> System.out.print("STDOUT: " + output);
67+
Consumer<String> stderrHandler = output -> System.out.print("STDERR: " + output);
68+
RunOptions realtimeOptions = new RunOptions()
69+
.onStdout(stdoutHandler)
70+
.onStderr(stderrHandler)
71+
.timeoutMs(15000);
72+
CommandResult realtimeResult = commands.run("for i in {1..5}; do echo \"Count: $i\"; sleep 1; done",
73+
realtimeOptions);
74+
System.out.println("\nReal-time output command completed");
75+
76+
System.out.println("\n=== Example 6: Execute Command Requiring Working Directory ===");
77+
RunOptions cwdOptions = new RunOptions()
78+
.cwd("/tmp")
79+
.timeoutMs(10000);
80+
CommandResult cwdResult = commands.run("pwd && ls -la", cwdOptions);
81+
System.out.println("Working directory command result:\n" + cwdResult.getStdout());
82+
83+
System.out.println("\n=== Example 7: Start Long-running Process And List All Processes ===");
84+
CommandHandle longRunningHandle = commands.runBackground("sleep 20 && echo 'Long-running task completed'",
85+
new RunOptions().timeoutMs(25000));
86+
System.out.println("Start long-running process, PID: " + longRunningHandle.getPid());
87+
88+
// Wait a moment for the process to start
89+
Thread.sleep(1000);
90+
91+
// List all processes
92+
System.out.println("\n=== Current Running Process List ===");
93+
List<ProcessInfo> processes = commands.list();
94+
for (ProcessInfo process : processes) {
95+
System.out.printf("PID: %d, CMD: %s, CWD: %s%n",
96+
process.getPid(), process.getCmd(), process.getCwd());
97+
}
98+
99+
System.out.println("\n=== Example 8: Send Standard Input To Running Process ===");
100+
// Start an interactive process
101+
CommandHandle interactiveHandle = commands.runBackground("read -p 'Please enter content: ' input && echo 'You entered: $input'",
102+
new RunOptions().stdin(true).timeoutMs(10000));
103+
System.out.println("Interactive command PID: " + interactiveHandle.getPid());
104+
105+
// Wait a moment for the process to be ready to receive input
106+
Thread.sleep(1000);
107+
108+
// Send standard input
109+
commands.sendStdin(interactiveHandle.getPid(), "Hello from stdin\n");
110+
111+
// Wait for completion
112+
CommandResult interactiveResult = interactiveHandle.waitForCompletion();
113+
System.out.println("Interactive command result: " + interactiveResult.getStdout());
114+
115+
System.out.println("\n=== Example 9: Terminate Running Process ===");
116+
// Start another long-running process
117+
CommandHandle toKillHandle = commands.runBackground("sleep 30 && echo 'Should not see this message'",
118+
new RunOptions().timeoutMs(30000));
119+
System.out.println("Start process to terminate, PID: " + toKillHandle.getPid());
120+
121+
Thread.sleep(1000);
122+
123+
// Kill the process
124+
boolean killed = commands.kill(toKillHandle.getPid());
125+
System.out.println("Process termination result: " + killed);
126+
127+
System.out.println("\n=== Example 10: Check Process List To Confirm Cleanup ===");
128+
List<ProcessInfo> finalProcesses = commands.list();
129+
System.out.println("Final process count: " + finalProcesses.size());
130+
for (ProcessInfo process : finalProcesses) {
131+
System.out.printf("PID: %d, CMD: %s%n", process.getPid(), process.getCmd());
132+
}
133+
134+
System.out.println("\n========== All Command Examples Executed ==========");
135+
136+
} finally {
137+
channel.shutdown();
138+
}
139+
}
140+
}
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package io.openkruise.agents.client.e2b.example;
2+
3+
import io.openkruise.agents.client.e2b.api.invoker.ApiClient;
4+
import io.openkruise.agents.client.e2b.api.invoker.Configuration;
5+
import io.openkruise.agents.client.e2b.api.models.*;
6+
import io.openkruise.agents.client.e2b.sandbox.SandboxesApi;
7+
8+
import java.util.List;
9+
10+
public class E2BClientExample {
11+
/**
12+
* API_BASE_URL configuration notes:
13+
*
14+
* Local development environment:
15+
* - Usually uses "http://localhost:8080" or similar local endpoint
16+
*
17+
* Online/Production environment:
18+
* - According to ConnectionConfig class logic, online environment API URL format is:
19+
* https://api.{domain}
20+
* - For example: if domain is "your-domain.com", then API URL is "https://api.your-domain.com"
21+
* - In your pre-production environment, it might be: https://api.pre-cad42426ced3b4418bcd93ed85ac1e33f-inner.bailian.ai
22+
*
23+
* Note: E2BClientExample uses REST API, while CommandsExample and FilesystemExample use gRPC interface,
24+
* they have different endpoints and service paths.
25+
*/
26+
private static final String API_BASE_URL = "https://api.pre-cad42426ced3b4418bcd93ed85ac1e33f-inner.bailian.ai"; // Online environment API URL
27+
private static final String API_KEY = "key";
28+
29+
/**
30+
* ============================================
31+
* Part One: Sandbox Lifecycle Management
32+
* ============================================
33+
*/
34+
public void sandboxLifecycleExample() throws Exception {
35+
System.out.println("========== Sandbox Lifecycle Management ==========");
36+
37+
// 1. Initialize API client
38+
ApiClient apiClient = Configuration.getDefaultApiClient();
39+
apiClient.setBasePath(API_BASE_URL);
40+
41+
// Set authentication (choose one method)
42+
// Method 1: API Key authentication
43+
apiClient.addDefaultHeader("X-API-Key", API_KEY);
44+
// Method 2: Access Token authentication
45+
// apiClient.addDefaultHeader("Authorization", "Bearer " + ACCESS_TOKEN);
46+
47+
SandboxesApi sandboxesApi = new SandboxesApi(apiClient);
48+
49+
// 2. Create Sandbox
50+
System.out.println("\n--- Create Sandbox ---");
51+
NewSandbox newSandbox = new NewSandbox();
52+
newSandbox.setTemplateID("base");
53+
newSandbox.setTimeout(300);
54+
55+
Sandbox sandbox = sandboxesApi.sandboxesPost(newSandbox);
56+
String sandboxId = sandbox.getSandboxID();
57+
System.out.println("Sandbox created successfully: " + sandboxId);
58+
System.out.println("Template ID: " + sandbox.getTemplateID());
59+
System.out.println("Client ID: " + sandbox.getClientID());
60+
61+
// 3. Get Sandbox details
62+
System.out.println("\n--- Get Sandbox Details ---");
63+
SandboxDetail detail = sandboxesApi.sandboxesSandboxIDGet(sandboxId);
64+
System.out.println("State: " + detail.getState());
65+
System.out.println("Started At: " + detail.getStartedAt());
66+
67+
// 4. List all running Sandboxes
68+
System.out.println("\n--- List All Sandboxes ---");
69+
List<SandboxesGet200ResponseInner> sandboxes = sandboxesApi.sandboxesGet(null);
70+
System.out.println("Number of running Sandboxes: " + sandboxes.size());
71+
72+
// 5. Refresh Sandbox TTL
73+
System.out.println("\n--- Refresh Sandbox TTL ---");
74+
SandboxesSandboxIDRefreshesPostRequest refreshRequest =
75+
new SandboxesSandboxIDRefreshesPostRequest();
76+
sandboxesApi.sandboxesSandboxIDRefreshesPost(sandboxId, refreshRequest);
77+
System.out.println("Sandbox TTL refreshed");
78+
79+
// 6. Set Sandbox timeout
80+
System.out.println("\n--- Set Sandbox Timeout ---");
81+
SandboxesSandboxIDTimeoutPostRequest timeoutRequest =
82+
new SandboxesSandboxIDTimeoutPostRequest();
83+
timeoutRequest.setTimeout(600);
84+
sandboxesApi.sandboxesSandboxIDTimeoutPost(sandboxId, timeoutRequest);
85+
System.out.println("Sandbox timeout set to 600 seconds");
86+
87+
// 7. Get Sandbox metrics
88+
System.out.println("\n--- Get Sandbox Metrics ---");
89+
List<SandboxMetric> metrics = sandboxesApi.sandboxesSandboxIDMetricsGet(
90+
sandboxId, null, null);
91+
System.out.println("Metrics count: " + metrics.size());
92+
93+
// 8. Create snapshot
94+
System.out.println("\n--- Create Snapshot ---");
95+
SandboxesSandboxIDSnapshotsPostRequest snapshotRequest =
96+
new SandboxesSandboxIDSnapshotsPostRequest();
97+
snapshotRequest.setName("my-snapshot-" + System.currentTimeMillis());
98+
SnapshotInfo snapshot = sandboxesApi.sandboxesSandboxIDSnapshotsPost(
99+
sandboxId, snapshotRequest);
100+
System.out.println("Snapshot created: " + snapshot.getSnapshotID());
101+
102+
// 9. Pause Sandbox
103+
System.out.println("\n--- Pause Sandbox ---");
104+
sandboxesApi.sandboxesSandboxIDPausePost(sandboxId);
105+
System.out.println("Sandbox paused");
106+
107+
// 10. Resume/Connect Sandbox
108+
System.out.println("\n--- Resume Sandbox ---");
109+
ConnectSandbox connectRequest = new ConnectSandbox();
110+
Sandbox resumedSandbox = sandboxesApi.sandboxesSandboxIDConnectPost(
111+
sandboxId, connectRequest);
112+
System.out.println("Sandbox resumed: " + resumedSandbox.getSandboxID());
113+
114+
// 11. Delete Sandbox
115+
System.out.println("\n--- Delete Sandbox ---");
116+
sandboxesApi.sandboxesSandboxIDDelete(sandboxId);
117+
System.out.println("Sandbox deleted");
118+
}
119+
}

0 commit comments

Comments
 (0)