kosa8 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +46 -4
- data/lib/kosa8/cloud.rb +139 -30
- data/lib/kosa8/cloud_features.rb +41 -5
- data/lib/kosa8/cloud_rl.rb +526 -0
- data/lib/kosa8/errors.rb +84 -6
- data/lib/kosa8/fork_map.rb +276 -0
- data/lib/kosa8/rl.rb +617 -0
- data/lib/kosa8/version.rb +1 -1
- data/lib/kosa8.rb +3 -0
- metadata +5 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: a4f3981efde8733ab02908a318db95c2e32c9da4168d24522e9a990b78b20836
|
|
4
|
+
data.tar.gz: 8634e0ead99043f629f19816d562896894d1b67b52da732c48a6590a6bd87ac7
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: f5136205aedaec3621316c7ac05da880d23126c30592f02d35df932967465e6491b39fa03dca2744528252a16d7d14447a1d01a82720f00b467d376887294d0b
|
|
7
|
+
data.tar.gz: 0abf794ce0bbf4ebda3392cc09d11f6f88c4ac5f215f9ed97e3461fae888c5b22fdb9f941232d2382dfafdf7f545fc511ef7de59bcf550d1dbf1d31e15187a30
|
data/README.md
CHANGED
|
@@ -7,7 +7,7 @@ Method for method it matches [`@kosa8/sdk`](https://github.com/kosa8ai/kosa8-js)
|
|
|
7
7
|
|
|
8
8
|
```sh
|
|
9
9
|
gem install kosa8 -v 0.4.0
|
|
10
|
-
# or in a Gemfile: gem "kosa8", "~> 0.
|
|
10
|
+
# or in a Gemfile: gem "kosa8", "~> 0.5.0"
|
|
11
11
|
export KOSA8_API_KEY=k8c_live_... # made in the cloud dashboard
|
|
12
12
|
```
|
|
13
13
|
|
|
@@ -91,7 +91,7 @@ an id), `secrets:` and `egress:`. `list` takes `name:` and `labels:`.
|
|
|
91
91
|
### Background commands, previews, terminal and more
|
|
92
92
|
|
|
93
93
|
```ruby
|
|
94
|
-
job = box.exec_background("npm run build") # no
|
|
94
|
+
job = box.exec_background("npm run build") # no 90 s limit
|
|
95
95
|
job = box.wait_background(job) # or background_exec(id) to poll once
|
|
96
96
|
puts job["exit"], job["output"]
|
|
97
97
|
|
|
@@ -122,6 +122,47 @@ cloud.pipelines.logs(run["id"])["logs"].each { |l| puts l["text"] }
|
|
|
122
122
|
Also `runs`, `get`, `cancel`, `artifacts`, `download_artifact`, `create_hook` (webhook URL and
|
|
123
123
|
optional `cron:`), `hooks`, `delete_hook`.
|
|
124
124
|
|
|
125
|
+
### RL training and fan-out
|
|
126
|
+
|
|
127
|
+
```ruby
|
|
128
|
+
# Many sandboxes at once, leased: deleted 10 minutes after the last heartbeat.
|
|
129
|
+
batch = cloud.sandboxes.create_many(64, template: "python", run_id: "exp-1", lease_s: 600, prefix: "roll")
|
|
130
|
+
batch.failed # what could not be made, with failure_class
|
|
131
|
+
cloud.sandboxes.heartbeat(run_id: "exp-1") # keep them alive
|
|
132
|
+
cloud.sandboxes.drain(run_id: "exp-1") # delete them all
|
|
133
|
+
|
|
134
|
+
# Forks of a prepared sandbox, 16 at a time; every fork is deleted, Ctrl-C included.
|
|
135
|
+
results = base.fork_map(tasks, concurrency: 16, retries: 2) { |child, task| child.exec(task["cmd"]).stdout }
|
|
136
|
+
|
|
137
|
+
# Grade in a sealed copy: hidden files, no network; the solver never sees them.
|
|
138
|
+
g = box.grade(%w[python /grader/test.py], files: { "/grader/test.py" => File.read("test.py") })
|
|
139
|
+
g.reward # nil when the grader did not finish (failure_class timeout or infra)
|
|
140
|
+
|
|
141
|
+
# A training run: rollouts recorded on kosa8 Cloud (app.kosa8.com, RL runs).
|
|
142
|
+
Kosa8::RL::Run.open(cloud, "grpo-1", lease_s: 600) do |run|
|
|
143
|
+
rollouts = run.map(base, tasks, grade_cmd: %w[python /grader/test.py], group_size: 8) do |sandbox, task|
|
|
144
|
+
sandbox.exec(["python", "agent.py", task["prompt"]])
|
|
145
|
+
end
|
|
146
|
+
rollouts.rewards # nil where masked (infra, quota or your own exception), never 0
|
|
147
|
+
rollouts.groups # per task, for group-relative advantages
|
|
148
|
+
end
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Create, batch, fork and grade send an `Idempotency-Key` (a UUID, or `idempotency_key:`) that every
|
|
152
|
+
retry reuses, so a retry after a timeout never doubles the fleet. Retries (`Kosa8::RetryPolicy`:
|
|
153
|
+
3 tries, backoff with full jitter, at least Retry-After) apply only where safe; every error has
|
|
154
|
+
`failure_class` (`ok`, `exit_nonzero`, `timeout`, `infra`, `quota`, `client`, `error`) and
|
|
155
|
+
`retryable?`.
|
|
156
|
+
|
|
157
|
+
```ruby
|
|
158
|
+
cloud.org_templates.build("swe-task-1", image: "ghcr.io/org/task@sha256:...") # kept as a snapshot
|
|
159
|
+
cloud.org_templates.wait_ready("swe-task-1")
|
|
160
|
+
cloud.sandboxes.create(template: "swe-task-1") # a restore, ~1 s
|
|
161
|
+
|
|
162
|
+
tok = cloud.tokens.create(["sandboxes:read", "sandboxes:write"], sandbox_ids: [box.id], ttl_s: 3600)
|
|
163
|
+
Kosa8::Cloud.new(api_key: tok["secret"]) # hand this to your end user, not your API key
|
|
164
|
+
```
|
|
165
|
+
|
|
125
166
|
### The base template
|
|
126
167
|
|
|
127
168
|
- The `base` template is **Alpine Linux**: `sh` is busybox, and there is no `bash`, `python` or `git`.
|
|
@@ -130,7 +171,7 @@ optional `cron:`), `hooks`, `delete_hook`.
|
|
|
130
171
|
installed outside `/workspace` (`apk add`, a system `pip install`) are gone by the next command. Install
|
|
131
172
|
into `/workspace` (for example `pip install --target /workspace/lib ...` with `PYTHONPATH=/workspace/lib`),
|
|
132
173
|
or chain the steps in one `sh -c`.
|
|
133
|
-
- **A buffered `exec`
|
|
174
|
+
- **A buffered `exec` runs at most 90 seconds** and raises `Kosa8::ExecTimeoutError`. Run long
|
|
134
175
|
work in the background and poll it:
|
|
135
176
|
`box.exec("nohup sh -c 'make test > /workspace/test.log 2>&1; echo $? > /workspace/test.exit' &")`.
|
|
136
177
|
- A request body (command and env) is at most 64 KiB; a file read or write is at most 8 MiB.
|
|
@@ -145,7 +186,7 @@ optional `cron:`), `hooks`, `delete_hook`.
|
|
|
145
186
|
| `Kosa8::PaymentRequiredError` (402) | no payment method (`payment_required`), spending cap reached (`spending_cap_reached`), Store price not accepted (`price_not_accepted`) | show `e.upgrade_url`; an agent should relay `e.agent_message` to its person and stop |
|
|
146
187
|
| `Kosa8::OrgFrozenError` (423, `org_frozen`) | the org is frozen in the Security Center | an owner or admin unfreezes it; retrying does not help |
|
|
147
188
|
| `Kosa8::RateLimitError` (429) | too many requests, or `quota_exceeded` (active sandbox limit) | wait `e.retry_after` seconds when set, or delete sandboxes |
|
|
148
|
-
| `Kosa8::ExecTimeoutError` (504 `exec_timeout`, or today's 502 "timed out" on exec) | a buffered exec ran past
|
|
189
|
+
| `Kosa8::ExecTimeoutError` (504 `exec_timeout`, or today's 502 "timed out" on exec) | a buffered exec ran past its 90 s limit | run it in the background and poll |
|
|
149
190
|
| `Kosa8::UnsupportedError` (501) | the host has no data plane yet (files, checkpoints, rewind, fork, ports) | use `exec`, or try later |
|
|
150
191
|
|
|
151
192
|
Every Cloud error is a `Kosa8::ApiError` carrying the server's stable `e.code`, its message and `e.body`.
|
|
@@ -253,6 +294,7 @@ ruby -w test/test_client.rb # mock daemon on a unix socket
|
|
|
253
294
|
ruby -w test/test_toolbox.rb
|
|
254
295
|
ruby -w test/test_cloud.rb # stub transport and a local socket
|
|
255
296
|
ruby -w test/test_cloud_parity.rb # Cloud API parity, stub transport
|
|
297
|
+
ruby -w test/test_cloud_rl.rb # RL and fan-out, a fake Cloud API on a local socket
|
|
256
298
|
ruby -w -Ilib -Itest -e 'Dir["test/test_*.rb"].sort.each { |f| require File.expand_path(f) }' # all, as CI does
|
|
257
299
|
ruby examples/smoke.rb # live, against a running `kosa8 daemon`
|
|
258
300
|
```
|
data/lib/kosa8/cloud.rb
CHANGED
|
@@ -4,15 +4,24 @@ require "json"
|
|
|
4
4
|
require "net/http"
|
|
5
5
|
require "openssl"
|
|
6
6
|
require "socket"
|
|
7
|
+
require "securerandom"
|
|
8
|
+
require "time"
|
|
7
9
|
require "uri"
|
|
8
10
|
|
|
9
11
|
module Kosa8
|
|
10
12
|
# The outcome of a cloud exec. +woke_ms+ is set when the sandbox was asleep
|
|
11
13
|
# and woke for this command.
|
|
12
|
-
|
|
14
|
+
# +failure_class+ is "ok" (exit 0), "exit_nonzero" (the command failed) or
|
|
15
|
+
# "infra" (the host gave no exit code; +retryable+ true).
|
|
16
|
+
CloudExecResult = Struct.new(:exit_code, :stdout, :stderr, :woke_ms, :failure_class, :retryable,
|
|
17
|
+
keyword_init: true) do
|
|
13
18
|
def ok?
|
|
14
19
|
exit_code == 0 # exit_code is nil when the command never ran
|
|
15
20
|
end
|
|
21
|
+
|
|
22
|
+
def retryable?
|
|
23
|
+
retryable == true
|
|
24
|
+
end
|
|
16
25
|
end
|
|
17
26
|
|
|
18
27
|
# One page of CloudSandboxes#list_page. +next_cursor+ is nil on the last page,
|
|
@@ -37,38 +46,61 @@ module Kosa8
|
|
|
37
46
|
# +code+ (for example payment_required, quota_exceeded). Standard library only.
|
|
38
47
|
#
|
|
39
48
|
# Each exec runs in a fresh container and only /workspace persists; a
|
|
40
|
-
# buffered exec
|
|
49
|
+
# buffered exec runs at most 90 s (ExecTimeoutError), and a request
|
|
41
50
|
# body is at most 64 KiB.
|
|
42
51
|
class Cloud
|
|
43
52
|
DEFAULT_URL = "https://api.kosa8.com"
|
|
44
53
|
KEY_PREFIX = "k8c_live_"
|
|
54
|
+
# A capability token from cloud.tokens.create works as a key too.
|
|
55
|
+
TOKEN_PREFIX = "k8c_tok_"
|
|
45
56
|
LOCAL_HOSTS = %w[localhost 127.0.0.1 ::1].freeze
|
|
46
57
|
# A ttl_s is from 60 seconds to 90 days.
|
|
47
58
|
MIN_TTL_S = 60
|
|
48
59
|
MAX_TTL_S = 7_776_000
|
|
49
60
|
# sleep_after_s is from 0 (never) to 7 days.
|
|
50
61
|
MAX_SLEEP_AFTER_S = 604_800
|
|
51
|
-
# A fork makes from 1 to
|
|
52
|
-
MAX_FORK =
|
|
53
|
-
# The limit kosa8 Cloud puts on a buffered exec
|
|
54
|
-
EXEC_LIMIT_S =
|
|
55
|
-
EXEC_HINT = "a buffered exec is
|
|
62
|
+
# A fork makes from 1 to 1000 copies in one call.
|
|
63
|
+
MAX_FORK = 1000
|
|
64
|
+
# The limit kosa8 Cloud puts on a buffered exec, in seconds (504 exec_timeout past it).
|
|
65
|
+
EXEC_LIMIT_S = 90
|
|
66
|
+
EXEC_HINT = "a buffered exec is stopped after #{EXEC_LIMIT_S} s; run long work in the background, " \
|
|
56
67
|
"writing to /workspace, and poll it"
|
|
57
68
|
|
|
58
69
|
attr_reader :base_url, :timeout, :sandboxes, :functions
|
|
70
|
+
# The RetryPolicy applied to every request where trying again is safe.
|
|
71
|
+
attr_accessor :retry_policy
|
|
72
|
+
# How retries and polls wait: a callable taking seconds (default Kernel#sleep).
|
|
73
|
+
attr_accessor :sleeper
|
|
74
|
+
# Set by Kosa8::RL::Run while it is open: {"run_id" => id, "lease_s" => s}
|
|
75
|
+
# given to every create, batch, fork and grade that does not name its own.
|
|
76
|
+
attr_accessor :run_defaults
|
|
59
77
|
|
|
60
78
|
# transport: an optional callable (method, url, headers, body_or_nil, timeout) -> [status, body_string]
|
|
61
79
|
# or [status, body_string, response_headers], used instead of Net::HTTP (tests, proxies).
|
|
62
|
-
|
|
80
|
+
#
|
|
81
|
+
# retry_policy: (default RetryPolicy.new: 3 tries, backoff with full
|
|
82
|
+
# jitter) is applied where trying again is safe: reads, PUTs, deletes,
|
|
83
|
+
# heartbeats and drains on infra failures; the calls that make sandboxes
|
|
84
|
+
# (create, batch, fork, grade), which carry an Idempotency-Key reused on
|
|
85
|
+
# every retry; and any request answered 429, waiting at least its
|
|
86
|
+
# Retry-After. RetryPolicy::NONE turns it off. sleeper: replaces
|
|
87
|
+
# Kernel#sleep for those waits (tests).
|
|
88
|
+
def initialize(api_key: nil, base_url: nil, env: ENV, timeout: 120, transport: nil, retry_policy: nil,
|
|
89
|
+
sleeper: nil)
|
|
63
90
|
key = (api_key.nil? ? env["KOSA8_API_KEY"].to_s : api_key.to_s).strip
|
|
64
91
|
raise Error, "no kosa8 Cloud API key: pass api_key: or set KOSA8_API_KEY" if key.empty?
|
|
65
|
-
|
|
92
|
+
unless key.start_with?(KEY_PREFIX) || key.start_with?(TOKEN_PREFIX)
|
|
93
|
+
raise Error, "a kosa8 Cloud API key starts with #{KEY_PREFIX} (a capability token with #{TOKEN_PREFIX})"
|
|
94
|
+
end
|
|
66
95
|
|
|
67
96
|
@key = key
|
|
68
97
|
base = [base_url, env["KOSA8_CLOUD_URL"]].find { |v| v && !v.to_s.empty? } || DEFAULT_URL
|
|
69
98
|
@base_url = Cloud.check_base(base.to_s)
|
|
70
99
|
@timeout = timeout
|
|
71
100
|
@transport = transport || method(:net_http)
|
|
101
|
+
@retry_policy = retry_policy || RetryPolicy.new
|
|
102
|
+
@sleeper = sleeper || Kernel.method(:sleep)
|
|
103
|
+
@run_defaults = nil
|
|
72
104
|
@sandboxes = CloudSandboxes.new(self)
|
|
73
105
|
@functions = CloudFunctions.new(self)
|
|
74
106
|
end
|
|
@@ -95,21 +127,70 @@ module Kosa8
|
|
|
95
127
|
r.is_a?(Hash) ? (r["templates"] || []) : []
|
|
96
128
|
end
|
|
97
129
|
|
|
98
|
-
# One JSON request; raises the typed
|
|
99
|
-
|
|
100
|
-
|
|
130
|
+
# One JSON request, retried as retry_policy allows; raises the typed
|
|
131
|
+
# error for an error answer. A call that makes sandboxes (Cloud.keyed?)
|
|
132
|
+
# sends +idempotency_key+ (a new UUID when not given), the same on every
|
|
133
|
+
# retry, so it may be retried after a timeout or a 5xx too.
|
|
134
|
+
#
|
|
135
|
+
# +opts+ (a Hash, not keywords, so an empty body Hash stays the body):
|
|
136
|
+
# :idempotency_key and :retry_policy.
|
|
137
|
+
def request(method, path, body = nil, opts = nil)
|
|
138
|
+
opts ||= {}
|
|
139
|
+
perform(method, path, body, nil, false, opts[:idempotency_key], opts[:retry_policy])
|
|
101
140
|
end
|
|
102
141
|
|
|
103
142
|
# One request whose body is +data+ (raw bytes, application/octet-stream)
|
|
104
143
|
# when given; with +raw+ a successful answer's bytes come back as a binary
|
|
105
144
|
# String instead of parsed JSON. Raises the typed error for an error answer.
|
|
106
|
-
def request_bytes(method, path, data: nil, raw: false)
|
|
107
|
-
perform(method, path, nil, data, raw)
|
|
145
|
+
def request_bytes(method, path, data: nil, raw: false, retry_policy: nil)
|
|
146
|
+
perform(method, path, nil, data, raw, nil, retry_policy)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Methods safe to send twice. Other POSTs are retried only on 429 (refused
|
|
150
|
+
# before anything was done), unless they carry an Idempotency-Key.
|
|
151
|
+
IDEMPOTENT_METHODS = %w[GET HEAD PUT DELETE].freeze
|
|
152
|
+
IDEMPOTENT_POSTS = %w[/v1/sandboxes/heartbeat /v1/sandboxes/drain].freeze
|
|
153
|
+
# The POSTs kosa8 Cloud keeps an Idempotency-Key for (24 hours).
|
|
154
|
+
KEYED_POSTS = %r{\A/v1/sandboxes(/batch|/[A-Za-z0-9_%]{1,64}/(fork|grade))?\z}.freeze
|
|
155
|
+
IDEMPOTENCY_KEY = /\A[\x21-\x7e]{1,255}\z/.freeze
|
|
156
|
+
|
|
157
|
+
# Whether kosa8 Cloud honours an Idempotency-Key on this call.
|
|
158
|
+
def self.keyed?(method, path)
|
|
159
|
+
method == "POST" && KEYED_POSTS.match?(path.to_s.split("?", 2)[0])
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def self.check_idempotency_key(key)
|
|
163
|
+
return if key.nil? || (key.is_a?(String) && IDEMPOTENCY_KEY.match?(key))
|
|
164
|
+
|
|
165
|
+
raise ArgumentError, "idempotency_key must be 1-255 printable ASCII characters, e.g. a UUID"
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
private def perform(method, path, body, data, raw, idempotency_key, policy)
|
|
169
|
+
Cloud.check_idempotency_key(idempotency_key)
|
|
170
|
+
extra = {}
|
|
171
|
+
if !idempotency_key.nil? || Cloud.keyed?(method, path)
|
|
172
|
+
extra["Idempotency-Key"] = idempotency_key || SecureRandom.uuid
|
|
173
|
+
end
|
|
174
|
+
policy ||= @retry_policy
|
|
175
|
+
bare = path.to_s.split("?", 2)[0]
|
|
176
|
+
safe = !extra.empty? || IDEMPOTENT_METHODS.include?(method) || IDEMPOTENT_POSTS.include?(bare)
|
|
177
|
+
attempt = 1
|
|
178
|
+
loop do
|
|
179
|
+
begin
|
|
180
|
+
return perform_once(method, path, body, data, raw, extra)
|
|
181
|
+
rescue Error => e
|
|
182
|
+
raise unless policy.retry?(e, attempt) && (safe || e.status == 429)
|
|
183
|
+
|
|
184
|
+
@sleeper.call(policy.delay(e, attempt))
|
|
185
|
+
attempt += 1
|
|
186
|
+
end
|
|
187
|
+
end
|
|
108
188
|
end
|
|
109
189
|
|
|
110
|
-
private def
|
|
190
|
+
private def perform_once(method, path, body, data, raw, extra)
|
|
111
191
|
headers = { "Authorization" => "Bearer #{@key}", "User-Agent" => "kosa8-ruby/#{VERSION}",
|
|
112
192
|
"Accept" => raw ? "application/octet-stream" : "application/json" }
|
|
193
|
+
headers.update(extra)
|
|
113
194
|
payload = nil
|
|
114
195
|
if !data.nil?
|
|
115
196
|
headers["Content-Type"] = "application/octet-stream"
|
|
@@ -165,7 +246,11 @@ module Kosa8
|
|
|
165
246
|
Kosa8.error_from_response(status, msg_body, method: method, path: path, code: code)
|
|
166
247
|
end
|
|
167
248
|
e.instance_variable_set(:@body, body)
|
|
168
|
-
e.retry_after = retry_after(headers)
|
|
249
|
+
e.retry_after = retry_after(headers)
|
|
250
|
+
if e.retry_after.nil? && body.is_a?(Hash)
|
|
251
|
+
ra = body["retry_after_s"] # e.g. 409 idempotency_in_progress, 503 no_capacity
|
|
252
|
+
e.retry_after = ra.to_f if ra.is_a?(Numeric) && ra.positive?
|
|
253
|
+
end
|
|
169
254
|
e
|
|
170
255
|
end
|
|
171
256
|
|
|
@@ -180,16 +265,25 @@ module Kosa8
|
|
|
180
265
|
status == 502 && exec_path?(path) && message.downcase.include?("timed out")
|
|
181
266
|
end
|
|
182
267
|
|
|
183
|
-
# Retry-After in seconds (
|
|
184
|
-
def self.retry_after(headers)
|
|
268
|
+
# Retry-After in seconds (delta-seconds or an HTTP date), or nil.
|
|
269
|
+
def self.retry_after(headers, now: Time.now)
|
|
185
270
|
return nil unless headers.respond_to?(:each)
|
|
186
271
|
|
|
187
272
|
v = nil
|
|
188
273
|
headers.each { |k, val| v = val if k.to_s.casecmp("retry-after").zero? }
|
|
189
274
|
v = v.first if v.is_a?(Array)
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
275
|
+
return nil if v.nil?
|
|
276
|
+
|
|
277
|
+
s = v.to_s.strip
|
|
278
|
+
begin
|
|
279
|
+
Float(s)
|
|
280
|
+
rescue ArgumentError, TypeError
|
|
281
|
+
begin
|
|
282
|
+
[Time.httpdate(s) - now, 0.0].max
|
|
283
|
+
rescue ArgumentError
|
|
284
|
+
nil
|
|
285
|
+
end
|
|
286
|
+
end
|
|
193
287
|
end
|
|
194
288
|
|
|
195
289
|
# Argument checks shared by create and update; raise ArgumentError before any request.
|
|
@@ -366,7 +460,7 @@ module Kosa8
|
|
|
366
460
|
#
|
|
367
461
|
# Each exec runs in a fresh container: only /workspace persists, so cd,
|
|
368
462
|
# export and packages installed elsewhere are gone by the next one. kosa8
|
|
369
|
-
# Cloud
|
|
463
|
+
# Cloud stops a buffered exec after 90 s, raised as
|
|
370
464
|
# Kosa8::ExecTimeoutError; run long work in the background
|
|
371
465
|
# (nohup sh -c '...' > /workspace/job.log 2>&1 &) and poll it. The request
|
|
372
466
|
# (command and env) is at most 64 KiB (413 too_large).
|
|
@@ -376,8 +470,11 @@ module Kosa8
|
|
|
376
470
|
body["image"] = image unless image.nil?
|
|
377
471
|
body["env"] = env.map { |k, v| "#{k}=#{v}" } if env && !env.empty?
|
|
378
472
|
r = @cloud.request("POST", path("/exec"), body)
|
|
473
|
+
fc, rt = Kosa8.exec_failure(r["exit"])
|
|
474
|
+
fc = r["failure_class"] if r["failure_class"].is_a?(String)
|
|
475
|
+
rt = r["retryable"] if r["retryable"] == true || r["retryable"] == false
|
|
379
476
|
CloudExecResult.new(exit_code: r["exit"], stdout: r["stdout"] || "", stderr: r["stderr"] || "",
|
|
380
|
-
woke_ms: r["woke_ms"])
|
|
477
|
+
woke_ms: r["woke_ms"], failure_class: fc, retryable: rt)
|
|
381
478
|
end
|
|
382
479
|
|
|
383
480
|
# Snapshot it and free its VM; it then costs only snapshot storage.
|
|
@@ -482,21 +579,33 @@ module Kosa8
|
|
|
482
579
|
CloudRewindResult.new(checkpoint: r["checkpoint"] || {}, backup: r["backup"], ms: r["ms"])
|
|
483
580
|
end
|
|
484
581
|
|
|
485
|
-
# +n+ (1 to
|
|
486
|
-
# an Array of CloudSandbox. Each is held to
|
|
487
|
-
# (payment, quotas)
|
|
582
|
+
# +n+ (1 to 1000) live copies of the sandbox as it is now, on its host, as
|
|
583
|
+
# a SandboxBatch (an Array of CloudSandbox with +failed+). Each is held to
|
|
584
|
+
# the rules of a create (payment, quotas).
|
|
585
|
+
#
|
|
586
|
+
# labels: go on every copy, run_id: labels them kosa8.run=<run_id>
|
|
587
|
+
# (heartbeat and drain select by it), lease_s: (60..86400) deletes each
|
|
588
|
+
# lease_s from now unless heartbeats extend it, prefix: names them
|
|
589
|
+
# <prefix>-0001, ... With partial_ok: true copies that could not be made
|
|
590
|
+
# (no room on the host, the running limit) are listed in +failed+ instead
|
|
591
|
+
# of failing the call; false is all or nothing. The API's default is true
|
|
592
|
+
# when a fan-out option is given or n is over 100. A fork that made none
|
|
593
|
+
# raises the first refusal. The call carries an Idempotency-Key
|
|
594
|
+
# (+idempotency_key+, default a new UUID) reused on every retry.
|
|
488
595
|
#
|
|
489
596
|
# Needs the host's data plane; on hosts without it the API answers 501
|
|
490
597
|
# (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
|
|
491
598
|
# every kosa8 Cloud host has it yet.
|
|
492
|
-
def fork(n = 1)
|
|
599
|
+
def fork(n = 1, labels: nil, run_id: nil, lease_s: nil, prefix: nil, partial_ok: nil, idempotency_key: nil)
|
|
493
600
|
unless n.is_a?(Integer) && n.between?(1, Cloud::MAX_FORK)
|
|
494
601
|
raise ArgumentError, "n must be a whole number from 1 to #{Cloud::MAX_FORK}"
|
|
495
602
|
end
|
|
496
603
|
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
604
|
+
body = { "n" => n }.merge(Cloud.fanout_body(@cloud, labels: labels, run_id: run_id, lease_s: lease_s,
|
|
605
|
+
prefix: prefix, partial_ok: partial_ok))
|
|
606
|
+
Cloud.check_idempotency_key(idempotency_key)
|
|
607
|
+
r = @cloud.request("POST", path("/fork"), body, idempotency_key: idempotency_key)
|
|
608
|
+
SandboxBatch.from(@cloud, r, n)
|
|
500
609
|
end
|
|
501
610
|
|
|
502
611
|
# TCP ports listening in its running containers (Hashes: "port",
|
data/lib/kosa8/cloud_features.rb
CHANGED
|
@@ -105,11 +105,49 @@ module Kosa8
|
|
|
105
105
|
# - snapshot: "snap_..." starts it from a durable snapshot; then give
|
|
106
106
|
# only env:, name:, labels:, a lifetime or sleep_after_s:.
|
|
107
107
|
#
|
|
108
|
+
# - lease_s: (60..86400) leases it: deleted lease_s from now unless
|
|
109
|
+
# #heartbeat extends it, so a crashed client leaks nothing (not with
|
|
110
|
+
# ttl_s: or delete_after:). run_id: labels it kosa8.run=<run_id>.
|
|
111
|
+
# - idempotency_key: is sent as the Idempotency-Key header (default a new
|
|
112
|
+
# UUID) and reused on every retry, so a create retried after a timeout
|
|
113
|
+
# or a 5xx makes one sandbox, not two.
|
|
114
|
+
#
|
|
108
115
|
# Bad arguments raise ArgumentError before any request.
|
|
109
116
|
def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil,
|
|
110
117
|
size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil, persistent: nil, docker: nil, cpu: nil,
|
|
111
118
|
name: nil, labels: nil, env: nil, secrets: nil, egress: nil, snapshot: nil, wait: true,
|
|
112
|
-
poll_interval: 1)
|
|
119
|
+
poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil)
|
|
120
|
+
body = create_body(template: template, region: region, sleep_after_s: sleep_after_s, ttl_s: ttl_s,
|
|
121
|
+
delete_after: delete_after, accept_price: accept_price, size: size, cpus: cpus,
|
|
122
|
+
mem_mb: mem_mb, image: image, disk_gb: disk_gb, persistent: persistent, docker: docker,
|
|
123
|
+
cpu: cpu, name: name, labels: labels, env: env, secrets: secrets, egress: egress,
|
|
124
|
+
snapshot: snapshot)
|
|
125
|
+
amb = @cloud.run_defaults || {}
|
|
126
|
+
run_id = amb["run_id"] if run_id.nil?
|
|
127
|
+
if lease_s.nil? && ttl_s.nil? && delete_after.nil?
|
|
128
|
+
lease_s = amb["lease_s"]
|
|
129
|
+
end
|
|
130
|
+
unless lease_s.nil?
|
|
131
|
+
raise ArgumentError, "give lease_s or ttl_s/delete_after, not both" unless ttl_s.nil? && delete_after.nil?
|
|
132
|
+
|
|
133
|
+
body["lease_s"] = Cloud.check_lease(lease_s)
|
|
134
|
+
end
|
|
135
|
+
unless run_id.nil?
|
|
136
|
+
body["labels"] = (body["labels"] || {}).merge(Cloud::RUN_LABEL => Cloud.check_run_id(run_id))
|
|
137
|
+
raise ArgumentError, "at most #{Cloud::MAX_LABELS} labels, kosa8.run included" if body["labels"].size > Cloud::MAX_LABELS
|
|
138
|
+
end
|
|
139
|
+
Cloud.check_idempotency_key(idempotency_key)
|
|
140
|
+
r = @cloud.request("POST", "/v1/sandboxes", body, idempotency_key: idempotency_key)
|
|
141
|
+
box = CloudSandbox.new(@cloud, r["sandbox"])
|
|
142
|
+
box.wait_running(poll_interval: poll_interval) if wait && box.state == "creating"
|
|
143
|
+
box
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# The body of POST /v1/sandboxes for these options (ArgumentError on a bad one).
|
|
147
|
+
def create_body(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil,
|
|
148
|
+
accept_price: nil, size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil,
|
|
149
|
+
persistent: nil, docker: nil, cpu: nil, name: nil, labels: nil, env: nil, secrets: nil,
|
|
150
|
+
egress: nil, snapshot: nil)
|
|
113
151
|
Cloud.check_lifetime(ttl_s, delete_after)
|
|
114
152
|
Cloud.check_sleep_after(sleep_after_s)
|
|
115
153
|
if !accept_price.nil? && !accept_price.is_a?(Numeric)
|
|
@@ -143,9 +181,7 @@ module Kosa8
|
|
|
143
181
|
|
|
144
182
|
body["snapshot"] = snapshot.to_s
|
|
145
183
|
end
|
|
146
|
-
|
|
147
|
-
box.wait_running(poll_interval: poll_interval) if wait && box.state == "creating"
|
|
148
|
-
box
|
|
184
|
+
body
|
|
149
185
|
end
|
|
150
186
|
|
|
151
187
|
# One page of sandboxes; name: finds one by name, labels: keeps those
|
|
@@ -219,7 +255,7 @@ module Kosa8
|
|
|
219
255
|
raise Error, "sandbox #{id} is #{state}, not running#{@info['last_error'] ? ": #{@info['last_error']}" : ''}"
|
|
220
256
|
end
|
|
221
257
|
|
|
222
|
-
# Start a command that keeps running after this returns (no
|
|
258
|
+
# Start a command that keeps running after this returns (no 90 s
|
|
223
259
|
# limit). Returns the background command (a Hash: "id" (bg_...),
|
|
224
260
|
# "state", "pid", "output_path", ...); poll it with #background_exec or
|
|
225
261
|
# #wait_background.
|