Skip to content

Commit 31d35ac

Browse files
committed
add filesystem & example
1 parent d6864a5 commit 31d35ac

10 files changed

Lines changed: 1100 additions & 4 deletions

File tree

clients/java/src/main/java/io/openkruise/agents/client/e2b/sandbox/SandboxesApi.java renamed to clients/java/src/main/java/io/openkruise/agents/client/e2b/api/SandboxesApi.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
*/
1212

1313

14-
package io.openkruise.agents.client.e2b.sandbox;
14+
package io.openkruise.agents.client.e2b.api;
1515

1616
import io.openkruise.agents.client.e2b.api.invoker.ApiCallback;
1717
import io.openkruise.agents.client.e2b.api.invoker.ApiClient;

clients/java/src/main/java/io/openkruise/agents/client/e2b/config/ConnectionConfig.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public String getApiUrl() {
101101
if (apiUrl != null) {
102102
return apiUrl;
103103
}
104-
return debug ? "http://localhost:3000" : "https://api." + domain;
104+
return debug ? "http://localhost/kruise/api" : "https://api." + domain;
105105
}
106106

107107
public String getSandboxUrl(String sandboxId, String sandboxDomain) {
@@ -141,7 +141,7 @@ public Map<String, String> getSandboxHeaders() {
141141
return sandboxHeaders;
142142
}
143143

144-
public ManagedChannel createChannel(String sandboxId, String sandboxDomain) {
144+
public ManagedChannel createChannel(String sandboxId, String token, String sandboxDomain) {
145145
String target = getSandboxHost(sandboxId, sandboxDomain);
146146

147147
ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forTarget(target);
@@ -155,7 +155,7 @@ public ManagedChannel createChannel(String sandboxId, String sandboxDomain) {
155155
}
156156

157157
Metadata metadata = RpcUtils.createFullMetadata(
158-
sandboxId, ENVD_PORT, apiKey, accessToken, getSandboxHeaders()
158+
sandboxId, ENVD_PORT, apiKey, token, getSandboxHeaders()
159159
);
160160

161161
return builder.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata))
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
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 CommandsExample() throws Exception {
23+
ConnectionConfig config = new ConnectionConfig.Builder()
24+
.apiKey(API_KEY)
25+
.debug(true)
26+
.requestTimeoutMs(30000)
27+
.build();
28+
29+
ManagedChannel channel = config.createChannel(SANDBOX_ID, ACCESS_TOKEN, SANDBOX_DOMAIN);
30+
31+
try {
32+
Commands commands = new Commands(channel, config);
33+
34+
System.out.println("=== Example 1: Execute Simple Command ===");
35+
CommandResult pwd = commands.run("pwd", new RunOptions().timeoutMs(10000));
36+
System.out.println("pwd command result: " + pwd);
37+
38+
System.out.println("\n=== Example 2: Execute Complex Command ===");
39+
CommandResult ls = commands.run("ls -la /tmp", new RunOptions().timeoutMs(10000));
40+
System.out.println("ls -la /tmp result: ");
41+
System.out.println(ls.getStdout());
42+
if (!ls.getStderr().isEmpty()) {
43+
System.out.println("Error output: " + ls.getStderr());
44+
}
45+
46+
System.out.println("\n=== Example 3: Execute Command With Environment Variables ===");
47+
Map<String, String> envs = new HashMap<>();
48+
envs.put("MY_VAR", "hello_world");
49+
RunOptions optionsWithEnv = new RunOptions()
50+
.envs(envs)
51+
.timeoutMs(10000);
52+
CommandResult envTest = commands.run("echo $MY_VAR", optionsWithEnv);
53+
System.out.println("Environment variable test result: " + envTest.getStdout().trim());
54+
55+
System.out.println("\n=== Example 4: Execute Background Command And Wait For Completion ===");
56+
CommandHandle bgHandle = commands.runBackground("sleep 3 && echo 'Background task completed'",
57+
new RunOptions().timeoutMs(10000));
58+
System.out.println("Background command PID: " + bgHandle.getPid());
59+
CommandResult bgResult = bgHandle.waitForCompletion();
60+
System.out.println("Background command result: " + bgResult.getStdout().trim());
61+
62+
System.out.println("\n=== Example 5: Execute Real-time Output Command ===");
63+
// Use callback function to handle output in real-time
64+
Consumer<String> stdoutHandler = output -> System.out.print("STDOUT: " + output);
65+
Consumer<String> stderrHandler = output -> System.out.print("STDERR: " + output);
66+
RunOptions realtimeOptions = new RunOptions()
67+
.onStdout(stdoutHandler)
68+
.onStderr(stderrHandler)
69+
.timeoutMs(15000);
70+
CommandResult realtimeResult = commands.run("for i in {1..5}; do echo \"Count: $i\"; sleep 1; done",
71+
realtimeOptions);
72+
System.out.println("\nReal-time output command completed");
73+
74+
System.out.println("\n=== Example 6: Execute Command Requiring Working Directory ===");
75+
RunOptions cwdOptions = new RunOptions()
76+
.cwd("/tmp")
77+
.timeoutMs(10000);
78+
CommandResult cwdResult = commands.run("pwd && ls -la", cwdOptions);
79+
System.out.println("Working directory command result:\n" + cwdResult.getStdout());
80+
81+
System.out.println("\n=== Example 7: Start Long-running Process And List All Processes ===");
82+
CommandHandle longRunningHandle = commands.runBackground("sleep 20 && echo 'Long-running task completed'",
83+
new RunOptions().timeoutMs(25000));
84+
System.out.println("Start long-running process, PID: " + longRunningHandle.getPid());
85+
86+
// Wait a moment for the process to start
87+
Thread.sleep(1000);
88+
89+
// List all processes
90+
System.out.println("\n=== Current Running Process List ===");
91+
List<ProcessInfo> processes = commands.list();
92+
for (ProcessInfo process : processes) {
93+
System.out.printf("PID: %d, CMD: %s, CWD: %s%n",
94+
process.getPid(), process.getCmd(), process.getCwd());
95+
}
96+
97+
System.out.println("\n=== Example 8: Send Standard Input To Running Process ===");
98+
// Start an interactive process
99+
CommandHandle interactiveHandle = commands.runBackground(
100+
"read -p 'Please enter content: ' input && echo 'You entered: $input'",
101+
new RunOptions().stdin(true).timeoutMs(10000));
102+
System.out.println("Interactive command PID: " + interactiveHandle.getPid());
103+
104+
// Wait a moment for the process to be ready to receive input
105+
Thread.sleep(1000);
106+
107+
// Send standard input
108+
commands.sendStdin(interactiveHandle.getPid(), "Hello from stdin\n");
109+
110+
// Wait for completion
111+
CommandResult interactiveResult = interactiveHandle.waitForCompletion();
112+
System.out.println("Interactive command result: " + interactiveResult.getStdout());
113+
114+
System.out.println("\n=== Example 9: Terminate Running Process ===");
115+
// Start another long-running process
116+
CommandHandle toKillHandle = commands.runBackground("sleep 30 && echo 'Should not see this message'",
117+
new RunOptions().timeoutMs(30000));
118+
System.out.println("Start process to terminate, PID: " + toKillHandle.getPid());
119+
120+
Thread.sleep(1000);
121+
122+
// Kill the process
123+
boolean killed = commands.kill(toKillHandle.getPid());
124+
System.out.println("Process termination result: " + killed);
125+
126+
System.out.println("\n=== Example 10: Check Process List To Confirm Cleanup ===");
127+
List<ProcessInfo> finalProcesses = commands.list();
128+
System.out.println("Final process count: " + finalProcesses.size());
129+
for (ProcessInfo process : finalProcesses) {
130+
System.out.printf("PID: %d, CMD: %s%n", process.getPid(), process.getCmd());
131+
}
132+
133+
System.out.println("\n========== All Command Examples Executed ==========");
134+
135+
} finally {
136+
channel.shutdown();
137+
}
138+
}
139+
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
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.api.SandboxesApi;
7+
8+
import java.util.List;
9+
10+
public class E2BClientExample {
11+
private static final String API_BASE_URL = "api.{domain}";
12+
private static final String API_KEY = "key";
13+
14+
/**
15+
* ============================================
16+
* Part One: Sandbox Lifecycle Management
17+
* ============================================
18+
*/
19+
public void E2BClientExample() throws Exception {
20+
System.out.println("========== Sandbox Lifecycle Management ==========");
21+
22+
// 1. Initialize API client
23+
ApiClient apiClient = Configuration.getDefaultApiClient();
24+
apiClient.setBasePath(API_BASE_URL);
25+
26+
// API Key authentication
27+
apiClient.addDefaultHeader("X-API-Key", API_KEY);
28+
29+
SandboxesApi sandboxesApi = new SandboxesApi(apiClient);
30+
31+
// 2. Create Sandbox
32+
System.out.println("\n--- Create Sandbox ---");
33+
NewSandbox newSandbox = new NewSandbox();
34+
newSandbox.setTemplateID("base");
35+
newSandbox.setTimeout(300);
36+
37+
Sandbox sandbox = sandboxesApi.sandboxesPost(newSandbox);
38+
String sandboxId = sandbox.getSandboxID();
39+
System.out.println("Sandbox created successfully: " + sandboxId);
40+
System.out.println("Template ID: " + sandbox.getTemplateID());
41+
System.out.println("Client ID: " + sandbox.getClientID());
42+
43+
// 3. Get Sandbox details
44+
System.out.println("\n--- Get Sandbox Details ---");
45+
SandboxDetail detail = sandboxesApi.sandboxesSandboxIDGet(sandboxId);
46+
System.out.println("State: " + detail.getState());
47+
System.out.println("Started At: " + detail.getStartedAt());
48+
49+
// 4. List all running Sandboxes
50+
System.out.println("\n--- List All Sandboxes ---");
51+
List<SandboxesGet200ResponseInner> sandboxes = sandboxesApi.sandboxesGet(null);
52+
System.out.println("Number of running Sandboxes: " + sandboxes.size());
53+
54+
// 5. Refresh Sandbox TTL
55+
System.out.println("\n--- Refresh Sandbox TTL ---");
56+
SandboxesSandboxIDRefreshesPostRequest refreshRequest =
57+
new SandboxesSandboxIDRefreshesPostRequest();
58+
sandboxesApi.sandboxesSandboxIDRefreshesPost(sandboxId, refreshRequest);
59+
System.out.println("Sandbox TTL refreshed");
60+
61+
// 6. Set Sandbox timeout
62+
System.out.println("\n--- Set Sandbox Timeout ---");
63+
SandboxesSandboxIDTimeoutPostRequest timeoutRequest =
64+
new SandboxesSandboxIDTimeoutPostRequest();
65+
timeoutRequest.setTimeout(600);
66+
sandboxesApi.sandboxesSandboxIDTimeoutPost(sandboxId, timeoutRequest);
67+
System.out.println("Sandbox timeout set to 600 seconds");
68+
69+
// 7. Get Sandbox metrics
70+
System.out.println("\n--- Get Sandbox Metrics ---");
71+
List<SandboxMetric> metrics = sandboxesApi.sandboxesSandboxIDMetricsGet(
72+
sandboxId, null, null);
73+
System.out.println("Metrics count: " + metrics.size());
74+
75+
// 8. Create snapshot
76+
System.out.println("\n--- Create Snapshot ---");
77+
SandboxesSandboxIDSnapshotsPostRequest snapshotRequest =
78+
new SandboxesSandboxIDSnapshotsPostRequest();
79+
snapshotRequest.setName("my-snapshot-" + System.currentTimeMillis());
80+
SnapshotInfo snapshot = sandboxesApi.sandboxesSandboxIDSnapshotsPost(
81+
sandboxId, snapshotRequest);
82+
System.out.println("Snapshot created: " + snapshot.getSnapshotID());
83+
84+
// 9. Pause Sandbox
85+
System.out.println("\n--- Pause Sandbox ---");
86+
sandboxesApi.sandboxesSandboxIDPausePost(sandboxId);
87+
System.out.println("Sandbox paused");
88+
89+
// 10. Resume/Connect Sandbox
90+
System.out.println("\n--- Resume Sandbox ---");
91+
ConnectSandbox connectRequest = new ConnectSandbox();
92+
Sandbox resumedSandbox = sandboxesApi.sandboxesSandboxIDConnectPost(
93+
sandboxId, connectRequest);
94+
System.out.println("Sandbox resumed: " + resumedSandbox.getSandboxID());
95+
96+
// 11. Delete Sandbox
97+
System.out.println("\n--- Delete Sandbox ---");
98+
sandboxesApi.sandboxesSandboxIDDelete(sandboxId);
99+
System.out.println("Sandbox deleted");
100+
}
101+
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package io.openkruise.agents.client.e2b.example;
2+
3+
import java.util.List;
4+
import java.util.concurrent.CountDownLatch;
5+
6+
import io.grpc.ManagedChannel;
7+
import io.openkruise.agents.client.e2b.config.ConnectionConfig;
8+
import io.openkruise.agents.client.e2b.sandbox.filesystem.Filesystem;
9+
import io.openkruise.agents.client.e2b.sandbox.filesystem.Filesystem.EntryInfo;
10+
import io.openkruise.agents.client.e2b.sandbox.filesystem.WatchHandle;
11+
12+
public class FilesystemExample {
13+
private static final String ACCESS_TOKEN = "sandbox-token";
14+
private static final String API_KEY = "key";
15+
private static final String SANDBOX_ID = "sandbox-id";
16+
private static final String SANDBOX_DOMAIN = "your.domain.com";
17+
18+
public void FilesystemExample() {
19+
// Enable debug mode for testing
20+
ConnectionConfig config = new ConnectionConfig.Builder()
21+
.apiKey(API_KEY)
22+
.debug(true)
23+
.requestTimeoutMs(30000)
24+
.build();
25+
26+
ManagedChannel channel = config.createChannel(SANDBOX_ID, ACCESS_TOKEN, SANDBOX_DOMAIN);
27+
try {
28+
// Create Filesystem instance
29+
Filesystem filesystem = new Filesystem(channel, config);
30+
31+
// Example 1: List directory contents
32+
System.out.println("=== Example 1: List Directory Contents ===");
33+
try {
34+
List<EntryInfo> entries = filesystem.listDir("/tmp", 1);
35+
System.out.println("Entries in directory /tmp:");
36+
for (EntryInfo entry : entries) {
37+
System.out.printf(" %s (%s, Size: %d)\n",
38+
entry.getName(), entry.getType(), entry.getSize());
39+
}
40+
} catch (Exception e) {
41+
System.err.println("Failed to list directory: " + e.getMessage());
42+
}
43+
44+
// Example 2: Check if file/directory exists
45+
System.out.println("\n=== Example 2: Check If File/Directory Exists ===");
46+
boolean exists = filesystem.exists("/tmp/testdir");
47+
System.out.println("/tmp/testdir exists: " + exists);
48+
49+
// Example 3: Create directory
50+
System.out.println("\n=== Example 3: Create Directory ===");
51+
String newDirPath = "/tmp/testdir_" + System.currentTimeMillis();
52+
boolean created = filesystem.makeDir(newDirPath);
53+
System.out.println("Create directory " + newDirPath + ": " + (created ? "Success" : "Already exists"));
54+
55+
// Example 4: Get file/directory information
56+
System.out.println("\n=== Example 4: Get Directory Information ===");
57+
try {
58+
EntryInfo dirInfo = filesystem.getInfo(newDirPath);
59+
System.out.printf("Directory info: %s (%s, Size: %d, Permissions: %s)\n",
60+
dirInfo.getPath(), dirInfo.getType(), dirInfo.getSize(), dirInfo.getPermissions());
61+
} catch (Exception e) {
62+
System.err.println("Failed to get directory info: " + e.getMessage());
63+
}
64+
65+
// Example 5: Rename directory
66+
System.out.println("\n=== Example 5: Rename Directory ===");
67+
String renamedDirPath = newDirPath + "_renamed";
68+
try {
69+
EntryInfo renamedInfo = filesystem.rename(newDirPath, renamedDirPath);
70+
System.out.println("Rename successful: " + renamedInfo.getPath());
71+
} catch (Exception e) {
72+
System.err.println("Failed to rename: " + e.getMessage());
73+
}
74+
75+
// Example 6: Monitor directory changes (non-recursive)
76+
System.out.println("\n=== Example 6: Monitor Directory Changes ===");
77+
CountDownLatch latch = new CountDownLatch(1);
78+
79+
WatchHandle watchHandle = filesystem.watchDir(renamedDirPath, event -> {
80+
System.out.printf("Detected filesystem event: %s Type: %s\n",
81+
event.getName(), event.getType());
82+
});
83+
84+
System.out.println("Start monitoring directory " + renamedDirPath + ", press Ctrl+C to stop");
85+
86+
// Wait for some time to let monitoring take effect
87+
Thread.sleep(5000);
88+
89+
// Example 7: Remove directory
90+
System.out.println("\n=== Example 7: Remove Directory ===");
91+
try {
92+
filesystem.remove(renamedDirPath);
93+
System.out.println("Remove directory " + renamedDirPath + " successful");
94+
95+
// Verify if directory has been deleted
96+
boolean stillExists = filesystem.exists(renamedDirPath);
97+
System.out.println("Directory " + renamedDirPath + " still exists: " + stillExists);
98+
} catch (Exception e) {
99+
System.err.println("Failed to remove directory: " + e.getMessage());
100+
}
101+
102+
// Stop monitoring
103+
watchHandle.stop();
104+
System.out.println("Stop monitoring directory");
105+
106+
} catch (Exception e) {
107+
System.err.println("Error occurred while executing example: " + e.getMessage());
108+
e.printStackTrace();
109+
} finally {
110+
channel.shutdown();
111+
}
112+
}
113+
}

0 commit comments

Comments
 (0)