diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a79f689..624c696 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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-.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 diff --git a/Gemfile.lock b/Gemfile.lock index 1bc4f4c..04f4f60 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -2,6 +2,7 @@ PATH remote: . specs: unikraft-cloud (0.0.0) + unikraft-cloud-plugin-sandbox-api (~> 1.0) GEM remote: https://rubygems.org/ @@ -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 diff --git a/README.md b/README.md index 019d79c..a458f75 100644 --- a/README.md +++ b/README.md @@ -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` @@ -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`: diff --git a/Rakefile b/Rakefile index c5589da..3d56a48 100644 --- a/Rakefile +++ b/Rakefile @@ -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 diff --git a/examples/sandbox.rb b/examples/sandbox.rb new file mode 100644 index 0000000..f48f0fb --- /dev/null +++ b/examples/sandbox.rb @@ -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 diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index ff243f4..3226dad 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -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" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb index 68ede2b..2d6d74f 100644 --- a/lib/unikraft/cloud/client.rb +++ b/lib/unikraft/cloud/client.rb @@ -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 diff --git a/lib/unikraft/cloud/resources/sandboxes/command.rb b/lib/unikraft/cloud/resources/sandboxes/command.rb new file mode 100644 index 0000000..8e4e834 --- /dev/null +++ b/lib/unikraft/cloud/resources/sandboxes/command.rb @@ -0,0 +1,186 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# One command inside a sandbox, addressed by the UUID the plugin assigned it. + +require_relative "../../core/base64" +require_relative "../../core/errors" +require_relative "../../core/response" + +module Unikraft + module Cloud + class Sandbox + # A command's output: both streams decoded as UTF-8, and the total size + # of each, which a {Command#read} range can then address. + Logs = Data.define(:stdout, :stderr, :stdout_available, :stderr_available) + + # A command inside a sandbox, from {Sandbox#spawn}, {Sandbox#command} or + # {Sandbox#commands}. Each method is exactly one request, so a caller + # can see what a wait costs. Standard input reads like an IO opened for + # writing: {#write} and {#close_write}. + # + # @example + # cat = sb.spawn("cat") + # cat.write("first line\n").close_write + # cat.wait(within: 10).logs.stdout # => "first line\n" + # sb.spawn("sleep 30").signal(:TERM) + class Command + # @return [String] the command's UUID, assigned by the plugin + attr_reader :uuid + # @return [Sandbox] the sandbox the command runs in + attr_reader :sandbox + + # @api private + def initialize(sandbox, uuid) + @sandbox = sandbox + @uuid = uuid + end + + # The command line, working directory, environment and `exitcode`, + # which is nil while the command runs. The only operation that + # reports the exit code. + # + # @param call [Hash] `headers:`, `timeout:` + # @return [Plugin::Sandbox::API::Models::GetCommandData] + def info(**call) = unwrap(api.get_command_by_uuid(uuid:, **call)) + + # Block until the command exits, or until `within` seconds pass. A + # wait that runs out is not an error: the command keeps running, and + # {#info} says whether it finished. + # + # @example + # cmd.wait # however long it takes + # cmd.wait(within: 5) # then return regardless + # @param within [Numeric, nil] seconds the plugin waits; decimals are + # accepted. The plugin holds the request open meanwhile, so the + # read timeout is stretched to cover it (or lifted without + # `within`), unless `timeout:` sets it. + # @param call [Hash] `headers:`, `timeout:` (the HTTP timeout) + # @return [self] + def wait(within: nil, **call) + # The plugin holds the request open for the wait. + call = { timeout: within && (within + 10) }.merge(call) + if within.nil? + unwrap(api.wait_for_command(uuid:, **call)) + return self + end + begin + unwrap(api.wait_for_command_with_timeout(uuid:, body: { timeout_s: within }, **call)) + rescue Error => e + # 408 is the plugin saying the timeout elapsed, which is what was + # asked for; every other status is still a failure. + raise unless e.kind == :http && e.status == 408 + end + self + end + + # Both output streams, decoded. + # + # @return [Logs] + def logs(**call) + data = unwrap(api.get_command_logs(uuid:, **call)) + Logs.new(stdout: Core::Base64.decode_text(data&.stdout), + stderr: Core::Base64.decode_text(data&.stderr), + stdout_available: data&.stdout_available, + stderr_available: data&.stderr_available) + end + + # One output stream as bytes, optionally a byte range of it. The + # range goes in a `Range` header: the plugin also models it as a body + # on the JSON log `GET`, which the transport refuses to send. + # + # @example + # cmd.read(:stdout, offset: -4096) # the last 4 KiB + # cmd.read(:stderr, offset: 0, limit: 1024) + # @param stream [Symbol, String] `:stdout` or `:stderr` + # @param offset [Integer, nil] first byte; negative counts back from + # the end, and then cannot be combined with `limit` + # @param limit [Integer, nil] at most this many bytes + # @return [String] binary + # @raise [Unikraft::Cloud::Error] kind `:config` for an unusable range + def read(stream = :stdout, offset: nil, limit: nil, **call) + api.get_raw_command_log(uuid:, stream: stream.to_s, range: range(offset, limit), **call) + end + + # Feed data into the command's standard input. Text and binary + # Strings are both sent as their bytes. + # + # @param data [String] + # @param eof [Boolean] close standard input afterwards + # @return [self] + def write(data, eof: false, **call) + body = { data: Core::Base64.encode(data) } + body[:eof] = true if eof + unwrap(api.write_command_stdin(uuid:, body:, **call)) + self + end + + # Close the command's standard input. + # + # @return [self] + def close_write(**call) = write("", eof: true, **call) + + # Send a signal, by name or number. + # + # @example + # cmd.signal(:TERM) # or "SIGTERM", or 15 + # @param signal [Symbol, String, Integer] + # @return [self] + def signal(signal, **call) + signal = signal.to_s if signal.is_a?(Symbol) + unwrap(api.signal_command(uuid:, body: { signal: }, **call)) + self + end + + # Delete the command record and its logs. A running command cannot be + # deleted (409). + # + # @return [nil] + def delete(**call) + unwrap(api.delete_command_by_uuid(uuid:, **call)) + nil + end + + # Delete the command's logs, keeping its record. + # + # @return [nil] + def delete_logs(**call) + unwrap(api.delete_command_logs_by_uuid(uuid:, **call)) + nil + end + + def inspect = "#<#{self.class.name} #{uuid} sandbox=#{sandbox.uuid}>" + + private + + def api = sandbox.api.commands + + def unwrap(res) = Core::Response.unwrap(res) + + # The `Range` header for a byte range of a log stream. + def range(offset, limit) + return nil if offset.nil? && limit.nil? + + { offset:, limit: }.each do |name, value| + next if value.nil? || value.is_a?(Integer) + + raise Error.new("`#{name}:` must be a whole number of bytes. Received " \ + "#{value.inspect}.", kind: :config) + end + if limit && limit <= 0 + raise Error.new("A `limit:` of #{limit} asks for no bytes at all; omit it to read " \ + "to the end of the stream.", kind: :config) + end + start = offset || 0 + return "bytes=#{start}-#{limit && (start + limit - 1)}" unless start.negative? + return "bytes=#{start}" if limit.nil? + + raise Error.new("A negative `offset:` already names the last bytes of the stream, " \ + "so it cannot be combined with `limit:`.", kind: :config) + end + end + end + end +end diff --git a/lib/unikraft/cloud/resources/sandboxes/files.rb b/lib/unikraft/cloud/resources/sandboxes/files.rb new file mode 100644 index 0000000..dda1ba1 --- /dev/null +++ b/lib/unikraft/cloud/resources/sandboxes/files.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# The filesystem inside a sandbox, in the shape of Ruby's own File. + +require_relative "../../core/base64" +require_relative "../../core/response" + +module Unikraft + module Cloud + class Sandbox + # The sandbox's filesystem, as `sb.files`. Paths are absolute paths + # inside the sandbox. Data is a String, or anything that responds to + # `read`, such as an open File: a binary String (`Encoding::BINARY`) + # travels as bytes, any other String as UTF-8 text. + # + # @example + # sb.files.mkdir("/work/input") + # sb.files.write("/work/input/a.txt", "hello\n") + # sb.files.write("/work/input/a.txt", "more\n", append: true) + # sb.files.upload("/work/input", "data.bin", File.binread("data.bin")) + # sb.files.read("/work/input/a.txt") # => "hello\nmore\n" (binary) + class Files + # @api private + def initialize(sandbox) + @sandbox = sandbox + end + + # Read a file. + # + # @param path [String] + # @param call [Hash] `headers:`, `timeout:` + # @return [String] the contents, binary + def read(path, **call) + # The raw read, not the base64 one, which costs a third more bytes. + api.read_raw_file(body: { path: }, **call) + end + + # Write a file, creating it if it is missing. + # + # @param path [String] + # @param data [String, #read] + # @param append [Boolean] append rather than truncate + # @return [nil] + def write(path, data, append: false, **call) + Core::Response.unwrap(api.write_file(body: { path:, append:, **encode(data) }, **call)) + nil + end + + # Create a directory, and its missing parents unless `parents: false`. + # + # @param path [String] + # @param parents [Boolean] + # @return [nil] + def mkdir(path, parents: true, **call) + Core::Response.unwrap(api.create_directory(body: { path:, parents: }, **call)) + nil + end + + # Upload a file: into the directory `path` under `filename`, or to + # `path` itself when that is not a directory. + # + # @param path [String] + # @param filename [String] + # @param data [String, #read] + # @param parents [Boolean] create missing parent directories + # @return [nil] + def upload(path, filename, data, parents: true, **call) + body = { path:, filename:, parents:, **encode(data) } + Core::Response.unwrap(api.upload_file(body:, **call)) + nil + end + + def inspect = "#<#{self.class.name} sandbox=#{@sandbox.uuid}>" + + private + + def api = @sandbox.api.fs + + # The encoding and payload the filesystem API wants for some data. + def encode(data) + data = data.read if data.respond_to?(:read) + data = data.to_s + if data.encoding == Encoding::BINARY || !data.valid_encoding? + { encoding: "base64", data: Core::Base64.encode(data) } + else + { encoding: "utf-8", data: data.encode(Encoding::UTF_8) } + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/resources/sandboxes/sandbox.rb b/lib/unikraft/cloud/resources/sandboxes/sandbox.rb new file mode 100644 index 0000000..062eb76 --- /dev/null +++ b/lib/unikraft/cloud/resources/sandboxes/sandbox.rb @@ -0,0 +1,366 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# A sandbox spans two APIs. The platform creates the virtual machine and +# attaches the plugin; the plugin's own API runs commands inside it. The +# plugin is addressed under the name it was attached with, not the +# specification's `servers` block, and a sandbox borrows the client's session +# rather than resolving credentials of its own. + +require "unikraft/cloud/plugin/sandbox/api" + +require_relative "../../core/errors" +require_relative "../../core/metro" +require_relative "../../core/ready" +require_relative "../../core/ref" +require_relative "../../core/response" +require_relative "../../core/url" +require_relative "../instances" +require_relative "command" +require_relative "files" + +module Unikraft + module Cloud + # One virtual machine with the sandbox plugin attached: it runs whatever + # command it is handed. Commands and files go to the plugin's endpoint, + # a route under that machine; {#instance} is the machine itself. + # + # There are two ways in. {Sandbox.create} builds a client from its + # options; `ukc.metro(:fra).sandboxes.create` borrows one you hold. With + # a block, either deletes the sandbox when the block returns, however it + # returns. + # + # @example + # Unikraft::Cloud::Sandbox.create do |sb| + # sb.run("echo hello").stdout # => "hello\n" + # sb.files.write("/tmp/a.txt", "hello") + # sb.instance.update(memory_mb: 4096) # it is a real instance + # end + class Sandbox + # The plugin name, and so the URL segment, used when the caller names + # none. + DEFAULT_PLUGIN_NAME = Plugin::Sandbox::API::PLUGIN_NAME + + # The prebuilt sandbox plugin ROM used when the caller names none. + DEFAULT_PLUGIN_ROM = "plugins/sandbox:latest" + + # The image a sandbox boots when the caller names none, unless + # `UKC_SANDBOX_IMAGE` names another. A replacement must carry a shell + # and a main process that stays alive. + DEFAULT_IMAGE = "debian-slim:latest" + + # Memory, in megabytes: sized for a compiler or a test suite rather + # than for one small service. + DEFAULT_MEMORY_MB = 2048 + + # How long a stopped sandbox is kept before the platform deletes it, in + # milliseconds. It counts stopped time only, so a running sandbox is + # untouched. + DEFAULT_AUTOKILL_MS = 300_000 + + # How long `create` waits for the machine to reach `running`, in + # seconds. + DEFAULT_BOOT_WITHIN = 30 + + # What a finished command produced. `exitcode` is nil when the + # `within:` of {Sandbox#run} ran out; the command then keeps running, + # and its record is kept, so `uuid` stays addressable through + # {Sandbox#command}. + Result = Data.define(:uuid, :stdout, :stderr, :exitcode) do + # @return [Boolean] whether the command exited with status 0 + def success? = exitcode.is_a?(Integer) && exitcode.zero? + end + + # `stop_reason` bits only a running instance can set: [A]pp (bit 1) + # for an application that exited, [K]ernel (bit 0) for a kernel that did. + STOP_REASON_RAN = 0b00011 + private_constant :STOP_REASON_RAN + + # @return [String] the instance's UUID + attr_reader :uuid + # @return [String] the metro the sandbox lives in + attr_reader :metro + # @return [String] the name the plugin is attached under, also its URL + # segment + attr_reader :plugin_name + # @return [Core::Session] the credentials and metro knowledge it runs on, + # shared with the client it came from + attr_reader :session + # @return [String] the plugin's endpoint + attr_reader :base_url + # @return [Plugin::Sandbox::API::Client] the raw ("plumbing") plugin API, + # pinned to this sandbox: `api.commands` and `api.fs`, returning the + # envelopes untouched + attr_reader :api + # @return [Files] the filesystem inside the sandbox + attr_reader :files + + class << self + # Create a sandbox through a client built from the options, the way + # `Unikraft::Cloud.new` takes them (`token:` or `UKC_TOKEN`, `metro:` + # or `UKC_METRO`, ...), or through a borrowed `client:`. The rest is + # {Resources::Sandboxes#create}'s. With a block, the sandbox is + # deleted, and a client built here closed, when the block returns. + # + # @example + # Unikraft::Cloud::Sandbox.create(image: "my-org/base:latest", metro: :fra) do |sb| + # puts sb.run("uname -a").stdout + # end + # @param spec [Hash, nil] see {Resources::Sandboxes#create} + # @param client [Client, nil] borrow this client + # @yieldparam sandbox [Sandbox] + # @return [Sandbox, Object] the sandbox, or the block's value + def create(spec = nil, client: nil, **kwargs, &) + ukc, rest, scope = door(client, kwargs, "`Sandbox.create(spec, client:)`") + endpoint = ukc.session.resolve_one(scope, "Creating a sandbox") + ukc.metro(endpoint.metro).sandboxes.create(spec, **rest, &) + ensure + ukc&.close if block_given? && client.nil? + end + + # Attach to a sandbox that already exists. An instance UUID is + # metro-scoped, so a ref without `metro:` is searched for across the + # scope; name the metro to skip the search. + # + # @example + # sb = Unikraft::Cloud::Sandbox.connect(uuid: uuid, metro: :fra) + # @param ref [Hash, nil] or pass `uuid:`/`name:`/`metro:` + # @param client [Client, nil] borrow this client + # @return [Sandbox] + def connect(ref = nil, client: nil, **kwargs) + ref_kw = kwargs.slice(*Core::Ref.members) + ukc, rest, scope = door(client, kwargs.except(*Core::Ref.members), + "`Sandbox.connect(ref, client:)`") + Resources::Sandboxes.new(ukc.session, scope, ukc.session.transport) + .get(ref, **ref_kw, **rest) + end + + private + + # The client a static door runs through, the options left for the + # call, and the metro scope. Credentials are only ever resolved by + # building a client. + def door(client, kwargs, name) + picked = kwargs[:metros] || kwargs[:metro] + if client + Resources::Sandboxes.refuse_client_config!(kwargs.except(:metro, :metros), name, + borrowed: true) + scope = picked ? Core::Metro.scope(picked) : client.scope + return [client, kwargs.except(:metro, :metros), scope] + end + + config = kwargs.slice(*Resources::Sandboxes::CLIENT_CONFIG) + token = config[:token] || ENV.fetch("UKC_TOKEN", nil) + if token.to_s.empty? + raise Error.new("UKC_TOKEN is missing or empty; set it, or pass a token: " \ + "`Sandbox.create(token: ...)`, or use a client: " \ + "`Unikraft::Cloud.new(token: ...).metro(:fra).sandboxes.create`.", + kind: :config) + end + ukc = Client.new(**config) + [ukc, kwargs.except(*Resources::Sandboxes::CLIENT_CONFIG), ukc.scope] + end + end + + # @api private + # @param endpoint [Core::Endpoint] the endpoint the instance was reached + # through, which a pinned or discovered metro makes unguessable from + # its code + def initialize(session:, endpoint:, uuid:, plugin_name:) + @session = session + @endpoint = endpoint + @uuid = uuid + @metro = endpoint.metro + @plugin_name = plugin_name + # Built here rather than read from the specification, whose server URL + # omits `/v1` and hardcodes `sandbox` as the plugin's name. + @base_url = "#{Core::URL.strip_trailing_slashes(endpoint.base_url)}/v1/instances/" \ + "#{uuid}/plugins/#{plugin_name}" + # The SDK's own transport, so a plugin failure is a Unikraft::Cloud::Error. + @api = Plugin::Sandbox::API.new(session.transport(@base_url)) + @instances = Resources::Instances.new(session, [@metro], + session.transport(endpoint.base_url)) + @files = Files.new(self) + end + + # The instance underneath, as a lazy handle (see {Core::Handle}). Each + # call returns a fresh handle, so keep it to read it twice. + # + # @example + # sb.instance.state + # sb.instance.update(memory_mb: 4096) + # @return [Resources::InstanceHandle] + def instance + ref = Core::Ref.new(uuid:, metro:) + location = Core::Location.new(ref:, metro:, base_url: @endpoint.base_url) + Resources::InstanceHandle.new(@instances, ref, {}, + located: Core::Located.new(location:, value: nil)) + end + + # Wait until the plugin answers. `create` does this for you; call it + # after `create(ready: false)`, or after a start or a resume from + # standby, where the plugin reloads. When the wait runs out, the error + # names the likely cause, read from the instance. + # + # @example + # sb.ready(within: 10) + # @param within [Numeric] seconds to keep probing; each probe's HTTP + # timeout is the time left + # @param headers [Hash, nil] sent with each probe + # @param policy [Hash] `initial_delay:`, `max_delay:` in seconds (see + # {Core::Ready.wait_until_ready}) + # @return [self] + # @raise [Unikraft::Cloud::Error] kind `:timeout` + def ready(within: Core::Ready::DEFAULTS[:timeout], headers: nil, **policy) + # ListCommands is the probe the specification nominates + # (`x-unikraft-plugin-readiness`); a booting instance answers it with + # 404 or 502, which the loop retries. + Core::Ready.wait_until_ready(**policy, timeout: within, what: "sandbox #{uuid}", + diagnose: ->(_) { diagnose }) do |left| + api.commands.list_commands(headers:, timeout: left) + end + self + end + + # Run a command, wait for it to exit, and return its output: one + # String is a shell command line, several are an argument vector run + # directly, as with `Kernel#system`. A failing command is not an + # error; check {Result#success?}. + # + # A `within:` that runs out is not an error either: the result has + # the output so far and a nil `exitcode`, and the command keeps + # running. Otherwise the command's record is deleted, unless `keep:`. + # + # @example + # sb.run("echo hello").stdout # => "hello\n" + # sb.run("ls", "-la", cwd: "/tmp").success? + # sb.run("make", within: 600) + # @param cmd [Array] + # @param cwd [String, nil] + # @param env [Hash{String => String}, nil] + # @param keep [Boolean] keep the record, to read its logs again later + # @param within [Numeric, nil] seconds to wait before giving up (see + # {Command#wait}) + # @param call [Hash] `headers:`, `timeout:` (the HTTP timeout of each + # request) + # @return [Result] + def run(*cmd, cwd: nil, env: nil, keep: false, within: nil, **call) + command = spawn(*cmd, cwd:, env:, **call) + command.wait(within:, **call) + exitcode = command.info(**call)&.exitcode + logs = command.logs(**call) + command.delete(**call) unless keep || exitcode.nil? + Result.new(uuid: command.uuid, stdout: logs.stdout, stderr: logs.stderr, exitcode:) + end + + # Start a command and return at once, without waiting for it. + # + # @example + # server = sb.spawn("python3 -m http.server", cwd: "/srv") + # server.signal(:TERM) + # @param (see #run) + # @param call [Hash] `headers:`, `timeout:` + # @return [Command] + def spawn(*cmd, cwd: nil, env: nil, **call) + raise ArgumentError, "no command given" if cmd.empty? + + cmd = cmd.first if cmd.size == 1 + res = api.commands.run_command(body: { cmd:, cwd:, env: }.compact, **call) + uuid = Core::Response.unwrap(res)&.uuid + return Command.new(self, uuid) if uuid + + raise Error.new("The sandbox started a command but reported no UUID for it.", + kind: :http, body: res) + end + + # Every command the sandbox knows about, in the order they started. + # + # @return [Array] + def commands(**call) + Core::Response.list(api.commands.list_commands(**call), :commands) + .map { |uuid| Command.new(self, uuid) } + end + + # A command by UUID, without a request: one kept by `run(keep: true)`, + # or started by another process. + # + # @return [Command] + def command(uuid) = Command.new(self, uuid.to_s) + + # Delete the sandbox, which deletes the instance underneath it. + # + # @param call [Hash] `headers:`, `timeout:` + # @return [Resources::InstanceHandle] carrying what the platform reported + def delete(**call) = instance.delete(**call) + + def inspect + "#<#{self.class.name} #{uuid} metro=#{metro.inspect} plugin=#{plugin_name.inspect}>" + end + + private + + # Name the cause once a readiness wait ran out of time. The silent + # plugin is the symptom; the instance's own state usually says why. + def diagnose + inst = instance.model + plugins = inst.plugins + plugin = plugins&.find { |p| p[:name] == plugin_name } + case inst.state + when "running" then diagnose_running(plugins, plugin) + when "standby" + 'the instance is in "standby", asleep. A plugin request wakes it, so this is a ' \ + "slow wake rather than a refusal: raise `ready: { within: }`. If you suspended " \ + "it yourself, start it (`sb.instance.start.wait(state: :running)`) and call " \ + "`sb.ready` again" + when "starting" + 'the instance is still "starting", so it only needs longer. Raise ' \ + "`ready: { within: }`, or `boot_within:` on `create`" + else diagnose_down(inst, plugin) + end + end + + def diagnose_running(plugins, plugin) + if plugins && plugin.nil? + if plugins.empty? + return "the instance is running but carries no plugin at all, so nothing answers " \ + "at `#{plugin_name}`" + end + + return "the instance is running but carries no plugin named `#{plugin_name}`, " \ + "only #{plugins.map { |p| "`#{p[:name]}`" }.join(", ")}. Pass the name it " \ + "does carry as `plugin_name:`" + end + rom = plugin ? " and that its ROM (`#{plugin[:rom]}`) is a sandbox plugin image" : "" + "the instance is running, so it is the sandbox plugin that did not answer. Read the " \ + "instance's console log (`sb.instance.logs`), which carries the plugin's own " \ + "output#{rom}" + end + + def diagnose_down(inst, plugin) + state = inst.state ? %(the instance is "#{inst.state}") : "the instance reported no state" + unless started?(inst) + # An image or ROM that could not be pulled: the console log is empty. + roms = ["`#{inst.image}`", plugin && "`#{plugin[:rom]}`"].compact + return "#{state} and never started, so nothing inside it has run yet. The usual " \ + "cause is an image the platform could not fetch or boot: check that " \ + "#{roms.join(" or ")} #{roms.size > 1 ? "both exist" : "exists"}, and that " \ + "this account can read #{roms.size > 1 ? "them" : "it"}" + end + exit = inst.exit_code.nil? ? "" : ", having exited with code #{inst.exit_code}" + "#{state}#{exit}, and the sandbox plugin runs inside the instance, so nothing " \ + "answers while it is down. Start it again (`sb.instance.start`) and read the " \ + "console log (`sb.instance.logs`); a base image whose main process exits at once " \ + "stops the instance with it" + end + + # Whether anything ever ran inside an instance: three witnesses, each + # optional on the wire. + def started?(inst) + inst.start_count.to_i.positive? || !inst.started_at.nil? || + inst.stop_reason.to_i.anybits?(STOP_REASON_RAN) + end + end + end +end diff --git a/lib/unikraft/cloud/resources/sandboxes/sandboxes.rb b/lib/unikraft/cloud/resources/sandboxes/sandboxes.rb new file mode 100644 index 0000000..36e3503 --- /dev/null +++ b/lib/unikraft/cloud/resources/sandboxes/sandboxes.rb @@ -0,0 +1,336 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../../core/errors" +require_relative "../../core/metro" +require_relative "../../core/response" +require_relative "../instances" +require_relative "sandbox" + +module Unikraft + module Cloud + module Resources + # The sandboxes of one metro, as `ukc.metro(:fra).sandboxes`. A sandbox + # lives in exactly one metro, so this hangs off a metro scope rather + # than the account-wide client, where `create` could only quietly mean + # the default metro. Enumerable over the sandboxes in the metro. + # + # @example + # fra = ukc.metro(:fra) + # fra.sandboxes.create(memory_mb: 512) do |sb| + # sb.run("make", "test", cwd: "/src") + # end + # fra.sandboxes.each { |sb| puts sb.uuid } + class Sandboxes + include Enumerable + + # The keywords that configure a client: a door that runs through an + # existing one refuses them rather than ignoring them. `headers:` + # and `timeout:` are not among them, being per-call options too. A + # test keeps this in step with {Client#initialize}. + CLIENT_CONFIG = %i[token metro metros base_url control_plane_url proxy_from_env + user_agent transport].freeze + + # The create fields a sandbox sets itself, or cannot honour. + MANAGED = %i[autostart timeout_s wait_timeout_ms].freeze + + # What creates from a snapshot, which carries the image, the memory + # and the plugins of its source. + SNAPSHOT = %i[template branch_from checkpoint].freeze + + # @return [Core::Session] + attr_reader :session + # @return [:all, Array] the metros these operations cover + attr_reader :scope + + # Refuse options that would be silently ignored, the client they + # configure already existing. + # + # @api private + def self.refuse_client_config!(opts, door, borrowed: false) + named = opts.keys & (CLIENT_CONFIG + [:client]) + return if named.empty? + + remedies = [] + if named.include?(:client) + remedies << "run the call through that client's own `sandboxes`" + end + config = named - %i[client metro metros] + unless config.empty? + remedies << "set #{config.size == 1 ? "it" : "them"} when the client is built " \ + "(`Unikraft::Cloud.new(#{config.map { |k| "#{k}: ..." }.join(", ")})`)" + end + if named.intersect?(%i[metro metros]) + remedies << "pick the metro one step earlier (`ukc.metro(:fra).sandboxes`)" + end + remedies << if borrowed + "drop `client:`, so that these options build the client instead" + else + "use `Unikraft::Cloud::Sandbox.create`, which builds a client from them" + end + keys = named.map { |k| "`#{k}:`" }.join(", ") + raise Error.new("#{door} runs through a client that already exists, so #{keys} " \ + "would be ignored. To fix it, #{remedies.join(", or ")}.", + kind: :config) + end + + # @api private + def initialize(session, scope, transport) + @session = session + @scope = scope + @instances = Instances.new(session, scope, transport) + end + + # Create a sandbox: create the instance with the plugin attached, then + # wait for the plugin to answer. A failed wait deletes the instance + # it made, so a broken sandbox does not linger; pass `ready: false` + # to keep it for inspection. + # + # The spec is every field `instances.create` takes, minus the ones a + # sandbox manages (`autostart`, `timeout_s`, `wait_timeout_ms`, + # `replicas`), plus `rom:` (shorthand for the plugin's entry in + # `plugins`) and `plugin_name:`. `image` defaults to + # `UKC_SANDBOX_IMAGE` or {Sandbox::DEFAULT_IMAGE}, `memory_mb` to + # {Sandbox::DEFAULT_MEMORY_MB}, `autokill` to + # {Sandbox::DEFAULT_AUTOKILL_MS}. A `template:`, `branch_from:` or + # `checkpoint:` carries its image, memory and plugins, so those + # defaults are left out. + # + # With a block, the sandbox is yielded and deleted when the block + # returns, however it returns. + # + # @example + # sb = fra.sandboxes.create(image: "my-org/base:latest", env: { "A" => "1" }) + # fra.sandboxes.create(template: { name: "warm" }) { |sb| sb.run("true") } + # @param spec [Hash, nil] the spec, or pass it as keywords + # @param boot_within [Integer, nil] seconds the platform waits for + # `running`; {Sandbox::DEFAULT_BOOT_WITHIN}, or 0 with `ready: false`. + # The create request is held open meanwhile, so a given value + # stretches its read timeout to cover it, unless `timeout:` sets it + # @param ready [Hash, false] the {Sandbox#ready} policy (`within:`, + # ...), or false to return as soon as the instance exists + # @param headers [Hash, nil] + # @param timeout [Numeric, nil] the HTTP timeout of each request + # @yieldparam sandbox [Sandbox] + # @return [Sandbox, Object] the sandbox, or the block's value + # @raise [Unikraft::Cloud::Error] kind `:config` for a field a sandbox + # manages or a client option + def create(spec = nil, boot_within: nil, ready: {}, headers: nil, timeout: nil, **kwargs) + spec = (spec || {}).transform_keys(&:to_sym).merge(kwargs) + self.class.refuse_client_config!(spec, "`sandboxes.create`") + check_spec!(spec) + call = { headers:, timeout: }.compact + plugin_name = (spec.delete(:plugin_name) || Sandbox::DEFAULT_PLUGIN_NAME).to_s + body = instance_body(spec, plugin_name, spec.delete(:rom)) + body[:timeout_s] = boot_within || (ready == false ? 0 : Sandbox::DEFAULT_BOOT_WITHIN) + booting = boot_within&.positive? ? { timeout: boot_within + 10 }.merge(call) : call + sandbox = attach(create_instance(body, booting), plugin_name) + ready_or_delete(sandbox, ready, headers) unless ready == false + return sandbox unless block_given? + + begin + yield sandbox + ensure + # A block that deleted the sandbox itself still ends here. + Core::Response.absent { sandbox.delete(**call) } + end + end + + # Attach to a sandbox that already exists. Nothing waits for the + # plugin unless `ready:` is given, and nothing is ever deleted. + # + # @example + # fra.sandboxes.get(uuid: uuid) + # fra.sandboxes.get(name: "ci", ready: { within: 10 }) + # @param ref [Hash, nil] or pass `uuid:`/`name:`/`metro:` + # @param plugin_name [String, nil] the plugin to address; defaults to + # the one named {Sandbox::DEFAULT_PLUGIN_NAME}, or the only one + # @param ready [Hash, nil] probe the plugin with this policy + # @return [Sandbox] + def get(ref = nil, plugin_name: nil, ready: nil, **kwargs) + self.class.refuse_client_config!(kwargs.except(:metro), "`sandboxes.get`") + call = kwargs.slice(:headers, :timeout) + handle = @instances.get(ref, **kwargs) + sandbox = attach(handle, plugin_name_on(handle.model, plugin_name)) + sandbox.ready(**ready, headers: call[:headers]) if ready + sandbox + end + + # Every instance in scope carrying the sandbox plugin, as sandboxes. + # A sandbox is an instance, so this is the instance list, filtered. + # + # @param plugin_name [String, nil] the plugin to look for + # @param opts [Hash] `tags:`, `page_size:`, `metros:`, `base_url:`, + # `headers:`, `timeout:`, as `instances.list` takes them + # @return [Enumerator] without a block + def list(plugin_name: nil, **opts, &block) + wanted = (plugin_name || Sandbox::DEFAULT_PLUGIN_NAME).to_s + enum = Enumerator.new do |out| + @instances.list(**opts, details: true).each do |inst| + next unless inst.plugins&.any? { |p| p[:name] == wanted } + + out << Sandbox.new(session:, endpoint: endpoint_of(inst, opts[:base_url]), + uuid: inst.uuid, plugin_name: wanted) + end + end + block ? enum.each(&block) : enum + end + + # @yieldparam sandbox [Sandbox] + def each(&) + return enum_for(:each) unless block_given? + + list(&) + self + end + + def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" + + private + + def check_spec!(spec) + if spec.key?(:replicas) + raise Error.new("A sandbox addresses exactly one instance, so `replicas` would " \ + "create instances no sandbox wraps. Create one sandbox per call, " \ + "or replicated instances through `instances.create`.", kind: :config) + end + managed = MANAGED & spec.keys + return if managed.empty? + + raise Error.new("`sandboxes.create` sets #{managed.map { |k| "`#{k}`" }.join(", ")} " \ + "itself, because a plugin cannot answer in a stopped instance. " \ + "Control the boot wait with `boot_within:` instead.", kind: :config) + end + + # The instance create body: the spec, with the defaults it leaves out. + def instance_body(spec, plugin_name, rom) + snapshot = SNAPSHOT.any? { |key| spec.key?(key) } + image = spec.delete(:image) + # An empty image is as unusable as an absent one. + image = nil if image.to_s.empty? + unless snapshot + image ||= ENV.fetch("UKC_SANDBOX_IMAGE", "") + image = Sandbox::DEFAULT_IMAGE if image.empty? + spec[:memory_mb] ||= Sandbox::DEFAULT_MEMORY_MB + end + plugins = if snapshot + from_snapshot(spec[:plugins], plugin_name, rom) + else + with_plugin(spec[:plugins], plugin_name, rom) + end + autokill = spec[:autokill] || { time_ms: Sandbox::DEFAULT_AUTOKILL_MS } + { **spec, image:, plugins:, autokill:, autostart: true }.compact + end + + # The caller's plugins plus the sandbox plugin. An entry already named + # `plugin_name` is the sandbox plugin, and keeps its `config`. + def with_plugin(plugins, plugin_name, rom) + plugins = Array(plugins) + unless named?(plugins, plugin_name) + return [{ name: plugin_name, rom: rom || Sandbox::DEFAULT_PLUGIN_ROM }, *plugins] + end + return plugins if rom.nil? + + raise Error.new("The spec attaches a plugin named \"#{plugin_name}\" in `plugins` and " \ + "also passes `rom:`, so there are two ROMs for one plugin. Keep the " \ + "`plugins` entry, which can also carry `config`, and drop `rom:`.", + kind: :config) + end + + # A snapshot already carries the sandbox plugin: attaching it again + # is refused by the platform, so it is refused here first. + def from_snapshot(plugins, plugin_name, rom) + return plugins if rom.nil? && !named?(Array(plugins), plugin_name) + + raise Error.new("The spec creates the sandbox from a template, a branch source, or " \ + "a checkpoint, which already carries the sandbox plugin, so `rom:` " \ + "or a `plugins` entry named \"#{plugin_name}\" would attach it twice. " \ + "Drop it. If the source attached the plugin under another name, pass " \ + "that name as `plugin_name:`.", kind: :config) + end + + def named?(plugins, name) = plugins.any? { |p| (p[:name] || p["name"]).to_s == name } + + def create_instance(body, call) + @instances.create(body, **call) + rescue Error => e + raise unless e.kind == :network + + # The reply carries the UUID, so a request that failed on the way + # back leaves nothing to address, and autokill counts stopped time. + raise Error.new("#{e.message} The platform may have created the instance before this " \ + "failed. If it did, it is running, and neither this call nor " \ + "`autokill` removes it: find it with `sandboxes.list` and delete it.", + kind: e.kind, status: e.status, errors: e.errors, body: e.body, + cause: e.cause) + end + + # Wait for the plugin, and delete the instance this call made when + # the wait fails: a running instance with a silent plugin never stops + # on its own, so autokill would never reach it. + def ready_or_delete(sandbox, policy, headers) + sandbox.ready(**policy, headers:) + rescue Exception => e # rubocop:disable Lint/RescueException -- an interrupt leaks it too + deleted = begin + sandbox.delete(**{ headers: }.compact) + true + rescue StandardError + false + end + raise unless deleted && e.is_a?(Error) + + raise Error.new("#{e.message} The sandbox was deleted. To inspect a sandbox that " \ + "fails like this, create it with `ready: false`, which skips this " \ + "wait and keeps it for you to probe and delete.", + kind: e.kind, status: e.status, errors: e.errors, body: e.body, + cause: e.cause) + end + + # A sandbox on an instance handle, at the endpoint it was found at. + def attach(handle, plugin_name) + loc = handle.location + Sandbox.new(session:, uuid: handle.uuid, plugin_name:, + endpoint: Core::Endpoint.new(metro: loc.metro, base_url: loc.base_url)) + end + + # A listed instance's endpoint: a per-call `base_url:` wins over the + # metro, so the plugin is reached on the cluster the list came from. + def endpoint_of(inst, base_url) + return @session.endpoint_for(inst.metro) unless base_url + + url = Core::Metro.base_url(base_url) + Core::Endpoint.new(metro: url, base_url: url) + end + + # Which plugin on an instance is the sandbox: the one asked for, the + # conventional one, or the only one there is. + def plugin_name_on(inst, requested) + plugins = inst.plugins + names = Array(plugins).map { |p| p[:name] } + if requested + # No plugins listed is not evidence of absence; only a list can + # contradict the caller. + return requested.to_s if plugins.nil? || names.include?(requested.to_s) + + has = names.empty? ? "it has no plugins" : "it has: #{names.join(", ")}" + raise Error.new("Instance #{inst.uuid} carries no plugin named \"#{requested}\" " \ + "(#{has}).", kind: :http, status: 404, body: inst) + end + return Sandbox::DEFAULT_PLUGIN_NAME if names.include?(Sandbox::DEFAULT_PLUGIN_NAME) + return names.first if names.size == 1 + if names.empty? + raise Error.new("Instance #{inst.uuid} has no plugins attached, so it is not a " \ + "sandbox.", kind: :http, status: 404, body: inst) + end + + raise Error.new("Instance #{inst.uuid} carries #{names.size} plugins " \ + "(#{names.join(", ")}) and none is named " \ + "\"#{Sandbox::DEFAULT_PLUGIN_NAME}\". Say which one with " \ + "`plugin_name:`.", kind: :config, body: inst) + end + end + end + end +end diff --git a/test/e2e/sandbox_test.rb b/test/e2e/sandbox_test.rb new file mode 100644 index 0000000..8230d82 --- /dev/null +++ b/test/e2e/sandbox_test.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +# Sandboxes against a live account: real virtual machines. Run with +# `bundle exec rake test:e2e`; it needs UKC_TOKEN. UKC_METRO picks the +# deployment, UKC_SANDBOX_IMAGE the image and UKC_E2E_SANDBOX_ROM the plugin. + +require_relative "../test_helper" +require "securerandom" + +class SandboxLiveTest < Minitest::Test + Sandbox = Unikraft::Cloud::Sandbox + # The deployment live_test.rb uses by default. + METRO = "http://api.ukp-staging.apw.unikraft.internal" + + def env(name) + value = ENV.fetch(name, nil) + value unless value.nil? || value.empty? + end + + def setup + skip "UKC_TOKEN is missing or empty" unless env("UKC_TOKEN") + @ukc = Unikraft::Cloud.new(metro: env("UKC_METRO") || METRO) + @spec = { rom: env("UKC_E2E_SANDBOX_ROM") }.compact + end + + def teardown + @ukc&.close + end + + def sandboxes = @ukc.metro(@ukc.scope.first).sandboxes + + # One machine for the commands and files, since a boot is expensive and + # these cannot disturb one another. + def test_a_live_sandbox + sandboxes.create(**@spec) do |sb| + res = sb.run("echo hello") + + assert_equal ["hello\n", "", 0], [res.stdout, res.stderr, res.exitcode] + # The plugin answers 200 for a command that ran and failed. + assert_equal 3, sb.run("sh", "-c", "exit 3").exitcode + + path = "/tmp/round-trip-#{SecureRandom.hex(4)}" + sb.files.write(path, "hello\n") + + assert_equal "hello\n".b, sb.files.read(path) + # Bytes go up base64 and come back raw: no UTF-8 decoder round-trips these. + sb.files.write(path, "\x00\x01\xFE\xFF".b) + + assert_equal "\x00\x01\xFE\xFF".b, sb.files.read(path) + assert_includes sandboxes.map(&:uuid), sb.uuid + end + end + + def test_the_create_block_deletes_the_sandbox + uuid = sandboxes.create(**@spec) do |sb| + assert_equal "running", sb.instance.state + sb.uuid + end + # The platform answers HTTP 200 with an error envelope; the SDK reads + # the entry's code as the 404. + err = assert_raises(Unikraft::Cloud::Error) { Sandbox.connect(uuid:, client: @ukc) } + + assert_equal 404, err.status + end +end diff --git a/test/support/fake_cloud.rb b/test/support/fake_cloud.rb index a55f59c..7a33379 100644 --- a/test/support/fake_cloud.rb +++ b/test/support/fake_cloud.rb @@ -34,9 +34,15 @@ def request(method:, path:, query: nil, body: nil, headers: nil, **options) base_url: options[:base_url] || @base_url, params: FakeCloud.params(query), body: body.nil? ? nil : JSON.parse(JSON.generate(body)), - options: options.merge(headers:).compact)) + options: headers ? options.merge(headers:) : options)) end + # Raw bodies: the route answers a String, returned as binary. + def bytes(**) = request(**) + + # No fake streams yet; present so the plugin gems accept the transport. + def stream(**) = raise(NotImplementedError, "FakeCloud does not stream") + def close = @cloud.closed << @base_url end @@ -75,6 +81,8 @@ def dispatch(call) @mutex.synchronize { @calls << call } answer = @route.call(call) status, body = answer.is_a?(Array) ? answer : [200, answer] + return body.b if body.is_a?(String) && status < 300 + json = JSON.parse(JSON.generate(body), symbolize_names: true) return json if status < 300 diff --git a/test/unit/plugin_transport_test.rb b/test/unit/plugin_transport_test.rb new file mode 100644 index 0000000..223d79d --- /dev/null +++ b/test/unit/plugin_transport_test.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_server" +require "unikraft/cloud/plugin/sandbox/api" + +# The plugin gems take any transport with the methods their `Transport` +# module lists, called with its keywords. Ruby checks neither ahead of time, +# so this is where a drift between the gem and ApiClient shows up. +class PluginTransportTest < Minitest::Test + ApiClient = Unikraft::Cloud::Core::ApiClient + Plugin = Unikraft::Cloud::Plugin::Sandbox::API + + def setup + @server = FakeServer.new + @client = ApiClient.new(base_url: "#{@server.url}/v1/instances/u1/plugins/sandbox", + token: "tok", proxy_from_env: false) + end + + def teardown + @server.close + end + + def test_api_client_takes_every_transport_method_as_declared + Plugin::Transport::METHODS.each do |name| + declared = Plugin::Transport.instance_method(name).parameters + # `stream` also names its block, which the contract leaves implicit. + given = ApiClient.instance_method(name).parameters.reject { |param| param.first == :block } + + assert_equal declared, given, "ApiClient##{name} drifted from the plugin transport" + end + end + + def test_the_plugin_client_accepts_an_api_client + api = Plugin.new(@client) + + assert_same @client, api.transport + assert_raises(TypeError) { Plugin.new(Object.new) } + end + + def test_a_request_reaches_the_plugin_route + @server.respond(body: '{"status":"success","data":{"uuid":"c1"}}') + res = Plugin.new(@client).commands.run_command(body: { cmd: %w[ls -la] }, + headers: { "X-Trace" => "t" }, timeout: 5) + + assert_equal "c1", res.data.uuid + req = @server.last_request + + assert_equal "/v1/instances/u1/plugins/sandbox/commands", req.path + assert_equal '{"cmd":["ls","-la"]}', req.body + assert_equal "t", req.headers["x-trace"] + end + + def test_raw_bytes_carry_the_range_header + @server.respond(body: "\x00\xFF".b) + bytes = Plugin.new(@client).commands.get_raw_command_log(uuid: "c1", stream: "stdout", + range: "bytes=-2") + + assert_equal "\x00\xFF".b, bytes + assert_equal Encoding::BINARY, bytes.encoding + assert_equal "bytes=-2", @server.last_request.headers["range"] + end +end diff --git a/test/unit/sandboxes_test.rb b/test/unit/sandboxes_test.rb new file mode 100644 index 0000000..c7b6bc3 --- /dev/null +++ b/test/unit/sandboxes_test.rb @@ -0,0 +1,470 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" +require "stringio" + +# The sandboxes porcelain over a FakeCloud whose plugin routes answer like +# the sandbox plugin. A port of the JS SDK's test/sandbox.test.ts, plus the +# Ruby surface. +class SandboxesTest < Minitest::Test + include FakeCloud::Helpers + + Sandbox = Unikraft::Cloud::Sandbox + Error = Unikraft::Cloud::Error + PLUGIN = "https://api.fra.unikraft.cloud/v1/instances/u1/plugins/sandbox" + FAST = { within: 0.05, initial_delay: 0.001 }.freeze + + def setup + super + @saved_image = ENV.delete("UKC_SANDBOX_IMAGE") + end + + def teardown + @saved_image ? ENV["UKC_SANDBOX_IMAGE"] = @saved_image : ENV.delete("UKC_SANDBOX_IMAGE") + super + end + + INSTANCE = { uuid: "u1", state: "running", plugins: [{ name: "sandbox", rom: "r" }] }.freeze + + # The sandbox plugin's answers, for the routes these tests use. + def plugin(call) + case [call.verb, call.path] + in ["POST", "/commands"] then ok(uuid: "c1") + in ["GET", "/commands"] then ok(commands: %w[c1 c2]) + in ["POST", "/commands/c1/wait_timeout"] then [408, { status: "error", message: "Timed out" }] + in ["GET", "/commands/c1"] then ok(uuid: "c1", cmdline: "x", exitcode: @exitcode) + in ["GET", "/commands/c1/logs"] + ok(stdout: ["hi\n"].pack("m0"), stderr: "", stdout_available: 3, stderr_available: 0) + in ["GET", "/commands/c1/logs/raw/stdout"] then "\x00\xFF" + in ["POST", "/fs/read_raw"] then "\x00\x01\xFE\xFF" + in ["POST" | "DELETE", _] then ok(nil) + end + end + + # A client whose platform holds INSTANCE (or `instance`) and whose plugin + # answers through #plugin. The block may answer first; nil falls through. + def cloud(instance: INSTANCE, metros: nil, **opts, &extra) + client(**opts) do |call| + hit = extra&.call(call) + next hit if hit + next plugin(call) if call.base_url.include?("/plugins/") + next metros if metros && call.path == "/v1/metros" + + ok(instances: [instance]) + end + end + + def posts = @cloud.calls.select { |c| c.verb == "POST" } + def creates = @cloud.calls.select { |c| c.verb == "POST" && c.path == "/v1/instances" } + + # --- creating ------------------------------------------------------------ + + def test_create_takes_the_defaults_and_probes_the_plugin + sb = cloud(metro: :fra).metro(:fra).sandboxes.create + body = creates.first.body + + assert_equal({ "image" => Sandbox::DEFAULT_IMAGE, "memory_mb" => 2048, + "plugins" => [{ "name" => "sandbox", "rom" => Sandbox::DEFAULT_PLUGIN_ROM }], + "autokill" => { "time_ms" => Sandbox::DEFAULT_AUTOKILL_MS }, + "autostart" => true, "timeout_s" => Sandbox::DEFAULT_BOOT_WITHIN }, body) + assert_equal "u1", sb.uuid + assert_equal "fra", sb.metro + assert_equal PLUGIN, sb.base_url + probe = @cloud.calls.last + + assert_equal ["GET", PLUGIN, "/commands"], [probe.verb, probe.base_url, probe.path] + end + + def test_the_spec_and_the_environment_beat_the_defaults + fra = cloud(metro: :fra).metro(:fra) + fra.sandboxes.create(image: "img", memory_mb: 512) + + assert_equal %w[img 512], creates.last.body.values_at("image", "memory_mb").map(&:to_s) + ENV["UKC_SANDBOX_IMAGE"] = "from-env" + fra.sandboxes.create + + assert_equal "from-env", creates.last.body["image"] + fra.sandboxes.create({ "image" => "img" }) + + assert_equal "img", creates.last.body["image"] + ENV["UKC_SANDBOX_IMAGE"] = "" + fra.sandboxes.create(image: "") + + assert_equal Sandbox::DEFAULT_IMAGE, creates.last.body["image"] + end + + def test_a_snapshot_source_gets_no_image_memory_or_plugin + ENV["UKC_SANDBOX_IMAGE"] = "from-env" + fra = cloud(metro: :fra).metro(:fra) + [{ template: { uuid: "t1" } }, { branch_from: { name: "o" } }, + { checkpoint: { name: "cp" } }].each do |source| + fra.sandboxes.create(**source) + body = creates.last.body + + assert body["autostart"] + assert_equal({ "time_ms" => Sandbox::DEFAULT_AUTOKILL_MS }, body["autokill"]) + assert_empty body.keys & %w[image memory_mb plugins] + end + end + + def test_the_boot_wait_follows_ready + fra = cloud(metro: :fra).metro(:fra) + fra.sandboxes.create(ready: false) + + assert_equal 0, creates.last.body["timeout_s"] + refute(@cloud.calls.any? { |c| c.base_url.include?("/plugins/") }) + fra.sandboxes.create(ready: false, boot_within: 10) + + assert_equal 10, creates.last.body["timeout_s"] + # The create request is held open for the boot, unless timeout: says. + assert_equal 20, creates.last.options[:timeout] + fra.sandboxes.create(ready: false, boot_within: 10, timeout: 5) + + assert_equal 5, creates.last.options[:timeout] + end + + def test_the_callers_own_plugin_entry_is_kept + fra = cloud(metro: :fra).metro(:fra) + fra.sandboxes.create(image: "img", + plugins: [{ name: "sandbox", rom: "mine:1", config: { a: 1 } }]) + + assert_equal [{ "name" => "sandbox", "rom" => "mine:1", "config" => { "a" => 1 } }], + creates.last.body["plugins"] + fra.sandboxes.create(image: "img", plugins: [{ name: "other", rom: "o:1" }]) + + assert_equal [{ "name" => "sandbox", "rom" => Sandbox::DEFAULT_PLUGIN_ROM }, + { "name" => "other", "rom" => "o:1" }], creates.last.body["plugins"] + fra.sandboxes.create(template: { uuid: "t1" }, plugins: [{ name: "other", rom: "o:1" }]) + + assert_equal [{ "name" => "other", "rom" => "o:1" }], creates.last.body["plugins"] + custom = fra.sandboxes.create(template: { uuid: "t1" }, plugin_name: "custom") + + assert_equal "custom", custom.plugin_name + assert_nil creates.last.body["plugins"] + end + + def test_two_roms_for_one_plugin_are_refused + fra = cloud(metro: :fra).metro(:fra) + [{ image: "img", rom: "a:1", plugins: [{ name: "sandbox", rom: "b:1" }] }, + { template: { uuid: "t1" }, rom: "a:1" }, + { template: { uuid: "t1" }, plugins: [{ name: "sandbox", rom: "b:1" }] }].each do |spec| + err = assert_raises(Error) { fra.sandboxes.create(spec) } + + assert_equal :config, err.kind + end + assert_empty posts + end + + def test_fields_a_sandbox_manages_are_refused + fra = cloud(metro: :fra).metro(:fra) + err = assert_raises(Error) { fra.sandboxes.create(image: "img", replicas: 2) } + + assert_equal :config, err.kind + [{ autostart: false }, { timeout_s: 5 }, { wait_timeout_ms: 5000 }].each do |field| + assert_match(/boot_within:/, + assert_raises(Error) { fra.sandboxes.create(image: "img", **field) }.message) + end + assert_empty posts + end + + def test_client_options_on_a_borrowed_client_are_refused + ukc = cloud(metro: :fra) + fra = ukc.metro(:fra) + + refuse = ->(pattern, &call) { assert_match(pattern, assert_raises(Error, &call).message) } + + assert_equal :config, assert_raises(Error) { fra.sandboxes.create(token: "o") }.kind + refuse.call(/would be ignored/) { fra.sandboxes.get(uuid: "u1", token: "o") } + refuse.call(/one step earlier/) { fra.sandboxes.create(metros: :dal) } + refuse.call(/one step earlier/) { fra.sandboxes.create(metro: :dal) } + refuse.call(/that client's own `sandboxes`/) { fra.sandboxes.get(uuid: "u1", client: ukc) } + refuse.call(/would be ignored/) { Sandbox.create(client: ukc, token: "o") } + refuse.call(/drop `client:`/) { Sandbox.connect(uuid: "u1", client: ukc, user_agent: "ua") } + + assert_empty posts + end + + def test_client_config_tracks_the_client_keywords + keywords = Unikraft::Cloud::Client.instance_method(:initialize).parameters.map(&:last) + + assert_equal keywords - %i[headers timeout], Unikraft::Cloud::Resources::Sandboxes::CLIENT_CONFIG + end + + def test_the_static_door_builds_a_client_and_picks_its_metro + @cloud = FakeCloud.new do |call| + call.base_url.include?("/plugins/") ? plugin(call) : ok(instances: [INSTANCE]) + end + sb = Sandbox.create(token: "t", metros: :dal, transport: @cloud.transport, user_agent: "ua/1") + + assert_equal "dal", sb.metro + assert_equal "https://api.dal.unikraft.cloud", creates.first.base_url + assert_equal "ua/1", @cloud.transports.first.config[:user_agent] + err = assert_raises(Error) do + Sandbox.create(token: "t", metros: %i[dal sin], transport: @cloud.transport) + end + + assert_match(/single metro/, err.message) + assert_equal "dal", + Sandbox.connect(uuid: "u1", metro: :dal, token: "t", + transport: @cloud.transport).metro + end + + def test_a_borrowed_client_still_takes_a_metro + ukc = cloud(metro: :fra) + + assert_equal "dal", Sandbox.create(client: ukc, metros: :dal).metro + end + + def test_a_missing_token_is_a_config_error + assert_equal :config, assert_raises(Error) { Sandbox.connect(uuid: "u1", metro: :fra) }.kind + end + + def test_a_pinned_cluster_serves_the_plugin_endpoint + url = "https://api.ukp-staging.example.com" + ukc = cloud(metro: url) + sb = ukc.metro(:fra).sandboxes.create(image: "img") + + assert(@cloud.calls.all? { |c| c.base_url.start_with?(url) }) + assert_equal "#{url}/v1/instances/u1/plugins/sandbox", sb.base_url + other = "https://api.other-staging.example.com/v1" + listed = ukc.metro(:fra).sandboxes.list(base_url: other).first + + assert_equal "https://api.other-staging.example.com/v1/instances/u1/plugins/sandbox", + listed.base_url + end + + def test_a_discovered_metros_own_endpoint_is_used + found = ok(metros: [{ iata_code: "fra", endpoint: "https://api.fra-2.internal.example" }]) + ukc = cloud(metros: found) + sb = Sandbox.connect(uuid: "u1", client: ukc) + + assert_equal "fra", sb.metro + assert_equal "https://api.fra-2.internal.example/v1/instances/u1/plugins/sandbox", sb.base_url + @cloud.calls.clear + sb.delete + + assert(@cloud.calls.all? { |c| c.host == "api.fra-2.internal.example" }) + refute_empty @cloud.calls + made = ukc.metro(:fra).sandboxes.create(image: "img") + + assert_equal sb.base_url, made.base_url + end + + def test_headers_reach_the_create_and_the_probe + cloud(metro: :fra).metro(:fra).sandboxes.create(image: "img", headers: { "X-Trace" => "abc" }) + + assert_equal(%w[abc abc], @cloud.calls.first(2).map { |c| c.options[:headers]["X-Trace"] }) + end + + # --- readiness ----------------------------------------------------------- + + def test_a_failed_wait_deletes_what_create_made_and_says_why + fra = cloud(metro: :fra) { |call| [404, {}] if call.base_url.include?("/plugins/") }.metro(:fra) + err = assert_raises(Error) { fra.sandboxes.create(image: "img", ready: FAST) } + + assert_equal :timeout, err.kind + assert_nil err.status + assert_match(/the instance is running/, err.message) + assert_match(/The sandbox was deleted/, err.message) + assert_includes @cloud.verbs, "DELETE" + # Each probe gets the time left, so none outlives the deadline. + probes = @cloud.calls.select { |c| c.path == "/commands" } + + # (Within float rounding of the deadline arithmetic.) + assert(probes.all? { |c| c.options[:timeout] <= FAST[:within] + 1e-6 }) + end + + def test_a_failed_wait_on_get_deletes_nothing + fra = cloud(metro: :fra) { |call| [404, {}] if call.base_url.include?("/plugins/") }.metro(:fra) + err = assert_raises(Error) { fra.sandboxes.get(uuid: "u1", ready: FAST) } + + assert_equal :timeout, err.kind + refute_match(/deleted/, err.message) + refute_includes @cloud.verbs, "DELETE" + end + + def test_an_instance_that_never_ran_is_diagnosed_as_a_pull + stopped = { uuid: "u1", state: "stopped", image: "my-org/base:latest", + plugins: [{ name: "sandbox", rom: "plugins/sandbox:typo" }] } + fra = cloud(metro: :fra, instance: stopped.merge(stop_reason: 0b00100)) do |call| + [404, {}] if call.base_url.include?("/plugins/") + end.metro(:fra) + message = assert_raises(Error) { fra.sandboxes.create(image: "img", ready: FAST) }.message + + assert_match(/never started/, message) + assert_includes message, "`my-org/base:latest`" + assert_includes message, "`plugins/sandbox:typo`" + refute_match(/console log/, message) + [{ start_count: 1 }, { started_at: "2026-01-01T00:00:00Z" }, + { stop_reason: 0b00011 }].each do |ran| + fra = cloud(metro: :fra, instance: stopped.merge(ran, exit_code: 1)) do |call| + [404, {}] if call.base_url.include?("/plugins/") + end.metro(:fra) + message = assert_raises(Error) { fra.sandboxes.create(image: "img", ready: FAST) }.message + + assert_match(/console log/, message) + assert_match(/exited with code 1/, message) + end + end + + def test_the_create_block_deletes_the_sandbox_however_it_ends + fra = cloud(metro: :fra).metro(:fra) + + assert_equal(:done, fra.sandboxes.create { |sb| sb.uuid && :done }) + assert_equal "DELETE", @cloud.calls.last.verb + assert_raises(RuntimeError) { fra.sandboxes.create { raise "boom" } } + assert_equal "DELETE", @cloud.calls.last.verb + end + + def test_a_block_that_deleted_the_sandbox_itself_is_not_an_error + gone = { status: "error", message: "Failed to perform all operations", + data: { instances: [{ uuid: "u1", status: "error", error: 8 }] } } + fra = cloud(metro: :fra) do |call| + gone if call.verb == "DELETE" && !call.base_url.include?("/plugins/") + end + .metro(:fra) + + assert_equal 404, assert_raises(Error) { fra.sandboxes.create.delete }.status + assert_equal(:ok, fra.sandboxes.create { :ok }) + end + + # --- reading ------------------------------------------------------------- + + def test_get_resolves_the_plugin_name + fra = cloud(metro: :fra, instance: { uuid: "u1", plugins: [{ name: "mine" }] }).metro(:fra) + + assert_equal "mine", fra.sandboxes.get(uuid: "u1").plugin_name + assert_equal 404, assert_raises(Error) { + fra.sandboxes.get(uuid: "u1", plugin_name: "x") + }.status + fra = cloud(metro: :fra, + instance: { uuid: "u1", + plugins: [{ name: "a" }, { name: "b" }] }).metro(:fra) + + assert_equal :config, assert_raises(Error) { fra.sandboxes.get(uuid: "u1") }.kind + fra = cloud(metro: :fra, instance: { uuid: "u1", plugins: [] }).metro(:fra) + + assert_equal 404, assert_raises(Error) { fra.sandboxes.get(uuid: "u1") }.status + end + + def test_list_is_the_instance_list_filtered_by_plugin + instances = [INSTANCE, { uuid: "u2", plugins: [{ name: "other" }] }, { uuid: "u3" }] + fra = cloud(metro: :fra) { |call| ok(instances:) if call.path == "/v1/instances" }.metro(:fra) + + assert_equal %w[u1], fra.sandboxes.map(&:uuid) + assert_equal %w[u2], fra.sandboxes.list(plugin_name: "other").map(&:uuid) + assert_equal "true", @cloud.calls.last.params["details"] + end + + def test_the_instance_underneath_is_a_lazy_handle + sb = cloud(metro: :fra).metro(:fra).sandboxes.create(ready: false) + @cloud.calls.clear + inst = sb.instance + + assert_empty @cloud.calls + assert_equal "running", inst.state + assert_equal({ "uuid" => "u1", "details" => "true" }, @cloud.calls.last.params) + end + + # --- commands ------------------------------------------------------------ + + def sandbox(&) + cloud(metro: :fra, &).metro(:fra).sandboxes.create(ready: false).tap { @cloud.calls.clear } + end + + def test_run_returns_the_output_and_deletes_the_record + @exitcode = 0 + res = sandbox.run("echo hi", cwd: "/tmp", env: { "A" => "1" }) + + assert_equal ["c1", "hi\n", "", 0], [res.uuid, res.stdout, res.stderr, res.exitcode] + assert_predicate res, :success? + assert_equal({ "cmd" => "echo hi", "cwd" => "/tmp", "env" => { "A" => "1" } }, + @cloud.calls.first.body) + assert_equal %w[POST POST GET GET DELETE], @cloud.verbs + # The wait without a timeout must not be cut short by the transport's. + assert_nil @cloud.calls[1].options.fetch(:timeout) + end + + def test_several_arguments_are_an_argument_vector + @exitcode = 3 + sb = sandbox + res = sb.run("sh", "-c", "exit 3", keep: true) + + assert_equal ["sh", "-c", "exit 3"], @cloud.calls.first.body["cmd"] + refute_predicate res, :success? + refute_includes @cloud.verbs, "DELETE" + assert_raises(ArgumentError) { sb.spawn } + end + + def test_a_timed_out_run_keeps_the_command + res = sandbox.run("sleep 100", within: 1) + + assert_nil res.exitcode + assert_equal %w[POST POST GET GET], @cloud.verbs + assert_equal({ "timeout_s" => 1 }, @cloud.calls[1].body) + assert_equal 11, @cloud.calls[1].options[:timeout] + @cloud.calls.clear + sandbox.command("c1").wait(within: 1, timeout: 3) + + assert_equal 3, @cloud.calls.last.options[:timeout] + end + + def test_a_plugin_error_is_the_sdks_own_error + sb = sandbox do |call| + [500, { status: "error", message: "boom" }] if call.verb == "POST" && call.path == "/commands" + end + err = assert_raises(Error) { sb.run("true") } + + assert_equal [:http, 500], [err.kind, err.status] + end + + def test_a_command_reads_like_an_io + cmd = sandbox.spawn("cat") + cmd.write("hi\n").close_write.signal(:TERM) + + assert_equal [{ "data" => ["hi\n"].pack("m0") }, { "data" => "", "eof" => true }, + { "signal" => "TERM" }], @cloud.calls.drop(1).map(&:body) + assert_equal "hi\n", cmd.wait.logs.stdout + assert_equal "\x00\xFF".b, cmd.read(:stdout, offset: -2) + assert_equal "bytes=-2", @cloud.calls.last.options[:headers]["Range"] + cmd.read(:stdout, offset: 1, limit: 2) + + assert_equal "bytes=1-2", @cloud.calls.last.options[:headers]["Range"] + end + + def test_an_unusable_range_never_reaches_the_wire + cmd = sandbox.command("c1") + + [{ limit: 0 }, { limit: 2.5 }, { offset: Float::NAN }, { offset: -1, limit: 1 }].each do |range| + assert_equal :config, assert_raises(Error) { cmd.read(:stdout, **range) }.kind + end + assert_empty @cloud.calls + end + + def test_commands_lists_every_command + sb = sandbox + + assert_equal %w[c1 c2], sb.commands.map(&:uuid) + assert_equal "c9", sb.command("c9").uuid + end + + # --- files --------------------------------------------------------------- + + def test_files_send_text_as_utf8_and_bytes_as_base64 + files = sandbox.files + files.write("/a", "héllo") + files.write("/b", "\x00\xFF".b, append: true) + files.upload("/dir", "c.txt", StringIO.new("io"), parents: false) + files.mkdir("/x/y") + + assert_equal [{ "path" => "/a", "append" => false, "encoding" => "utf-8", "data" => "héllo" }, + { "path" => "/b", "append" => true, "encoding" => "base64", "data" => "AP8=" }, + { "path" => "/dir", "filename" => "c.txt", "parents" => false, + "encoding" => "utf-8", "data" => "io" }, + { "path" => "/x/y", "parents" => true }], @cloud.calls.map(&:body) + assert_equal %w[/fs/write /fs/write /fs/upload /fs/mkdir], @cloud.paths + assert_equal "\x00\x01\xFE\xFF".b, files.read("/bin") + assert_equal({ "path" => "/bin" }, @cloud.calls.last.body) + end +end diff --git a/unikraft-cloud.gemspec b/unikraft-cloud.gemspec index 6c50b1d..667d453 100644 --- a/unikraft-cloud.gemspec +++ b/unikraft-cloud.gemspec @@ -23,4 +23,7 @@ Gem::Specification.new do |spec| .split("\x0") .select { |f| f.start_with?("lib/", "README", "LICENSE") } spec.require_paths = ["lib"] + + # The generated plumbing of the sandbox plugin, which `sandboxes` wraps. + spec.add_dependency "unikraft-cloud-plugin-sandbox-api", "~> 1.0" end