Foundational Compute

Python SDK

Classes, methods, options and defaults of the fdtn Python package. Times are in seconds.

1Install

Needs Python 3.11 or newer. The CLI install puts the SDK in ~/.fdtn; run your code with ~/.fdtn/bin/python.

$ curl -fsSL https://compute.fdtn.dev/install | sh -s -- --python
$ fdtn auth
$ ~/.fdtn/bin/python hello.py

In your own environment (also Windows):

$ pip install https://compute.fdtn.dev/install/fdtn-0.1.5-py3-none-any.whl

The SDK reads the key from api_key=, then FDTN_API_KEY, then ~/.fdtn/key. See API keys.

2Create a sandbox

create.py
from fdtn import Sandbox

sbx = Sandbox.create(
    "base",
    timeout=600,                          # lifetime in seconds
    metadata={"run": "eval-1"},
    envs={"MODE": "test"},
    request_timeout=1800,                 # wait up to 30 minutes in the queue
)
print(sbx.sandbox_id)
OptionDefaultWhat it does
template"base"base, small, claude or your own. Sets the size.
timeout300 (5 minutes)Lifetime in seconds. Maximum 86400 (24 hours).
metadata{}String pairs to find and group sandboxes.
envs{}Environment variables for every command. After a resume, pass them per command (envs on commands.run).
allow_internet_accessTrueFalse blocks all outbound traffic.
networkprivate portsDict: allow_public_traffic (default False), allow_out and deny_out (lists of addresses or ranges).
lifecyclekill on timeout{"on_timeout": "pause"} pauses when the lifetime ends.
request_timeout60 secondsHow long the SDK waits for an answer. 0: no limit.
api_key, domainsee API keysKey and service domain for this call.

Metadata: up to 64 pairs, keys 1 to 128 bytes, values up to 1024 bytes. fdtn_ keys are reserved, except fdtn_own_fleet_only (Create options).

When machines are busy, a create waits in the queue for up to 30 minutes. For batch work, set request_timeout=1800.

3Run commands

sbx.commands.run waits and returns stdout, stderr and exit_code. A non-zero exit raises CommandExitException.

result = sbx.commands.run("python3 -c 'print(1 + 1)'")
print(result.stdout)        # "2\n"

# Stream output; no time limit
sbx.commands.run("pip install requests", on_stdout=print, on_stderr=print, timeout=0)

# Background: returns a handle at once
server = sbx.commands.run("python3 -m http.server 8000", background=True, timeout=0)
server.kill()
OptionDefaultWhat it does
backgroundFalseTrue returns a handle at once.
cwduser's home folderFolder to run in.
usertemplate's userUser, such as "root".
envs{}Variables for this command. Override the create envs.
on_stdout, on_stderrnoneFunctions that get output as it comes.
stdinFalseTrue keeps standard input open for send_stdin.
timeout60 secondsLongest run time. 0: no limit.
request_timeoutnoneNot used here. timeout limits the start and the run.

A background handle has pid, wait(), kill(), send_stdin(data), close_stdin() and disconnect(). By PID: sbx.commands.list(), connect(pid), send_stdin(pid, data), close_stdin(pid) and kill(pid).

4Read and write files

Every method also takes user= and request_timeout=. To copy folders, use fdtn cp -r (Files).

sbx.files.write("/app/input.json", '{"n": 3}')
data = sbx.files.read("/app/model.bin", format="bytes")
for entry in sbx.files.list("/app"):
    print(entry.name, entry.type, entry.size)
MethodReturnsWhat it does
read(path, format="text")str, bytes or a streamformat: "text", "bytes" or "stream".
write(path, data)file infoWrites text, bytes or an open file. Makes missing folders.
list(path, depth=1)list of entriesEntries with name, type, path, size, modified_time and more.
exists(path), get_info(path)bool, entryChecks one path.
make_dir(path), rename(old_path, new_path), remove(path)bool, entry, NoneMakes, moves or removes. remove also removes folder contents.

5Pause, resume and stop

Pause keeps memory and files and stops the charge. Sandbox.connect resumes from the same point (paused limits).

sandbox_id = sbx.sandbox_id
sbx.pause()

# Later, from any program with the same key:
sbx = Sandbox.connect(sandbox_id)       # resumes it
sbx.kill()
MethodWhat it does
Sandbox.connect(sandbox_id, timeout=None)Object for a sandbox; a paused one resumes. timeout sets a new lifetime; a running sandbox keeps a later end time.
sbx.pause()False if already paused.
sbx.kill()Ends the sandbox and deletes its files.
sbx.set_timeout(seconds)Time left, from now. Maximum 86400.
sbx.get_info()sandbox_id, template_id, metadata, started_at, end_at, state, cpu_count, memory_mb and more.
sbx.is_running()Tells if the sandbox answers.
sbx.get_metrics(start=None, end=None)Samples of CPU, memory and disk use. The first seconds have no samples.
sbx.get_host(port)Host name for a port (Ports).
sbx.create_snapshot(name=None)Saves the sandbox as a template. Give name, then start from it with Sandbox.create(name). Delete it with fdtn api /templates/<name> -X DELETE.
Sandbox.list(query=None, limit=None, order=None)Pager with has_next and next_items(). Usually one page, newest first. Sort on your side for another order.
from fdtn import Sandbox, SandboxQuery, SandboxState

pager = Sandbox.list(query=SandboxQuery(metadata={"run": "eval-1"},
                                        state=[SandboxState.RUNNING, SandboxState.PAUSED]))
while pager.has_next:
    for info in pager.next_items():
        print(info.sandbox_id, info.state)

Timeouts

Setting (seconds)WhereDefaultLimit
Sandbox lifetimeSandbox.create(timeout=), set_timeout()30086400
Command run timecommands.run(timeout=)600 means no limit
Wait for an answerrequest_timeout= on any call600 means no limit

Errors

Import from fdtn or fdtn.exceptions. Status codes: HTTP API errors.

ClassWhen
AuthenticationExceptionNo key, a wrong key, or an unsafe key file.
CommandExitExceptionNon-zero exit. Has exit_code, stdout, stderr.
TimeoutExceptionA timeout passed, or the lifetime ended.
SandboxNotFoundExceptionUnknown or ended sandbox.
NotFoundException, FileNotFoundExceptionA file, folder or template is missing.
InvalidArgumentExceptionA wrong argument.
NotEnoughSpaceExceptionThe sandbox disk is full.
RateLimitExceptionToo many requests or queued creates. Wait, then retry.
ServiceBusyExceptionRetry in a moment.
SandboxExceptionBase class of most errors, also 400 and 403. AuthenticationException and ServiceBusyException are separate: catch them too.
from fdtn import CommandExitException

try:
    sbx.commands.run("exit 3")
except CommandExitException as e:
    print(e.exit_code, e.stderr)    # 3

Async API

AsyncSandbox has the same methods as Sandbox. Await every call.

many.py
import asyncio
from fdtn import AsyncSandbox

async def one(i):
    sbx = await AsyncSandbox.create("base", metadata={"run": "demo"}, request_timeout=1800)
    try:
        r = await sbx.commands.run(f"echo {i}")
        return r.stdout.strip()
    finally:
        await sbx.kill()

async def main():
    print(await asyncio.gather(*(one(i) for i in range(10))))

asyncio.run(main())

Next