Documentation
¶
Overview ¶
Package e2b provides a Go client for the E2B cloud sandbox API.
E2B sandboxes are lightweight microVMs that can run commands, access a filesystem, and be configured with environment variables.
Basic usage:
client, err := e2b.NewClient(e2b.ClientConfig{
APIKey: os.Getenv("E2B_API_KEY"),
})
if err != nil {
log.Fatal(err)
}
sandbox, err := client.NewSandbox(context.Background(), e2b.SandboxConfig{
Template: "base",
EnvVars: map[string]string{"VALUE": "hello"},
})
if err != nil {
log.Fatal(err)
}
defer sandbox.Close()
result, err := sandbox.Commands.Run("echo", []string{"hello"})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Stdout)
Index ¶
- Constants
- func WithFileUser(user string) fileUserOption
- type Client
- type ClientConfig
- type CommandResult
- type CommandService
- type Error
- type FileInfo
- type FileNotFoundError
- type FilesystemService
- func (f *FilesystemService) Read(ctx context.Context, path string, opts ...ReadOption) (io.ReadCloser, error)
- func (f *FilesystemService) ReadBytes(ctx context.Context, path string, opts ...ReadOption) ([]byte, error)
- func (f *FilesystemService) ReadString(ctx context.Context, path string, opts ...ReadOption) (string, error)
- func (f *FilesystemService) Write(ctx context.Context, path string, r io.Reader, opts ...WriteOption) (*FileInfo, error)
- func (f *FilesystemService) WriteBytes(ctx context.Context, path string, b []byte, opts ...WriteOption) (*FileInfo, error)
- func (f *FilesystemService) WriteString(ctx context.Context, path string, s string, opts ...WriteOption) (*FileInfo, error)
- type ListSnapshotsOption
- type ListSnapshotsResult
- type LogsOption
- type ReadOption
- type RunOption
- type Sandbox
- func (s *Sandbox) Close() error
- func (s *Sandbox) CloseWithContext(ctx context.Context) error
- func (s *Sandbox) CreateSnapshot(ctx context.Context, name ...string) (*SnapshotInfo, error)
- func (s *Sandbox) Info() (*SandboxInfo, error)
- func (s *Sandbox) InfoWithContext(ctx context.Context) (*SandboxInfo, error)
- func (s *Sandbox) Logs(opts ...LogsOption) ([]SandboxLogEntry, error)
- func (s *Sandbox) LogsWithContext(ctx context.Context, opts ...LogsOption) ([]SandboxLogEntry, error)
- func (s *Sandbox) Metrics() ([]SandboxMetric, error)
- func (s *Sandbox) MetricsWithContext(ctx context.Context) ([]SandboxMetric, error)
- func (s *Sandbox) Pause() error
- func (s *Sandbox) PauseWithContext(ctx context.Context) error
- func (s *Sandbox) Resume(timeoutSeconds int) error
- func (s *Sandbox) ResumeWithContext(ctx context.Context, timeoutSeconds int) error
- func (s *Sandbox) SetTimeout(timeoutSeconds int) error
- func (s *Sandbox) SetTimeoutWithContext(ctx context.Context, timeoutSeconds int) error
- type SandboxConfig
- type SandboxInfo
- type SandboxLifecycle
- type SandboxLogEntry
- type SandboxMetric
- type SandboxNotFoundError
- type SnapshotInfo
- type TimeoutError
- type VolumeMount
- type WriteOption
Constants ¶
const ( // DefaultAPIBaseURL is the default E2B API endpoint. DefaultAPIBaseURL = "https://api.e2b.app" // DefaultTemplate is the default sandbox template. DefaultTemplate = "base" // DefaultTimeout is the default sandbox lifetime in seconds. DefaultTimeout = 300 // DefaultCommandTimeout is the default command execution timeout. DefaultCommandTimeout = 60 * time.Second )
Variables ¶
This section is empty.
Functions ¶
func WithFileUser ¶
func WithFileUser(user string) fileUserOption
WithFileUser sets the sandbox user for the file operation. The returned value satisfies both ReadOption and WriteOption.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the E2B API client. Create one with NewClient and reuse it for all operations — it holds shared configuration like the API key.
func NewClient ¶
func NewClient(cfgs ...ClientConfig) (*Client, error)
NewClient creates a new E2B client. If no config is provided, the API key is read from the E2B_API_KEY environment variable.
func (*Client) ListSandboxes ¶
func (c *Client) ListSandboxes(ctx context.Context) ([]SandboxInfo, error)
ListSandboxes returns all running sandboxes for this client's API key.
func (*Client) ListSnapshots ¶
func (c *Client) ListSnapshots(ctx context.Context, opts ...ListSnapshotsOption) (*ListSnapshotsResult, error)
ListSnapshots returns snapshots for this client's API key.
func (*Client) NewSandbox ¶
NewSandbox creates a new E2B sandbox microVM. The caller should call Close when the sandbox is no longer needed.
type ClientConfig ¶
type ClientConfig struct {
// APIKey is the E2B API key. If empty, the E2B_API_KEY environment variable is used.
APIKey string
// APIBaseURL overrides the default API base URL.
APIBaseURL string
// SandboxDomain overrides the default sandbox domain.
SandboxDomain string
// HTTPClient is the HTTP client used for API requests.
// If nil, http.DefaultClient is used.
HTTPClient *http.Client
}
ClientConfig configures a new Client.
type CommandResult ¶
type CommandResult struct {
// Stdout is the standard output of the command.
Stdout string
// Stderr is the standard error output of the command.
Stderr string
// ExitCode is the process exit code.
ExitCode int
}
CommandResult holds the output of a completed command.
type CommandService ¶
type CommandService struct {
// contains filtered or unexported fields
}
CommandService provides command execution within a sandbox.
func (*CommandService) Run ¶
func (c *CommandService) Run(cmd string, args []string, opts ...RunOption) (*CommandResult, error)
Run executes a command in the sandbox and returns the result. It blocks until the command completes.
func (*CommandService) RunWithContext ¶
func (c *CommandService) RunWithContext(ctx context.Context, cmd string, args []string, opts ...RunOption) (*CommandResult, error)
RunWithContext executes a command in the sandbox using the provided context for cancellation and deadline control.
type Error ¶
type Error struct {
// StatusCode is the HTTP status code, if applicable.
StatusCode int
// Message describes what went wrong.
Message string
}
Error represents an error returned by the E2B API or SDK.
type FileInfo ¶
type FileInfo struct {
Name string `json:"name"`
Path string `json:"path"`
Type string `json:"type,omitempty"`
}
FileInfo describes a file written to the sandbox filesystem.
type FileNotFoundError ¶
type FileNotFoundError struct {
Path string
}
FileNotFoundError is returned when the requested path does not exist in the sandbox.
func (*FileNotFoundError) Error ¶
func (e *FileNotFoundError) Error() string
Error implements the error interface.
type FilesystemService ¶
type FilesystemService struct {
// contains filtered or unexported fields
}
FilesystemService provides file read and write operations within a sandbox.
func (*FilesystemService) Read ¶
func (f *FilesystemService) Read(ctx context.Context, path string, opts ...ReadOption) (io.ReadCloser, error)
Read fetches the raw content of the file at path inside the sandbox. The caller must close the returned ReadCloser when done. For small files, ReadBytes or ReadString are more convenient.
func (*FilesystemService) ReadBytes ¶
func (f *FilesystemService) ReadBytes(ctx context.Context, path string, opts ...ReadOption) ([]byte, error)
ReadBytes fetches the full content of the file at path as a byte slice.
func (*FilesystemService) ReadString ¶
func (f *FilesystemService) ReadString(ctx context.Context, path string, opts ...ReadOption) (string, error)
ReadString fetches the full content of the file at path as a string.
func (*FilesystemService) Write ¶
func (f *FilesystemService) Write(ctx context.Context, path string, r io.Reader, opts ...WriteOption) (*FileInfo, error)
Write uploads data from r to path inside the sandbox. The file is created if it does not exist and overwritten if it does. Parent directories are created automatically by envd. r may be any io.Reader: *os.File, *bytes.Reader, strings.NewReader, io.Pipe, etc.
func (*FilesystemService) WriteBytes ¶
func (f *FilesystemService) WriteBytes(ctx context.Context, path string, b []byte, opts ...WriteOption) (*FileInfo, error)
WriteBytes writes b to path inside the sandbox.
func (*FilesystemService) WriteString ¶
func (f *FilesystemService) WriteString(ctx context.Context, path string, s string, opts ...WriteOption) (*FileInfo, error)
WriteString writes s to path inside the sandbox.
type ListSnapshotsOption ¶
type ListSnapshotsOption func(*listSnapshotsParams)
ListSnapshotsOption configures a ListSnapshots request.
func WithSnapshotLimit ¶
func WithSnapshotLimit(n int) ListSnapshotsOption
WithSnapshotLimit sets the maximum number of snapshots to return (default 100).
func WithSnapshotNextToken ¶
func WithSnapshotNextToken(token string) ListSnapshotsOption
WithSnapshotNextToken sets the pagination token from a previous ListSnapshotsResult.
func WithSnapshotSandboxID ¶
func WithSnapshotSandboxID(id string) ListSnapshotsOption
WithSnapshotSandboxID filters snapshots by the source sandbox ID.
type ListSnapshotsResult ¶
type ListSnapshotsResult struct {
Snapshots []SnapshotInfo
NextToken string
}
ListSnapshotsResult holds the result of a ListSnapshots call, including pagination.
type LogsOption ¶
type LogsOption func(*logsParams)
LogsOption configures a Logs request.
func WithDirection ¶
func WithDirection(d string) LogsOption
WithDirection sets the sort order: "forward" (oldest first) or "backward" (newest first, default).
func WithLevel ¶
func WithLevel(l string) LogsOption
WithLevel filters logs by level: "debug", "info", "warn", or "error".
func WithLimit ¶
func WithLimit(n int) LogsOption
WithLimit sets the maximum number of log entries to return (default 1000).
func WithSearch ¶
func WithSearch(q string) LogsOption
WithSearch filters logs by a text search on the message field.
type ReadOption ¶
type ReadOption interface {
// contains filtered or unexported methods
}
ReadOption configures a Read, ReadBytes, or ReadString call.
func WithReadTimeout ¶
func WithReadTimeout(d time.Duration) ReadOption
WithReadTimeout overrides the HTTP timeout for a Read call.
type RunOption ¶
type RunOption func(*runConfig)
RunOption configures a single command execution.
func WithTimeout ¶
WithTimeout sets the command timeout. Defaults to DefaultCommandTimeout (60s).
type Sandbox ¶
type Sandbox struct {
// ID is the unique identifier of the sandbox.
ID string
// Commands provides command execution within the sandbox.
Commands *CommandService
// Filesystem provides file read and write operations within the sandbox.
Filesystem *FilesystemService
// contains filtered or unexported fields
}
Sandbox represents a running E2B sandbox microVM.
func (*Sandbox) CloseWithContext ¶
CloseWithContext destroys the sandbox using the provided context.
func (*Sandbox) CreateSnapshot ¶
CreateSnapshot creates a snapshot of the sandbox's current state. An optional name can be provided; if omitted, the API generates an ID.
func (*Sandbox) Info ¶
func (s *Sandbox) Info() (*SandboxInfo, error)
Info retrieves detailed information about the sandbox.
func (*Sandbox) InfoWithContext ¶
func (s *Sandbox) InfoWithContext(ctx context.Context) (*SandboxInfo, error)
InfoWithContext retrieves detailed information about the sandbox using the provided context.
func (*Sandbox) Logs ¶
func (s *Sandbox) Logs(opts ...LogsOption) ([]SandboxLogEntry, error)
Logs retrieves structured log entries for the sandbox.
func (*Sandbox) LogsWithContext ¶
func (s *Sandbox) LogsWithContext(ctx context.Context, opts ...LogsOption) ([]SandboxLogEntry, error)
LogsWithContext retrieves structured log entries using the provided context.
func (*Sandbox) Metrics ¶
func (s *Sandbox) Metrics() ([]SandboxMetric, error)
Metrics retrieves resource usage metrics for the sandbox.
func (*Sandbox) MetricsWithContext ¶
func (s *Sandbox) MetricsWithContext(ctx context.Context) ([]SandboxMetric, error)
MetricsWithContext retrieves resource usage metrics using the provided context.
func (*Sandbox) Pause ¶
Pause pauses the sandbox, stopping billing while preserving state. A paused sandbox can be resumed with Resume.
func (*Sandbox) PauseWithContext ¶
PauseWithContext pauses the sandbox using the provided context.
func (*Sandbox) Resume ¶
Resume resumes a paused sandbox with the given lifetime timeout in seconds.
func (*Sandbox) ResumeWithContext ¶
ResumeWithContext resumes a paused sandbox using the provided context.
func (*Sandbox) SetTimeout ¶
SetTimeout updates the sandbox lifetime timeout in seconds.
type SandboxConfig ¶
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
}
SandboxConfig holds the configuration for creating a new sandbox.
type SandboxInfo ¶
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"`
}
SandboxInfo holds details about a sandbox.
type SandboxLifecycle ¶
type SandboxLifecycle struct {
AutoResume bool `json:"autoResume"`
OnTimeout string `json:"onTimeout"` // "keep" or "kill"
}
SandboxLifecycle holds lifecycle configuration for a sandbox.
type SandboxLogEntry ¶
type SandboxLogEntry struct {
Level string `json:"level"`
Message string `json:"message"`
Timestamp string `json:"timestamp"`
Fields map[string]string `json:"fields"`
}
SandboxLogEntry holds a single structured log entry from a sandbox.
type SandboxMetric ¶
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"`
}
SandboxMetric holds a single resource usage snapshot for a sandbox.
type SandboxNotFoundError ¶
type SandboxNotFoundError struct {
SandboxID string
}
SandboxNotFoundError is returned when a sandbox cannot be found.
func (*SandboxNotFoundError) Error ¶
func (e *SandboxNotFoundError) Error() string
Error implements the error interface.
type SnapshotInfo ¶
SnapshotInfo holds information about a sandbox snapshot.
type TimeoutError ¶
type TimeoutError struct {
Message string
}
TimeoutError is returned when an operation exceeds its deadline.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
Error implements the error interface.
type VolumeMount ¶
VolumeMount represents a mounted volume in the sandbox.
type WriteOption ¶
type WriteOption interface {
// contains filtered or unexported methods
}
WriteOption configures a Write, WriteBytes, or WriteString call.
func WithWriteTimeout ¶
func WithWriteTimeout(d time.Duration) WriteOption
WithWriteTimeout overrides the HTTP timeout for a Write call.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
envvars
command
|
|
|
files
command
|
|
|
sandbox-info
command
|
|
|
internal
|
|