Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,22 @@ turned off.
bundle install
```

### A locally built plugin gem

The SDK depends on `unikraft-cloud-plugin-sandbox-api`. To work against a
build of it that is not on RubyGems yet, build it with the generator in
[plugin-sdk] (its README says how), install the `.gem` into the gem path the
bundle reads, and resolve without the index:

```sh
gem install --local --no-document path/to/unikraft-cloud-plugin-sandbox-api-<version>.gem
bundle install --local
```

`Gemfile.lock` then records it as an ordinary RubyGems dependency, so do not
add a `path:` source to the `Gemfile`. `rake check_package` installs the
plugin gems from the bundle's gem cache, so it needs no index either.

## Common tasks

```sh
Expand Down
2 changes: 2 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ PATH
remote: .
specs:
unikraft-cloud (0.0.0)
unikraft-cloud-plugin-sandbox-api (~> 1.0)

GEM
remote: https://rubygems.org/
Expand Down Expand Up @@ -48,6 +49,7 @@ GEM
unicode-display_width (3.3.0)
unicode-emoji (~> 4.3)
unicode-emoji (4.3.0)
unikraft-cloud-plugin-sandbox-api (1.0.2)

PLATFORMS
aarch64-linux
Expand Down
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ ukc.instances.stop([{ name: "web" }, { uuid: "550e8400-e29b-41d4-a716-4466554400
| `ukc.services` | `create`, `get`, `where`, `list`, `each`, `update`, `edit`, `delete` |
| `ukc.certificates` | `create`, `get`, `where`, `list`, `each`, `update`, `delete` |
| `ukc.users` | `quotas`, `quotas(uuid:)` |
| `ukc.metro(m).sandboxes` | `create` (with a block), `get`, `list`, `each`; see [Sandboxes](#sandboxes) |

Handles add the per-resource operations: `reload`, `start`, `stop`,
`suspend`, `delete`, `update`, `edit`, `wait`, `logs`, `metrics`, `history`
Expand All @@ -463,6 +464,71 @@ ukc.api.platform.images.get_images

See [`examples/`](./examples) for complete programs.

## Sandboxes

A sandbox is a virtual machine that runs whatever command you hand it: an
instance with the sandbox plugin attached. It lives in one metro, so it hangs
off a metro scope. With a block, `create` deletes the sandbox when the block
returns, however it returns:

```ruby
Unikraft::Cloud.open do |ukc|
ukc.metro(:fra).sandboxes.create(memory_mb: 1024) do |sb|
res = sb.run("echo hello") # a shell line
res.stdout # => "hello\n"
sb.run("ls", "-la", cwd: "/tmp").success? # an argument vector

sb.files.write("/work/a.txt", "hello\n")
sb.files.read("/work/a.txt") # => "hello\n" (binary)

sb.instance.update(memory_mb: 2048) # it is a real instance
end
end
```

`Unikraft::Cloud::Sandbox.create` and `.connect` do the same without a
client in hand: they build one from `token:` (or `UKC_TOKEN`), `metro:` (or
`UKC_METRO`) and the other `Unikraft::Cloud.new` options, or borrow one as
`client:`.

- **Creating.** The spec is what `instances.create` takes, plus `rom:` and
`plugin_name:`. The image defaults to `UKC_SANDBOX_IMAGE`, else
`debian-slim:latest`; memory to 2048 MB; `autokill` to five minutes of
stopped time. `create` waits for the machine (`boot_within:`, 30 s) and
then for the plugin (`ready: { within: 60 }`). A failed wait deletes the
machine and names the likely cause; `ready: false` skips the waits and
keeps a broken sandbox for inspection. A `template:`, `branch_from:` or
`checkpoint:` brings its own image, memory and plugin.
- **Reattaching.** `sandboxes.get(uuid:)` and `Sandbox.connect(uuid:,
metro:)` never wait and never delete; call `sb.ready` after a start or a
resume. `sandboxes.list` and `each` are the instance list, filtered to
those carrying the plugin.
- **Commands.** `run` waits and returns a `Result` (`stdout`, `stderr`,
`exitcode`, `success?`); a failing command is not an exception, and a
`within:` that runs out leaves `exitcode` nil and the command running.
`spawn` returns a `Command` at once:

```ruby
cat = sb.spawn("cat", cwd: "/work", env: { "LANG" => "C" })
cat.write("first line\n").close_write # standard input, like an IO
cat.wait(within: 10)
cat.logs.stdout # => "first line\n"
cat.read(:stdout, offset: -4096) # the raw tail, binary
sb.spawn("sleep 600").signal(:TERM)
```

- **Files.** `sb.files.read`, `write` (`append:`), `mkdir` (parents by
default) and `upload(dir, filename, data)`. Data is a String or anything
with `read`; a binary String travels as bytes, any other as UTF-8 text.

As with `instance.wait`, `within:` is how long a wait may take, and
`timeout:` is only ever the HTTP timeout of a request. A request held open
for a wait has its read timeout stretched to cover it, unless `timeout:`
says otherwise.

`sb.api` is the raw plugin client (`sb.api.commands`, `sb.api.fs`) from the
`unikraft-cloud-plugin-sandbox-api` gem, pinned to this sandbox.

## Errors

Any network failure or non-2xx response raises a `Unikraft::Cloud::Error`:
Expand Down
5 changes: 4 additions & 1 deletion Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ RuboCop::RakeTask.new(:lint)
desc "Install the built gem into a temporary GEM_HOME and require it"
task check_package: :build do
gem = Dir["pkg/unikraft-cloud-*.gem"].max_by { |f| File.mtime(f) }
# The plugin gems come from the bundle's own cache, so the check needs no
# index and also passes with a locally built plugin gem.
plugins = Bundler.load.specs.select { |s| s.name.start_with?("unikraft-cloud-plugin-") }
Dir.mktmpdir do |home|
env = { "GEM_HOME" => home, "GEM_PATH" => home }
Bundler.with_unbundled_env do
sh env, "gem", "install", "--local", "--no-document", gem
sh env, "gem", "install", "--local", "--no-document", *plugins.map(&:cache_file), gem
sh env, RbConfig.ruby, "-e",
'require "unikraft/cloud"; puts "unikraft-cloud " + Unikraft::Cloud::VERSION'
end
Expand Down
83 changes: 83 additions & 0 deletions examples/sandbox.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# frozen_string_literal: true

# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2026, Unikraft GmbH.
#
# Sandboxes: a virtual machine that runs whatever command you hand it. Run
# with:
# UKC_TOKEN=... ruby -Ilib examples/sandbox.rb

require "unikraft/cloud"

# The hot path: credentials and image from the environment, and the sandbox
# deleted when the block returns.
def hot_path
Unikraft::Cloud::Sandbox.create do |sb|
puts sb.run("echo hello").stdout # hello
end
end

def configured
sb = Unikraft::Cloud::Sandbox.create(
image: "debian-slim:latest",
memory_mb: 1024,
env: { "LOG_LEVEL" => "debug" },
rom: "plugins/sandbox:latest", # your own plugin ROM
token: ENV.fetch("UKC_TOKEN"),
metro: :fra,
boot_within: 60,
ready: { within: 30 }
)

# The instance underneath stays reachable, so its whole surface works.
inst = sb.instance
puts "#{inst.name} in #{sb.metro}: #{inst.state}, #{inst.memory_mb} MiB"

# A command takes a working directory and its own environment.
build = sb.run("ls -la && env", cwd: "/tmp", env: { "CI" => "1" })
puts "exit #{build.exitcode}: #{build.stdout}#{build.stderr}"
files_and_stdin(sb)

# The UUID and the metro are all a later process needs to attach again.
again = Unikraft::Cloud::Sandbox.connect(uuid: sb.uuid, metro: sb.metro)
puts "reconnected to #{again.uuid}"

# Without a block, delete it yourself.
sb.delete
end

def files_and_stdin(sandbox)
# Files go in and come back out.
sandbox.files.mkdir("/work/input")
sandbox.files.write("/work/input/a.txt", "hello\n")
sandbox.files.upload("/work/input", "data.csv", "id,name\n1,fra\n")
puts sandbox.files.read("/work/input/a.txt")

# `spawn` does not wait, so the command stays under your control: write to
# its standard input, wait for it, then read its logs. `signal(:TERM)`
# ends one that does not stop on its own.
cat = sandbox.spawn("cat", cwd: "/work")
cat.write("first line\n").write("last line\n").close_write
puts cat.wait(within: 10).logs.stdout
cat.delete
end

def through_a_client
# A client you already have opens the same door, and spends no second token.
Unikraft::Cloud.open do |ukc|
fra = ukc.metro(:fra)
fra.sandboxes.create(memory_mb: 512) { |sb| puts sb.run("uname", "-a").stdout }

# Every sandbox in the metro: the instance list, filtered by plugin.
fra.sandboxes.each { |sb| puts "- #{sb.uuid}" }
end
end

begin
hot_path
configured
through_a_client
rescue Unikraft::Cloud::Error => e
warn "API error (#{e.status || "?"}): #{e.message}"
exit 1
end
1 change: 1 addition & 0 deletions lib/unikraft/cloud.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@
require_relative "cloud/resources/service_groups"
require_relative "cloud/resources/certificates"
require_relative "cloud/resources/users"
require_relative "cloud/resources/sandboxes/sandboxes"
require_relative "cloud/client"
9 changes: 7 additions & 2 deletions lib/unikraft/cloud/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,24 @@ def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>"
# metro is known, so `get(name: ...).suspend` is one request.
#
# A sandbox lives in exactly one metro, so `sandboxes` belongs here rather
# than on {Scope}, built in {#initialize} from `session` and `endpoint`.
# than on {Scope}.
class MetroScope < Scope
# @return [Core::Endpoint] the metro these clients are pinned to
attr_reader :endpoint
# @return [API] the raw API surfaces, the platform one pinned to this
# metro
attr_reader :api
# @return [Resources::Sandboxes] virtual machines that run the commands
# they are handed
attr_reader :sandboxes

# @api private
def initialize(session, endpoint)
super(session, [endpoint.metro].freeze, session.transport(endpoint.base_url))
transport = session.transport(endpoint.base_url)
super(session, [endpoint.metro].freeze, transport)
@endpoint = endpoint
@api = session.api(endpoint.base_url)
@sandboxes = Resources::Sandboxes.new(session, @scope, transport)
end
end

Expand Down
Loading
Loading