slicer

package module
v0.0.30 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 20 Imported by: 1

README

Golang SDK for Slicer

SDK for SlicerVM.com

Table of Contents

Installation

go get github.com/slicervm/sdk@latest

Features

  • VM Management: Create, list, delete, pause, and resume VMs.
  • Execute Commands in VMs: Run commands in VMs and stream command output (stdout/stderr).
  • File Management: Upload and download files to/from VMs with CpToVM and CpFromVM.
  • Secret Management: Securely manage secrets like API keys or other sensitive information for VMs.
  • Port Forwarding: Bidirectional port forwarding with support for TCP ports and UNIX sockets.
  • Pause/Resume: Pause VM CPU usage, then resume instantly when needed.

Connecting to UNIX Sockets

The SDK supports connecting directly to the Slicer API via a UNIX socket. Simply pass the socket path as the baseURL when creating a client:

// Connect via Unix socket
client := sdk.NewSlicerClient("/var/run/slicer/api.sock", token, userAgent, nil)

// Then use normally
ctx := context.Background()
hostGroups, err := client.GetHostGroups(ctx)

The client automatically detects UNIX socket paths (starting with / or ./) and configures the HTTP transport accordingly.

Port Forwarding with UNIX Sockets

Bidirectional port forwarding now supports UNIX sockets on either side or both. Forward local or remote TCP ports and UNIX sockets in any combination.

For now you need to use the CLI and an "exec" to access port-forwarding.

You can also use SSH tunnels via Go code, if you have SSH in your microVMs.

Supported on: Linux, Darwin, and WSL.

Pause and Resume VMs

Control VM CPU usage with instant pause/resume:

// Pause a VM
err := client.PauseVM(ctx, "vm-1")

// Resume a VM
err := client.ResumeVM(ctx, "vm-1")

SDK Methods Reference

Key concepts

User-facing documentation may refer to Sandboxes and Services. These are logical concepts, not API primitives.

Primitives:

  • Host Group - Host Groups define the template or specification for a Virtual Machine. A slicer daemon can have multiple host groups, but most use-cases should use only one. Host Groups are defined in YAML, and not via API at this time.
  • VM - A virtual machine - (sometimes called Node). Theses are either launched via an initial count value per Host Group, or on demand via API.

When you want a "Sandbox" (read: disposable VM launched via API), it's recommended that you have count: 0 in your host group. VMs launched via API are backed by a persistent disk or snapshot whilst running, which is removed when they terminate.

When you want to host a "Service" or run a server, such as a Kubernetes cluster, or a version of your application, it's best to write a succinct name for the host group such as "k3s" or "app" and then define how many VMs you'll need via count: 1, or count: 3, etc.

VM Operations
Method Description Parameters Returns
CreateVM(ctx, groupName, request) Create a new VM in a host group ctx (context.Context), groupName (string), request (SlicerCreateNodeRequest) (*SlicerCreateNodeResponse, error)
DeleteVM(ctx, groupName, hostname) Delete a VM from a host group ctx (context.Context), groupName (string), hostname (string) (*SlicerDeleteResponse, error)
ListVMs(ctx) List all VMs across all host groups ctx (context.Context) ([]SlicerNode, error)
GetHostGroups(ctx) Fetch all host groups ctx (context.Context) ([]SlicerHostGroup, error)
GetHostGroupNodes(ctx, groupName) Fetch nodes for a specific host group ctx (context.Context), groupName (string) ([]SlicerNode, error)
DeleteNode(groupName, nodeName) Delete a node from a host group groupName (string), nodeName (string) error
PauseVM(ctx, hostname) Pause a running VM to save CPU cost ctx (context.Context), hostname (string) error
ResumeVM(ctx, hostname) Resume a paused VM ctx (context.Context), hostname (string) error
Shutdown(ctx, hostname, request) Shutdown or reboot a VM ctx (context.Context), hostname (string), request (*SlicerShutdownRequest) error
GetVMStats(ctx, hostname) Get CPU, memory, and disk statistics for a VM or all VMs ctx (context.Context), hostname (string, empty for all) ([]SlicerNodeStat, error)
GetVMLogs(ctx, hostname, lines) Get recent logs from a VM ctx (context.Context), hostname (string), lines (int, -1 for all) (*SlicerLogsResponse, error)
GetInfo(ctx) Fetch server version and build information ctx (context.Context) (*SlicerInfo, error)
Guest Operations
Method Description Parameters Returns
Exec(ctx, hostname, request) Execute a command in a VM and stream output line-by-line ctx (context.Context), hostname (string), request (SlicerExecRequest) (chan SlicerExecWriteResult, error)
CpToVM(ctx, vmName, localPath, vmPath, uid, gid, permissions, mode) Upload a file/directory to a VM ctx (context.Context), vmName (string), localPath (string), vmPath (string), uid (uint32), gid (uint32), permissions (string), mode (string: "tar" or "binary") error
CpFromVM(ctx, vmName, vmPath, localPath, permissions, mode) Download a file/directory from a VM ctx (context.Context), vmName (string), vmPath (string), localPath (string), permissions (string), mode (string: "tar" or "binary") error
GetAgentHealth(ctx, hostname, includeStats) Check VM agent health and optionally get system stats ctx (context.Context), hostname (string), includeStats (bool) (*SlicerAgentHealthResponse, error)
Secret Management
Method Description Parameters Returns
CreateSecret(ctx, request) Create a new secret for VMs to use. Returns ErrSecretExists if a secret with the same name already exists. ctx (context.Context), request (CreateSecretRequest) error
ListSecrets(ctx) List all secrets (metadata only, not values for security reasons) ctx (context.Context) ([]Secret, error)
PatchSecret(ctx, secretName, request) Update an existing secret with new data and/or metadata. Only provided fields are modified. ctx (context.Context), secretName (string), request (UpdateSecretRequest) error
DeleteSecret(ctx, secretName) Delete a secret ctx (context.Context), secretName (string) error

Documentation

Samples/Examples

Quick start

Create a new slicer config with a count of 0.

Every VM launched by API will be ephemeral, so it'll be deleted after running sudo -E slicer vm shutdown NAME, or when it's deleted either by an API call, this slicer daemon shutting down, or when you delete the VM via REST API.

The first launch will take the name api-1, then api-2 and so forth. You can attach tags when you create the VM, if you want a stable name that can be looked up via the list endpoint.

slicer new api \
    --count=0 \
    --graceful-shutdown=false \
    --ram 4 \
    --cpu 2 > api.yaml

Start Slicer:

sudo -E slicer up ./api.yaml

Create a VM (node) in a host group with the default RAM/CPU settings as defined in the host group.

package main

import (
    "fmt"
    "os"
    "context"
    
    sdk "github.com/slicervm/sdk"
)

func main() {
    // Typically you'd load these from environment variables
    baseURL := os.Getenv("SLICER_URL")      // API base URL
    token := os.Getenv("SLICER_TOKEN")      // Your API token
    userAgent := "my-microvm-client/1.0"
    hostGroup := "api"                       // Existing host group name

    client := sdk.NewSlicerClient(baseURL, token, userAgent, nil /* or &http.Client{} */)

    createReq := sdk.SlicerCreateNodeRequest{
        RamBytes:      4 * 1024 * 1024 * 1024, // 4GB RAM 
        CPUs:       2,
        Userdata: `#!/bin/bash
echo 'Bootstrapping...'
ping -c3 google.com

sudo reboot
`,
        SSHKeys: []string{"ssh-rsa AAAA..."}, // Optional: inject public SSH keys
        ImportUser: "alexellis", // Optional: Import GitHub keys for a specific user
    }

    ctx := context.Background()
    node, err := client.CreateVM(ctx, hostGroup, createReq)
    if err != nil {
        panic(fmt.Errorf("failed to create node: %w", err))
    }

    fmt.Printf("Created VM: hostname=%s ip=%s created_at=%s\n", node.Hostname, node.IP, node.CreatedAt)
    fmt.Printf("Parsed IP only: %s\n", node.IPAddress())
}

Run the program i.e. after running go build -o client main.go:

SLICER_URL=http://127.0.0.1:8080 SLICER_TOKEN="$(sudo cat /var/lib/slicer/auth/token)" ./client

You'll find the logs for the microVM at /var/log/slicer/HOSTNAME.txt, showing the userdata executing.

Notes:

  • The argument order for NewSlicerClient is (baseURL, token, userAgent, httpClient).
  • If RamBytes or CPUs are not the values configured on the host group are used; Userdata, SSHKeys and ImportUser are optional.
  • Userdata runs on first boot; keep it idempotent.
  • Use a persistent http.Client (e.g. with timeout) in production instead of nil.

See a more minimal example at: examples/create/main.go

Documentation

Index

Constants

View Source
const NonRootUser = uint32(math.MaxUint32)

Variables

View Source
var (
	// ErrSecretExists is an error returned when a secret with given name already exists.
	ErrSecretExists = errors.New("secret already exists")
)

Functions

func ExtractTarStream added in v0.0.10

func ExtractTarStream(ctx context.Context, r io.Reader, extractDir string, uid, gid uint32, excludePatterns ...string) error

ExtractTarStream extracts a tar stream from r into extractDir. Only handles regular files and directories. Preserves mtime and executable bit. Normalizes permissions (strips setuid/setgid/sticky bits). Skips all other entry types. If uid or gid are non-zero, files will be chowned to that uid/gid after creation. Note: Permissions are set when opening files (efficient), chown is only applied if uid/gid are non-zero.

func ExtractTarToPath added in v0.0.10

func ExtractTarToPath(ctx context.Context, r io.Reader, dest string, uid, gid uint32, excludePatterns ...string) error

ExtractTarToPath extracts a tar stream to a local path with cp-like renaming. If dest exists and is a directory, extracts into it. Otherwise extracts and renames. No temporary directories are used - extraction happens directly. If uid or gid are non-zero, files will be chowned to that uid/gid after creation.

func GiB added in v0.0.17

func GiB(gb int64) int64

GB converts gigabytes to bytes

func MiB added in v0.0.17

func MiB(mb int64) int64

MB converts megabytes to bytes

func StreamTarArchive added in v0.0.10

func StreamTarArchive(ctx context.Context, w io.Writer, parentDir, baseName string, excludePatterns ...string) error

StreamTarArchive streams a tar archive of regular files and directories to w. Only handles regular files and directories. Preserves mtime and executable bit. Skips symlinks, devices, and other special files.

func ValidRelPath added in v0.0.10

func ValidRelPath(p string) bool

ValidRelPath validates that a path is a valid relative path and doesn't contain directory traversal attempts. Note: Backslashes are allowed in filenames (e.g., systemd unit files with escaped characters). Since tar paths use forward slashes as separators (via filepath.ToSlash()), any backslashes in the path are part of the filename, not path separators.

Types

type CreateSecretRequest added in v0.0.6

type CreateSecretRequest struct {
	// Name is the unique name of the secret
	Name string `json:"name"`
	// Data is the secret content
	Data string `json:"data"`
	// Permissions specifies the file permissions (defaults to system default)
	Permissions string `json:"permissions,omitempty"`

	// GID is the user ID that should own the secret file. If not set, the default for
	// a uint32 will be used i.e root.
	UID uint32 `json:"uid,omitempty"`

	// GID is the group ID that should own the secret file. If not set, the default for
	// a uint32 will be used i.e root.
	GID uint32 `json:"gid,omitempty"`
}

CreateSecretRequest is the payload for creating a new secret via the REST API.

type ExitError added in v0.0.23

type ExitError struct {
	*RemoteProcessState

	// Stderr holds stderr output if it was collected.
	Stderr []byte
}

ExitError is returned by RemoteCmd methods when a command exits with a non-zero status. It mirrors exec.ExitError but for remote executions.

func (*ExitError) Error added in v0.0.23

func (e *ExitError) Error() string

Error returns a string representation of the exit error.

func (*ExitError) Unwrap added in v0.0.23

func (e *ExitError) Unwrap() error

Unwrap returns the underlying process state for errors.Is/As compatibility.

type RemoteCmd added in v0.0.23

type RemoteCmd struct {
	// Path is the command to run. This is the only field that must be set.
	// If Path contains no path separators, it will be resolved using the
	// remote system's PATH.
	Path string

	// Args holds command line arguments, including the command as Args[0].
	// If Args is empty or nil, Run uses {Path}.
	Args []string

	// Env specifies the environment of the process.
	// Each entry is of the form "key=value".
	// If Env is nil, the remote process inherits the default environment.
	// Note: Environment variable support depends on the remote agent's capabilities.
	Env []string

	// Dir specifies the working directory of the command.
	// If Dir is empty, the command runs in the remote agent's default directory.
	Dir string

	// Stdin specifies the process's standard input.
	// If Stdin is nil, the process reads from an empty reader.
	// If Stdin is an *os.File, it is connected directly.
	// Otherwise, a goroutine reads from Stdin and delivers to the remote.
	Stdin io.Reader

	// Stdout specifies the process's standard output.
	// If Stdout is nil, output is discarded.
	// If Stdout is an *os.File, output is written directly.
	// Otherwise, a goroutine copies output to Stdout.
	Stdout io.Writer

	// Stderr specifies the process's standard error.
	// If Stderr is nil, error output is discarded.
	// If Stderr is the same as Stdout, both are combined.
	// Otherwise, a goroutine copies error output to Stderr.
	Stderr io.Writer

	// ProcessState contains information about an exited process.
	// It is available after a call to Wait or Run.
	ProcessState *RemoteProcessState

	// UID specifies the user ID to run the command as (Linux only).
	// If zero, uses the remote system's default (usually root).
	UID uint32

	// GID specifies the group ID to run the command as (Linux only).
	// If zero, uses the remote system's default (usually root).
	GID uint32

	// Shell specifies the shell interpreter to use.
	// If empty, defaults to "/bin/bash" on the remote.
	// Set to an empty string explicitly to disable shell interpretation.
	Shell string
	// contains filtered or unexported fields
}

RemoteCmd represents a remote command to be executed on a VM. It mirrors the os/exec.Cmd API but executes commands on remote VMs.

A RemoteCmd cannot be reused after calling Run, Output, or CombinedOutput.

func (*RemoteCmd) CombinedOutput added in v0.0.23

func (c *RemoteCmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the command and returns its combined stdout and stderr.

func (*RemoteCmd) Environ added in v0.0.23

func (c *RemoteCmd) Environ() []string

Environ returns a copy of the environment in which the command would be run.

func (*RemoteCmd) Output added in v0.0.23

func (c *RemoteCmd) Output() ([]byte, error)

Output runs the command and returns its standard output.

If the command fails, the error is of type *ExitError. If stderr was not otherwise collected, the ExitError.Stderr field will contain any captured stderr output.

func (*RemoteCmd) Run added in v0.0.23

func (c *RemoteCmd) Run() error

Run starts the specified command and waits for it to complete.

If the command runs successfully and copies all output, the error is nil. If the command fails to start or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for other situations.

func (*RemoteCmd) Start added in v0.0.23

func (c *RemoteCmd) Start() error

Start starts the specified command but does not wait for it to complete.

If Start returns successfully, the c.ProcessState field will be set after a successful call to Wait.

After a successful call to Start, the Wait method must be called to release associated system resources.

func (*RemoteCmd) StderrPipe added in v0.0.23

func (c *RemoteCmd) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.

Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed.

For the same reason, it is incorrect to call Run when using StderrPipe.

func (*RemoteCmd) StdinPipe added in v0.0.23

func (c *RemoteCmd) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts.

The pipe will be closed automatically after Wait sees the command exit. The caller only needs to call Close to force the pipe to close sooner. For example, if the command being run won't exit until standard input is closed, the caller must close the pipe.

func (*RemoteCmd) StdoutPipe added in v0.0.23

func (c *RemoteCmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts.

Wait will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed.

For the same reason, it is incorrect to call Run when using StdoutPipe.

func (*RemoteCmd) String added in v0.0.23

func (c *RemoteCmd) String() string

String returns a human-readable description of the command. It is intended only for debugging, not for execution.

func (*RemoteCmd) Wait added in v0.0.23

func (c *RemoteCmd) Wait() error

Wait waits for the command to exit and waits for any copying to complete.

The command must have been started by Start.

If the command runs successfully, the error is nil. If the command fails, the error is of type *ExitError.

Wait releases any resources associated with the Cmd.

type RemoteProcessState added in v0.0.23

type RemoteProcessState struct {
	// contains filtered or unexported fields
}

RemoteProcessState stores information about an exited remote process. It mirrors os.ProcessState but for remote executions.

func (*RemoteProcessState) ExitCode added in v0.0.23

func (p *RemoteProcessState) ExitCode() int

ExitCode returns the exit code of the exited process. Returns -1 if the process hasn't exited or was terminated abnormally.

func (*RemoteProcessState) Exited added in v0.0.23

func (p *RemoteProcessState) Exited() bool

Exited reports whether the program has exited.

func (*RemoteProcessState) Pid added in v0.0.23

func (p *RemoteProcessState) Pid() int

Pid returns the process id of the exited process. Returns -1 if the PID is not available (remote execution).

func (*RemoteProcessState) String added in v0.0.23

func (p *RemoteProcessState) String() string

String returns a human-readable description of the process state.

func (*RemoteProcessState) Success added in v0.0.23

func (p *RemoteProcessState) Success() bool

Success reports whether the program exited successfully (exit status 0).

type Secret added in v0.0.6

type Secret struct {
	// Name is the unique name of the secret
	Name string `json:"name"`
	// Size is the size of the secret data in bytes
	Size int64 `json:"size"`
	// Permissions specifies the file permissions for the secret (e.g., "0600")
	Permissions string `json:"permissions"`

	// GID is the user ID that should own the secret file. If not set, the default for
	// a uint32 will be used i.e root.
	UID uint32 `json:"uid,omitempty"`

	// GID is the group ID that should own the secret file. If not set, the default for
	// a uint32 will be used i.e root.
	GID uint32 `json:"gid,omitempty"`

	// ModifiedAt is the time the secret was last modified
	ModifiedAt *time.Time `json:"modified_at,omitempty"`
}

Secret represents a secret stored in the slicer system. Secrets can be used to store sensitive configuration data, keys, or other private information that can be mounted into nodes or used by services.

type SlicerAgentHealthResponse added in v0.0.13

type SlicerAgentHealthResponse struct {
	// Hostname is the hostname of the agent
	Hostname string `json:"hostname,omitempty"`

	// Uptime is the uptime of the agent
	AgentUptime time.Duration `json:"agent_uptime,omitempty"`

	// AgentVersion is the version of the agent
	AgentVersion string `json:"agent_version,omitempty"`

	// SystemUptime is the uptime of the system
	SystemUptime time.Duration `json:"system_uptime,omitempty"`

	// UserdataRan indicates whether the user data script has completed executing
	UserdataRan bool `json:"userdata_ran,omitempty"`
}

type SlicerClient

type SlicerClient struct {
	// contains filtered or unexported fields
}

SlicerClient handles all HTTP communication with the Slicer API

func NewClientFromEnv added in v0.0.30

func NewClientFromEnv(baseURL, userAgent string, httpClient *http.Client) (*SlicerClient, error)

NewClientFromEnv creates a client using environment credentials.

The token is loaded from env as: - SLICER_TOKEN (preferred), or - SLICER_TOKEN_FILE.

Parameters: - baseURL: if empty, loaded from SLICER_URL - userAgent: if empty, loaded from SLICER_USER_AGENT or "slicer-sdk-go/1.0" - httpClient: optional custom HTTP client passed to NewSlicerClient

func NewSlicerClient

func NewSlicerClient(baseURL, token string, userAgent string, httpClient *http.Client) *SlicerClient

NewSlicerClient creates a new Slicer API client If baseURL is a Unix socket path (starts with "/" or "./"), it will create a custom HTTP client that uses Unix socket transport.

func NewSlicerClientFromEnv added in v0.0.30

func NewSlicerClientFromEnv() (*SlicerClient, error)

NewSlicerClientFromEnv creates a client from env using default userAgent and default http client. This keeps compatibility with the earlier env-only constructor shape.

func (*SlicerClient) Command added in v0.0.23

func (c *SlicerClient) Command(ctx context.Context, vmName string, name string, arg ...string) *RemoteCmd

Command returns a RemoteCmd to execute the named program on the specified VM. The returned Cmd's Args field is set to the command name followed by any arguments.

The provided context is used for the lifetime of the command execution. If the context is canceled, the command will be terminated.

func (*SlicerClient) CommandContext added in v0.0.23

func (c *SlicerClient) CommandContext(ctx context.Context, vmName string, name string, arg ...string) *RemoteCmd

CommandContext is an alias for Command that makes the API more familiar to users of os/exec.CommandContext.

func (*SlicerClient) CpFromVM added in v0.0.10

func (c *SlicerClient) CpFromVM(ctx context.Context, vmName, vmPath, localPath string, permissions, mode string, excludePatterns ...string) error

CpFromVM copies files from a VM path to a local path. The tar stream is received from the VM and extracted to localPath with proper renaming logic (supports renaming files/directories). If uid or gid are 0, the current user's UID/GID will be used. On Windows, chown operations are skipped (uid/gid are ignored).

func (*SlicerClient) CpToVM added in v0.0.10

func (c *SlicerClient) CpToVM(ctx context.Context, vmName, localPath, vmPath string, uid, gid uint32, permissions, mode string, excludePatterns ...string) error

CpToVM copies files from a local path to a VM path. The localPath can be a file or directory. The tar stream is created internally and sent to the VM. uid and gid specify the ownership for extracted files (0 means use default).

func (*SlicerClient) CreateSecret added in v0.0.6

func (c *SlicerClient) CreateSecret(ctx context.Context, request CreateSecretRequest) error

CreateSecret creates a new secret. Returns ErrSecretExists if a secret with the same name already exists. An error is returned if creation fails.

func (*SlicerClient) CreateVM added in v0.0.10

func (c *SlicerClient) CreateVM(ctx context.Context, groupName string, request SlicerCreateNodeRequest) (*SlicerCreateNodeResponse, error)

CreateVM creates a new VM in the specified host group

func (*SlicerClient) DeleteNode

func (c *SlicerClient) DeleteNode(groupName, nodeName string) error

DeleteNode deletes a node from the specified host group

func (*SlicerClient) DeleteSecret added in v0.0.6

func (c *SlicerClient) DeleteSecret(ctx context.Context, secretName string) error

DeleteSecret removes a secret. Returns an error if the secret doesn't exist or if the deletion fails.

func (*SlicerClient) DeleteVM added in v0.0.10

func (c *SlicerClient) DeleteVM(ctx context.Context, groupName, hostname string) (*SlicerDeleteResponse, error)

DeleteVM deletes a VM from a host group

func (*SlicerClient) Exec added in v0.0.9

func (c *SlicerClient) Exec(ctx context.Context, nodeName string, execReq SlicerExecRequest) (chan SlicerExecWriteResult, error)

Exec executes a command on the specified node and streams the output. The channel is unbuffered so the caller should read from it promptly to avoid blocking.

func (*SlicerClient) ExecWithReader added in v0.0.23

func (c *SlicerClient) ExecWithReader(ctx context.Context, nodeName string, execReq SlicerExecRequest, stdin io.Reader) (chan SlicerExecWriteResult, error)

ExecWithReader is like Exec but accepts a custom io.Reader for stdin instead of using os.Stdin.

func (*SlicerClient) GetAgentHealth added in v0.0.13

func (c *SlicerClient) GetAgentHealth(ctx context.Context, hostname string, includeStats bool) (*SlicerAgentHealthResponse, error)

GetAgentHealth fetches the health of the agent If includeStats is true, the response will include statistics about the system and agent.

func (*SlicerClient) GetHostGroupNodes

func (c *SlicerClient) GetHostGroupNodes(ctx context.Context, groupName string) ([]SlicerNode, error)

GetHostGroupNodes fetches nodes for a specific host group

func (*SlicerClient) GetHostGroups

func (c *SlicerClient) GetHostGroups(ctx context.Context) ([]SlicerHostGroup, error)

GetHostGroups fetches all host groups from the API

func (*SlicerClient) GetInfo added in v0.0.21

func (c *SlicerClient) GetInfo(ctx context.Context) (*SlicerInfo, error)

GetInfo fetches server version information from the /info endpoint

func (*SlicerClient) GetVMLogs added in v0.0.10

func (c *SlicerClient) GetVMLogs(ctx context.Context, hostname string, lines int) (*SlicerLogsResponse, error)

GetVMLogs fetches logs for a specific VM

func (*SlicerClient) GetVMStats added in v0.0.10

func (c *SlicerClient) GetVMStats(ctx context.Context, hostname string) ([]SlicerNodeStat, error)

GetVMStats fetches stats for all VMs or a specific VM if hostname is provided. If hostname is empty, returns stats for all VMs.

func (*SlicerClient) ListSecrets added in v0.0.6

func (c *SlicerClient) ListSecrets(ctx context.Context) ([]Secret, error)

ListSecrets retrieves all secrets. Note: The actual secret data is not returned for security reasons.

func (*SlicerClient) ListVMs added in v0.0.10

func (c *SlicerClient) ListVMs(ctx context.Context) ([]SlicerNode, error)

ListVMs fetches all VMs (nodes)

func (*SlicerClient) PatchSecret added in v0.0.6

func (c *SlicerClient) PatchSecret(ctx context.Context, secretName string, request UpdateSecretRequest) error

PatchSecret updates an existing secret with new data and/or metadata. Only the fields provided in the UpdateSecretRequest will be modified. Returns an error if the secret doesn't exist or if the update fails.

func (*SlicerClient) PauseVM added in v0.0.20

func (c *SlicerClient) PauseVM(ctx context.Context, hostname string) error

PauseVM pauses a running VM

func (*SlicerClient) RestoreVM added in v0.0.25

func (c *SlicerClient) RestoreVM(ctx context.Context, hostname string) error

RestoreVM restores a VM from a Firecracker snapshot

func (*SlicerClient) ResumeVM added in v0.0.20

func (c *SlicerClient) ResumeVM(ctx context.Context, hostname string) error

ResumeVM resumes a paused VM

func (*SlicerClient) Shutdown added in v0.0.19

func (c *SlicerClient) Shutdown(ctx context.Context, hostname string, request *SlicerShutdownRequest) error

Shutdown shuts down or reboots a VM. If request is nil, it defaults to shutdown action. The request Action field can be "shutdown" (halt) or "reboot" (restart).

func (*SlicerClient) SuspendVM added in v0.0.25

func (c *SlicerClient) SuspendVM(ctx context.Context, hostname string) error

SuspendVM suspends a running VM to disk (Firecracker snapshot)

type SlicerCpRequest added in v0.0.10

type SlicerCpRequest struct {
	VM   string // VM name
	Path string // Path on the VM
}

SlicerCpRequest contains parameters for copying files to/from a VM

type SlicerCreateNodeRequest

type SlicerCreateNodeRequest struct {
	RamBytes   int64    `json:"ram_bytes,omitempty"` // RAM size in bytes (must not exceed host group limit)
	CPUs       int      `json:"cpus,omitempty"`      // Number of CPUs (must not exceed host group limit)
	GPUCount   int      `json:"gpu_count,omitempty"`
	Persistent bool     `json:"persistent,omitempty"`
	DiskImage  string   `json:"disk_image,omitempty"`
	ImportUser string   `json:"import_user,omitempty"`
	SSHKeys    []string `json:"ssh_keys,omitempty"`
	Userdata   string   `json:"userdata,omitempty"`
	IP         string   `json:"ip,omitempty"`
	Tags       []string `json:"tags,omitempty"`
	Secrets    []string `json:"secrets,omitempty"`
}

SlicerCreateNodeRequest contains parameters for creating a node

type SlicerCreateNodeResponse

type SlicerCreateNodeResponse struct {
	Hostname  string    `json:"hostname"`
	IP        string    `json:"ip"`
	CreatedAt time.Time `json:"created_at"`
	Arch      string    `json:"arch,omitempty"`
}

SlicerCreateNodeResponse is the response from the REST API when creating a node.

func (*SlicerCreateNodeResponse) IPAddress

func (n *SlicerCreateNodeResponse) IPAddress() net.IP

type SlicerDeleteResponse added in v0.0.10

type SlicerDeleteResponse struct {
	Message     string `json:"message"`
	DiskRemoved string `json:"disk_removed"`
	Error       string `json:"error"`
}

SlicerDeleteResponse represents the response from the delete endpoint

type SlicerExecRequest added in v0.0.9

type SlicerExecRequest struct {
	Command     string   `json:"command,omitempty"`
	Args        []string `json:"args,omitempty"`
	Env         []string `json:"env,omitempty"`
	UID         uint32   `json:"uid,omitempty"`
	GID         uint32   `json:"gid,omitempty"`
	Stdin       bool     `json:"stdin,omitempty"`
	Stdout      bool     `json:"stdout,omitempty"`
	Stderr      bool     `json:"stderr,omitempty"`
	Shell       string   `json:"shell,omitempty"`
	Cwd         string   `json:"cwd,omitempty"`
	Permissions string   `json:"permissions,omitempty"`
}

SlicerExecRequest contains parameters for invoking a command within a VM.

type SlicerExecWriteResult added in v0.0.9

type SlicerExecWriteResult struct {
	Timestamp time.Time `json:"timestamp"`
	Stdout    string    `json:"stdout,omitempty"`
	Stderr    string    `json:"stderr,omitempty"`
	ExitCode  int       `json:"exit_code,omitempty"`
	Error     string    `json:"error,omitempty"`
}

ExecWriteResult represents output from commands executing within a microVM.

type SlicerHostGroup

type SlicerHostGroup struct {
	Name     string `json:"name,omitempty"`
	Count    int    `json:"count,omitempty"`
	RamBytes int64  `json:"ram_bytes,omitempty"` // RAM size in bytes
	CPUs     int    `json:"cpus,omitempty"`
	Arch     string `json:"arch,omitempty"`
	GPUCount int    `json:"gpu_count,omitempty"`
}

SlicerHostGroup represents a host group from the /hostgroup endpoint.

type SlicerInfo added in v0.0.21

type SlicerInfo struct {
	// Version is the version of the slicer server
	Version string `json:"version,omitempty"`

	// GitCommit is the git commit hash of the slicer server
	GitCommit string `json:"git_commit,omitempty"`

	// Platform indicates the server operating system (runtime.GOOS).
	Platform string `json:"platform,omitempty"`

	// Arch is the server architecture (runtime.GOARCH).
	Arch string `json:"arch,omitempty"`
}

SlicerInfo represents version and server information from the /info endpoint

type SlicerLogsResponse added in v0.0.10

type SlicerLogsResponse struct {
	Hostname string `json:"hostname"`
	Lines    int    `json:"lines"`
	Content  string `json:"content"`
}

SlicerLogsResponse represents the response from the logs endpoint

type SlicerNode

type SlicerNode struct {
	Hostname  string    `json:"hostname"`
	IP        string    `json:"ip"`
	RamBytes  int64     `json:"ram_bytes,omitempty"` // RAM size in bytes
	CPUs      int       `json:"cpus,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	Arch      string    `json:"arch,omitempty"`
	Tags      []string  `json:"tags,omitempty"`
	Status    string    `json:"status,omitempty"` // "Running" or "Paused"
}

SlicerNode represents a node managed by the slicer REST API.

type SlicerNodeStat added in v0.0.10

type SlicerNodeStat struct {
	Hostname  string          `json:"hostname"`
	IP        string          `json:"ip"`
	CreatedAt time.Time       `json:"created_at"`
	Snapshot  *SlicerSnapshot `json:"snapshot"`
	Error     string          `json:"error"`
}

SlicerNodeStat represents stats for a VM node

type SlicerShutdownRequest added in v0.0.19

type SlicerShutdownRequest struct {
	// Action specifies the shutdown action: "shutdown" (halt) or "reboot" (restart).
	// If empty, defaults to "shutdown".
	Action string `json:"action,omitempty"`
}

SlicerShutdownRequest contains parameters for shutting down or rebooting a VM. Action can be "shutdown" (default) to halt the VM or "reboot" to restart it.

type SlicerSnapshot added in v0.0.10

type SlicerSnapshot struct {
	Hostname             string    `json:"hostname"`
	Arch                 string    `json:"arch"`
	Timestamp            time.Time `json:"timestamp"`
	Uptime               string    `json:"uptime"`
	TotalCPUS            int       `json:"totalCpus"`
	TotalMemory          uint64    `json:"totalMemory"`
	MemoryUsed           uint64    `json:"memoryUsed"`
	MemoryAvailable      uint64    `json:"memoryAvailable"`
	MemoryUsedPercent    float64   `json:"memoryUsedPercent"`
	LoadAvg1             float64   `json:"loadAvg1"`
	LoadAvg5             float64   `json:"loadAvg5"`
	LoadAvg15            float64   `json:"loadAvg15"`
	DiskReadTotal        float64   `json:"diskReadTotal"`
	DiskWriteTotal       float64   `json:"diskWriteTotal"`
	NetworkReadTotal     float64   `json:"networkReadTotal"`
	NetworkWriteTotal    float64   `json:"networkWriteTotal"`
	DiskIOInflight       int64     `json:"diskIOInflight"`
	OpenConnections      int64     `json:"openConnections"`
	OpenFiles            int64     `json:"openFiles"`
	Entropy              int64     `json:"entropy"`
	DiskSpaceTotal       uint64    `json:"diskSpaceTotal"`
	DiskSpaceUsed        uint64    `json:"diskSpaceUsed"`
	DiskSpaceFree        uint64    `json:"diskSpaceFree"`
	DiskSpaceUsedPercent float64   `json:"diskSpaceUsedPercent"`
}

SlicerSnapshot represents a snapshot of VM metrics

type UpdateSecretRequest added in v0.0.6

type UpdateSecretRequest struct {
	// Data is the updated secret content
	Data string `json:"data"`
	// Permissions specifies the file permissions
	Permissions string `json:"permissions,omitempty"`

	// GID is the user ID that should own the secret file. If not set, the default for
	// a uint32 will be used i.e root.
	UID uint32 `json:"uid,omitempty"`

	// GID is the group ID that should own the secret file. If not set, the default for
	// a uint32 will be used i.e root.
	GID uint32 `json:"gid,omitempty"`
}

UpdateSecretRequest is the payload for updating an existing secret via the REST API. All fields are optional - only provided fields will be updated.

Directories

Path Synopsis
examples
box command
claude command
create command
k3s-userdata command
transform command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL