Repository navigation
Expand file tree
/
Copy pathsandbox.go
More file actions
517 lines (436 loc) · 16.5 KB
/
Copy pathsandbox.go
File metadata and controls
517 lines (436 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
package e2b
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// SandboxConfig holds the configuration for creating a new sandbox.
type SandboxConfig struct {
// Template is the sandbox template ID. Defaults to "base".
Template string
// Timeout is the sandbox lifetime in seconds. Defaults to 300.
Timeout int
// EnvVars are environment variables set in the sandbox.
EnvVars map[string]string
// Secure enables secure envd communication with access tokens.
// Required when Network.AllowPublicTraffic is false.
// Defaults to true in the official SDKs since v2.0.0.
Secure bool
// AllowInternetAccess controls whether the sandbox can access
// the internet. When false, equivalent to DenyOut: ["0.0.0.0/0"].
// Defaults to true (server-side).
AllowInternetAccess *bool
// Network configures outbound network access and request transforms.
// If nil, the sandbox uses the default network configuration
// (all outbound traffic allowed).
Network *NetworkConfig
}
// Sandbox represents a running E2B sandbox microVM.
type Sandbox struct {
// ID is the unique identifier of the sandbox.
ID string
// TrafficAccessToken is set when the sandbox is created with
// Secure: true and Network.AllowPublicTraffic: false.
// Use it in the "e2b-traffic-access-token" HTTP header to access
// sandbox URLs.
TrafficAccessToken string
// Commands provides command execution within the sandbox.
Commands *CommandService
// Filesystem provides file read and write operations within the sandbox.
Filesystem *FilesystemService
accessToken string
client *Client
}
type createRequest struct {
TemplateID string `json:"templateID"`
Timeout int `json:"timeout"`
EnvVars map[string]string `json:"envVars,omitempty"`
Secure bool `json:"secure,omitempty"`
AllowInternetAccess *bool `json:"allow_internet_access,omitempty"`
Network *NetworkConfig `json:"network,omitempty"`
}
type createResponse struct {
SandboxID string `json:"sandboxID"`
EnvdAccessToken string `json:"envdAccessToken"`
TrafficAccessToken string `json:"trafficAccessToken,omitempty"`
}
// SandboxLifecycle holds lifecycle configuration for a sandbox.
type SandboxLifecycle struct {
AutoResume bool `json:"autoResume"`
OnTimeout string `json:"onTimeout"` // "keep" or "kill"
}
// VolumeMount represents a mounted volume in the sandbox.
type VolumeMount struct {
Name string `json:"name,omitempty"`
Path string `json:"path,omitempty"`
}
// SandboxInfo holds details about a sandbox.
type SandboxInfo struct {
ID string `json:"sandboxID"`
Alias string `json:"alias,omitempty"`
ClientID string `json:"clientID,omitempty"`
Template string `json:"templateID"`
State string `json:"state"`
CPUCount int `json:"cpuCount"`
MemoryMB int `json:"memoryMB"`
DiskSizeMB int `json:"diskSizeMB"`
StartedAt string `json:"startedAt"`
EndAt string `json:"endAt,omitempty"`
EnvdVersion string `json:"envdVersion,omitempty"`
Lifecycle SandboxLifecycle `json:"lifecycle,omitempty"`
VolumeMounts []VolumeMount `json:"volumeMounts,omitempty"`
Network *NetworkConfig `json:"network,omitempty"`
}
// envdBaseURL returns the base URL of the sandbox environment daemon.
func (s *Sandbox) envdBaseURL() string {
return fmt.Sprintf("https://%d-%s.%s", envdPort, s.ID, s.client.sandboxDomain)
}
// Close destroys the sandbox, freeing all associated resources.
func (s *Sandbox) Close() error {
return s.CloseWithContext(context.Background())
}
// CloseWithContext destroys the sandbox using the provided context.
func (s *Sandbox) CloseWithContext(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, s.client.apiBaseURL+"/sandboxes/"+s.ID, nil)
if err != nil {
return fmt.Errorf("e2b: build delete request: %w", err)
}
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("e2b: send delete request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusNoContent, http.StatusOK:
return nil
case http.StatusNotFound:
return &SandboxNotFoundError{SandboxID: s.ID}
default:
respBody, _ := io.ReadAll(resp.Body)
return &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
}
// Info retrieves detailed information about the sandbox.
func (s *Sandbox) Info() (*SandboxInfo, error) {
return s.InfoWithContext(context.Background())
}
// InfoWithContext retrieves detailed information about the sandbox using the provided context.
func (s *Sandbox) InfoWithContext(ctx context.Context) (*SandboxInfo, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.client.apiBaseURL+"/sandboxes/"+s.ID, nil)
if err != nil {
return nil, fmt.Errorf("e2b: build info request: %w", err)
}
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send info request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode == http.StatusNotFound {
return nil, &SandboxNotFoundError{SandboxID: s.ID}
}
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var info SandboxInfo
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
return nil, fmt.Errorf("e2b: decode info response: %w", err)
}
return &info, nil
}
type setTimeoutRequest struct {
Timeout int `json:"timeout"`
}
// SetTimeout updates the sandbox lifetime timeout in seconds.
func (s *Sandbox) SetTimeout(timeoutSeconds int) error {
return s.SetTimeoutWithContext(context.Background(), timeoutSeconds)
}
// SetTimeoutWithContext updates the sandbox lifetime timeout using the provided context.
func (s *Sandbox) SetTimeoutWithContext(ctx context.Context, timeoutSeconds int) error {
body, err := json.Marshal(setTimeoutRequest{Timeout: timeoutSeconds})
if err != nil {
return fmt.Errorf("e2b: marshal timeout request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.client.apiBaseURL+"/sandboxes/"+s.ID+"/timeout", bytes.NewReader(body))
if err != nil {
return fmt.Errorf("e2b: build timeout request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("e2b: send timeout request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusNoContent, http.StatusOK:
return nil
case http.StatusNotFound:
return &SandboxNotFoundError{SandboxID: s.ID}
default:
respBody, _ := io.ReadAll(resp.Body)
return &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
}
// Pause pauses the sandbox, stopping billing while preserving state.
// A paused sandbox can be resumed with Resume.
func (s *Sandbox) Pause() error {
return s.PauseWithContext(context.Background())
}
// PauseWithContext pauses the sandbox using the provided context.
func (s *Sandbox) PauseWithContext(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.client.apiBaseURL+"/sandboxes/"+s.ID+"/pause", nil)
if err != nil {
return fmt.Errorf("e2b: build pause request: %w", err)
}
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("e2b: send pause request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusNoContent, http.StatusOK:
return nil
case http.StatusNotFound:
return &SandboxNotFoundError{SandboxID: s.ID}
default:
respBody, _ := io.ReadAll(resp.Body)
return &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
}
type resumeRequest struct {
Timeout int `json:"timeout"`
}
// Resume resumes a paused sandbox with the given lifetime timeout in seconds.
func (s *Sandbox) Resume(timeoutSeconds int) error {
return s.ResumeWithContext(context.Background(), timeoutSeconds)
}
// ResumeWithContext resumes a paused sandbox using the provided context.
func (s *Sandbox) ResumeWithContext(ctx context.Context, timeoutSeconds int) error {
body, err := json.Marshal(resumeRequest{Timeout: timeoutSeconds})
if err != nil {
return fmt.Errorf("e2b: marshal resume request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.client.apiBaseURL+"/sandboxes/"+s.ID+"/resume", bytes.NewReader(body))
if err != nil {
return fmt.Errorf("e2b: build resume request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("e2b: send resume request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusCreated, http.StatusOK, http.StatusNoContent:
return nil
case http.StatusNotFound:
return &SandboxNotFoundError{SandboxID: s.ID}
default:
respBody, _ := io.ReadAll(resp.Body)
return &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
}
// UpdateNetwork replaces the mutable network configuration on a running sandbox.
// All fields in the update config are optional; omitted fields are cleared
// on the server. This replaces the entire mutable config, it does not merge.
// Create-only fields (AllowPublicTraffic, MaskRequestHost) are preserved.
func (s *Sandbox) UpdateNetwork(cfg NetworkUpdateConfig) error {
return s.UpdateNetworkWithContext(context.Background(), cfg)
}
// UpdateNetworkWithContext replaces the mutable network configuration using the provided context.
func (s *Sandbox) UpdateNetworkWithContext(ctx context.Context, cfg NetworkUpdateConfig) error {
body, err := json.Marshal(cfg)
if err != nil {
return fmt.Errorf("e2b: marshal network update request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPut, s.client.apiBaseURL+"/sandboxes/"+s.ID+"/network", bytes.NewReader(body))
if err != nil {
return fmt.Errorf("e2b: build network update request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return fmt.Errorf("e2b: send network update request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusNoContent, http.StatusOK:
return nil
case http.StatusNotFound:
return &SandboxNotFoundError{SandboxID: s.ID}
default:
respBody, _ := io.ReadAll(resp.Body)
return &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
}
// SandboxMetric holds a single resource usage snapshot for a sandbox.
type SandboxMetric struct {
CPUCount int `json:"cpuCount"`
CPUUsedPct float64 `json:"cpuUsedPct"`
MemTotal int64 `json:"memTotal"`
MemUsed int64 `json:"memUsed"`
MemCache int64 `json:"memCache"`
DiskTotal int64 `json:"diskTotal"`
DiskUsed int64 `json:"diskUsed"`
Timestamp string `json:"timestamp"`
TimestampUnix int64 `json:"timestampUnix"`
}
// Metrics retrieves resource usage metrics for the sandbox.
func (s *Sandbox) Metrics() ([]SandboxMetric, error) {
return s.MetricsWithContext(context.Background())
}
// MetricsWithContext retrieves resource usage metrics using the provided context.
func (s *Sandbox) MetricsWithContext(ctx context.Context) ([]SandboxMetric, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.client.apiBaseURL+"/sandboxes/"+s.ID+"/metrics", nil)
if err != nil {
return nil, fmt.Errorf("e2b: build metrics request: %w", err)
}
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send metrics request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var metrics []SandboxMetric
if err := json.NewDecoder(resp.Body).Decode(&metrics); err != nil {
return nil, fmt.Errorf("e2b: decode metrics response: %w", err)
}
return metrics, nil
}
// SandboxLogEntry holds a single structured log entry from a sandbox.
type SandboxLogEntry struct {
Level string `json:"level"`
Message string `json:"message"`
Timestamp string `json:"timestamp"`
Fields map[string]string `json:"fields"`
}
type logsResponse struct {
Logs []SandboxLogEntry `json:"logs"`
}
type logsParams struct {
limit int
direction string
level string
search string
}
// LogsOption configures a Logs request.
type LogsOption func(*logsParams)
// WithLimit sets the maximum number of log entries to return (default 1000).
func WithLimit(n int) LogsOption {
return func(p *logsParams) { p.limit = n }
}
// WithDirection sets the sort order: "forward" (oldest first) or "backward" (newest first, default).
func WithDirection(d string) LogsOption {
return func(p *logsParams) { p.direction = d }
}
// WithLevel filters logs by level: "debug", "info", "warn", or "error".
func WithLevel(l string) LogsOption {
return func(p *logsParams) { p.level = l }
}
// WithSearch filters logs by a text search on the message field.
func WithSearch(q string) LogsOption {
return func(p *logsParams) { p.search = q }
}
// Logs retrieves structured log entries for the sandbox.
func (s *Sandbox) Logs(opts ...LogsOption) ([]SandboxLogEntry, error) {
return s.LogsWithContext(context.Background(), opts...)
}
// LogsWithContext retrieves structured log entries using the provided context.
func (s *Sandbox) LogsWithContext(ctx context.Context, opts ...LogsOption) ([]SandboxLogEntry, error) {
var p logsParams
for _, o := range opts {
o(&p)
}
u := s.client.apiBaseURL + "/v2/sandboxes/" + s.ID + "/logs"
sep := '?'
if p.limit > 0 {
u += string(sep) + "limit=" + fmt.Sprintf("%d", p.limit)
sep = '&'
}
if p.direction != "" {
u += string(sep) + "direction=" + p.direction
sep = '&'
}
if p.level != "" {
u += string(sep) + "level=" + p.level
sep = '&'
}
if p.search != "" {
u += string(sep) + "search=" + p.search
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, fmt.Errorf("e2b: build logs request: %w", err)
}
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send logs request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var lr logsResponse
if err := json.NewDecoder(resp.Body).Decode(&lr); err != nil {
return nil, fmt.Errorf("e2b: decode logs response: %w", err)
}
return lr.Logs, nil
}
// SnapshotInfo holds information about a sandbox snapshot.
type SnapshotInfo struct {
Names []string `json:"names"`
SnapshotID string `json:"snapshotID"`
}
type createSnapshotRequest struct {
Name string `json:"name,omitempty"`
}
// CreateSnapshot creates a snapshot of the sandbox's current state.
// An optional name can be provided; if omitted, the API generates an ID.
func (s *Sandbox) CreateSnapshot(ctx context.Context, name ...string) (*SnapshotInfo, error) {
var reqBody createSnapshotRequest
if len(name) > 0 {
reqBody.Name = name[0]
}
body, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("e2b: marshal snapshot request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.client.apiBaseURL+"/sandboxes/"+s.ID+"/snapshots", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("e2b: build snapshot request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", s.client.apiKey)
resp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("e2b: send snapshot request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode == http.StatusNotFound {
return nil, &SandboxNotFoundError{SandboxID: s.ID}
}
return nil, &Error{StatusCode: resp.StatusCode, Message: string(respBody)}
}
var info SnapshotInfo
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
return nil, fmt.Errorf("e2b: decode snapshot response: %w", err)
}
return &info, nil
}