Ruby SDK
unikraft-cloud is the official Ruby SDK for Unikraft Cloud.
It covers the per-metro platform API and the global control plane API.
The SDK has two layers:
- The porcelain layer gives results without the response envelope, reads all the pages for you, sends reads to all metros, and lets you chain operations on a resource.
- The plumbing layer is the OpenAPI specification as written: one method for each operation, the raw response envelope, and one metro for each call.
Use the porcelain layer for most work. Use the plumbing layer for the operations that the porcelain layer doesn't have.
Installation
Code
To use Bundler, add the gem to your Gemfile:
Gemfile
The SDK needs Ruby 3.3 or later.
It has no runtime dependencies: it uses net/http, json and uri from the Ruby standard library.
Quickstart
quickstart.rb
Authentication
The client reads a bearer token from the UKC_TOKEN environment variable.
To give the token in your code, use the token: option.
Create a token in the Unikraft Cloud console.
Configuration
Unikraft::Cloud.new returns a Unikraft::Cloud::Client.
All the options have a default value or aren't necessary:
| Option | Default | Description |
|---|---|---|
token: | UKC_TOKEN | The bearer token. |
metro: | UKC_METRO | The metro of create and of the default scope: a metro code, such as :fra, or the full http(s):// address of an endpoint. |
metros: | :all, or the metro: value | The default scope of reads and bulk operations: :all, one metro, or a list of metros. |
base_url: | None | The address of the platform API, which overrides metro:. |
control_plane_url: | The global control plane | The address of the control plane API, for metro discovery and for ukc.api.controlplane. |
headers: | {} | The headers to add to each request. |
timeout: | 60 | The time limit in seconds to connect and to read. nil sets no limit. |
proxy_from_env: | true | Use the http_proxy, https_proxy and no_proxy environment variables. |
user_agent: | unikraft-cloud-ruby/<version> | The User-Agent header. |
transport: | None | A callable that makes the HTTP transport, as Custom transport shows. |
The client is thread-safe. Make one client and use it in all the threads of your program. Don't make a client for each request. All the scopes and handles of a client use the same list of metros and the same connections.
close closes the connections of the client.
A call after close opens the connections again.
In a script, use Unikraft::Cloud.open with a block.
It closes the client after the block, and returns the value of the block:
Code
Metros
The platform API has one endpoint for each metro.
By default, the client sends each read to all the metros that the account can use, at the same time, and merges the results.
Each result has a metro attribute, which tells the metro of the result.
Code
The client gets the list of metros from the control plane one time, and keeps it.
A scope that names its metros doesn't need this request.
The control plane gives the endpoint of each metro, so the client can use a new metro without an SDK update.
Unikraft::Cloud::KNOWN_METROS lists the metros that existed at the release of the SDK version.
Give a metro as a Symbol or as a String.
To set the default scope, give metro: or metros: when you make the client:
Code
UKC_METRO has the same effect as metro:.
If you give metro: and metros:, metros: sets the scope, and create uses metro:.
How the client uses more than one metro
- A read goes to all the metros in the scope. The client returns the pages in the order that they arrive, so a slow metro doesn't stop the results of a fast metro. The client gets the next page of a metro only when you have used all the items of its last page.
- When you stop early, for example with
firstorbreak, the client stops the requests to the other metros. An external enumerator (next) can't stop them: if you don't read it to the end, it keeps one thread for each metro until the process stops. Thus, useeach,firstorlazy. createuses one metro. This metro is themetro:argument of the call, the metro of the scope, or the default metro of the client (metro:, thenUKC_METRO, thenfra). If the scope has more than one named metro, the scope must include the default metro. If not,createraises an error withkind: :config.- A bulk operation finds the resources first.
Then it sends one call to each metro that has a match.
Thus,
delete(name: "web")in a wide scope deletes all thewebresources in the scope. To delete only one, make the scope smaller, or addmetro:to the reference. - The control plane is global, so the scope has no effect on it.
Names in more than one metro
A name is unique only in one metro. Thus, two metros can each have a resource with the same name. You can select a resource by its name in three ways:
Code
A UUID identifies one resource in all the metros.
But in a scope with more than one metro, the SDK reads each metro to find a uuid: reference too.
To send one request, add metro: or use a scope with one metro.
A handle from get must find exactly one resource, because the next operation can change it.
get sends no request, so the first use of the handle finds the resource.
If the name matches resources in more than one metro, this first use raises AmbiguousRefError.
The error contains the matches, so you don't have to send more requests:
Code
To use all the matches, use where.
where finds the matches one time, and it's Enumerable on them.
Each operation goes to the metro of each match:
Code
An operation on where returns an Array.
Instances, volumes, services and certificates have where.
Partial failures
If a metro doesn't answer, the client keeps the results of the other metros.
The client first returns the results of the metros that answered.
Then it raises MetroFanoutError, with the metros that failed:
Code
A bulk operation and an operation on where can't return results one at a time.
For these operations, the results attribute of the error has the results of the metros that succeeded.
Lists
list returns a lazy Enumerator.
The enumerator gets the pages of each metro in the scope when you need them.
With a block, list gives each item to the block, and returns the resource client.
The tags: argument filters instances and volumes by tag.
Each resource client, such as ukc.instances, is Enumerable on all the resources in the scope, with their details:
Code
Each result is a model.
A model has a reader for each field, #[] for each key, and #to_h.
Models support pattern matching, also on the metro attribute:
Code
Chainable handles
An operation on one resource returns a handle: a reference to one resource in one metro.
get sends no request.
When you read an attribute, the handle gets the resource one time and keeps it:
Code
An operation that changes a resource sends its request immediately. It returns a new handle, at the same location, with the data that the endpoint returned. Thus, you can chain the calls:
Code
The number of requests depends on the reference and on the scope:
| Reference and scope | Requests for get(...).suspend |
|---|---|
name: and metro:, any scope | One request: the suspend. |
name:, one metro in the scope | One request: the suspend. |
name:, more than one metro in the scope | One read to each metro to find the instance, then the suspend in the metro of the instance, or AmbiguousRefError if more than one metro has a match. |
A handle has metro, location, model, to_h, [], and a reader for each attribute:
Code
A handle from an operation that changes the resource has only the fields that its endpoint returns.
For example, suspend returns uuid, name, state and previous_state.
To read a field that the handle has no reader for, use [], for example handle[:previous_state].
If you read an attribute that the reply doesn't have, such as memory_mb, the handle gets it from the platform one time.
Use a handle in one thread only. You can share the client between threads.
Each porcelain operation also has a form without a handle.
The reference keys (name:, uuid:, metro:) find the resource, and the other arguments go to the operation.
For example, ukc.instances.logs(name: "web", offset: -4096) is the same as ukc.instances.get(name: "web").logs(offset: -4096).
On a resource client, start, stop, suspend and delete are bulk operations.
See References.
Updating a resource
Give the properties as keyword arguments.
A value sets the property, nil removes it, and the update doesn't change a property that you don't give.
This is the behavior of JSON Merge Patch:
Code
headers: and timeout: are always options of the call, not properties.
For example, update(memory_mb: 512, timeout: 10) sets a time limit of 10 seconds.
To add values to a property, or to remove some of its values, use edit.
edit collects the operations and sends them in one request.
Use a block or a chain:
Code
remove is the del operation of the API.
The block form sends the request at the end of the block.
The chain form sends the request on apply.
Both forms return a handle, so you can continue the chain:
Code
You can also use update and edit without a handle, for example ukc.instances.update(name: "web", memory_mb: 512).
To send the raw operations of the API, give a list of { prop:, op:, value: } items:
Code
References
An operation on a resource takes a reference: name: or uuid:, but not both.
If you give both, the SDK raises ArgumentError.
The SDK sends only the field that you give.
The API validates each identifier, so a name in the uuid field fails with an Invalid uuid error.
Code
Resources
| Resource client | Methods |
|---|---|
ukc.instances | create, get, where, list, each, update, edit, delete, start, stop, suspend, wait, logs, metrics, history |
ukc.volumes | create, get, where, list, each, update, edit, delete, attach, detach |
ukc.services | create, get, where, list, each, update, edit, delete |
ukc.certificates | create, get, where, list, each, update, delete |
ukc.users | quotas, quotas(uuid:) |
The handles have these operations:
| Handle | Operations |
|---|---|
| Instance | reload, start, stop, suspend, delete, update, edit, wait, logs, metrics, history, and a state predicate for each state, such as running?, stopped? and standby? |
| Volume | attach, detach, update, edit, delete |
| Service group | update, edit, delete |
| Certificate | update (with chain: and pkey:), delete |
The plumbing layer has the other operations, for example autoscale, the image registry, node information, and all the control plane:
Code
The plumbing layer
The plumbing layer has a method for each operationId of the OpenAPI specification.
Each method returns the response envelope.
The porcelain layer contains a plumbing client, so the plumbing layer is available from the same client and with the same credentials:
Code
A plumbing client uses one metro: the metro of its base_url:.
To send one call to a different metro, give base_url: to the call.
The SDK has plumbing clients for the two APIs:
Unikraft::Cloud::API::Platformandukc.api.platformfor the platform API: instances, volumes, services, certificates, autoscale, and images in one metro.Unikraft::Cloud::API::ControlPlaneandukc.api.controlplanefor the global control plane API: the account, the metros, images and self-hosted nodes. The control plane has no porcelain layer.
Code
Errors
A network failure, a response with a status that isn't 2xx, or an error in the body of a 2xx response raises Unikraft::Cloud::Error:
Code
e.kind tells which layer failed:
kind | Description |
|---|---|
:http | The server sent a status that isn't 2xx, or an error in the body of a 2xx response, and e.status and e.errors have the details. |
:network | The request got no answer, for example because of a refused connection, a reset, a DNS failure, a proxy that isn't available, or the end of the timeout: time limit. |
:parse | The server sent a body that isn't the JSON that the operation expects. |
:fanout | An operation on more than one metro failed in part, as in Partial failures, or the scope isn't correct. |
:config | The SDK can't send the call with this configuration, for example because a GET has a body, or because create has a scope of metros without the default metro. |
:timeout | The polling helper used all its time: the error has no status, because no request failed, and e.cause has the last failure. |
AmbiguousRefError and MetroFanoutError are subclasses of Unikraft::Cloud::Error.
Thus, one rescue Unikraft::Cloud::Error catches all the errors of the SDK.
An argument that isn't correct, such as a reference with name: and uuid:, raises ArgumentError.
The API can report an error in the body of a 2xx response, for each item.
For such an error, e.status is the HTTP status of the error code, for example 404 for a resource that doesn't exist, or nil.
Waiting
The SDK sends each request one time, and doesn't send it again after a failure.
There's one exception: if the server closes a reused connection before the response, the SDK sends a GET, HEAD, PUT, DELETE or OPTIONS request again on a new connection.
To wait for an instance, use wait:
Code
wait sends the state and the time limit in seconds to the platform.
The platform keeps the connection open until the instance gets to the state, or until the time limit.
-1 waits with no time limit.
This is one request, and the SDK makes the read timeout of this request longer than the wait.
The timeout: option is the HTTP time limit, as for all other calls.
To wait for a service that has no such endpoint, use the polling helper Unikraft::Cloud::Core::Ready.wait_until_ready.
The helper calls your block until the block returns without an error.
It gives the block the seconds that stay until the time limit, so that the block can use them as the timeout: of its request.
For example, this block waits until the instance web exists in fra:
Code
The interval between two calls starts at 100 ms and doubles to a maximum of 2 s, with a random change.
By default, the helper stops after 60 s, and raises an error with kind: :timeout.
It calls the block again only after a failure that can change: a network failure, or a 404, 502, 503 or 504 status.
It raises the other errors immediately.
Thus, a token that isn't correct causes a 401 or 403 error, and not a timeout.
Self-hosted and staging deployments
metro: and UKC_METRO also accept the full http(s):// address of an endpoint.
The SDK uses the address without changes, and doesn't make a https://api.<metro>.unikraft.cloud address from it.
The SDK removes a /v1 at the end of the address, because the path of each operation starts with /v1:
Code
With an address, the client uses only this endpoint.
It doesn't get the list of metros from the control plane, and it doesn't make other URLs, for all scopes.
To use the control plane of the same deployment, give control_plane_url::
Code
Custom transport
To use a different HTTP library, to add instrumentation, or to replace the HTTP transport in tests, give transport:.
transport: is a callable.
It receives the transport keywords base_url:, token:, headers:, timeout:, proxy_from_env: and user_agent:.
It returns an object with the request, bytes and stream methods, as Unikraft::Cloud::Core::ApiClient has:
Code
Debugging with a proxy
The client uses the proxy environment variables through Net::HTTP.
Thus, to see the traffic of the SDK, you can send it through a proxy such as mitmproxy, and not change your code:
Code
The client uses http_proxy, https_proxy and no_proxy, in lowercase or in uppercase.
SSL_CERT_FILE replaces the default trusted certificates of OpenSSL for the process, so that the client trusts the certificate of the proxy.
Remove SSL_CERT_FILE when you're done.
To ignore the proxy variables in one client, use Unikraft::Cloud.new(proxy_from_env: false).
Source
The source of the SDK is at github.com/unikraft-cloud/ruby-sdk, and the gem is at rubygems.org/gems/unikraft-cloud.
See examples/ for complete programs.
Learn more
- JavaScript SDK: the client library for the same platform API in JavaScript and TypeScript.
- Python SDK: the client library for the same platform API in Python.
- Go SDK: the client library for the same platform API in Go.
- Metros: the regions that the SDK uses.
- Instances: create and manage the instances that the SDK controls.
- Unikraft Cloud's REST API reference, which the plumbing layer mirrors.