daytona 0.232.0 → 0.233.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 639f8438b56a2524ed7f3fd14437964fecacb3d6e0d81a5640551c010a26b3f0
4
- data.tar.gz: 73b0b1a8f7fd58b8170fcae01e494aa2e82c0c0d534cf4dd01d42f139660dea6
3
+ metadata.gz: cca7c7f32049c410b94923b03635ae5b11a655fec10322a304cbcf4de504b35a
4
+ data.tar.gz: 5c83c64990b1491d410ca6b10932bfc4e608fe9d0172be3581d3d9660b095dcc
5
5
  SHA512:
6
- metadata.gz: ba662cc483441d4d8bc87e33bad3d79a1494559161b162704cc7de83ebbc9e1d6f0fee097fdebbaead55eb988a673370461edbc14e8fdc8d77a9bec272a4cab2
7
- data.tar.gz: 583decad8cb93b6bdc825490a9b432d7fde7be0e332eed9d901b6a67d9689f1f25fbcca74bebfa72994bc80d53bb65074493ac7ad004bc77a4ffe83688568676
6
+ metadata.gz: a714624344d6f55d898aa0d9660d37665a4a694bae9f2402d5e7c29f6017912bf7b341077cfdcd6f1aa915191f360abceed9bb77f295b497eec6e3f7e763084c
7
+ data.tar.gz: ae12b125432901005cdf2b08ed97e1ef2ac877e0b3da1d2497138835579b9d779e96b8cbd378df9c96b0c82cafb171c39763e6207bac2f33dc998b6f160c725a
data/README.md CHANGED
@@ -285,3 +285,60 @@ daytona.volume.list.each { |vol| puts vol.name }
285
285
  query = Daytona::ListSandboxesQuery.new(labels: { 'env' => 'dev' })
286
286
  daytona.list(query).each { |sandbox| puts sandbox.id }
287
287
  ```
288
+
289
+ ## Multi-node GPU sandboxes
290
+
291
+ Multi-node access requires an enabled organization quota and compatible fabric capacity.
292
+ Initial profiles use whole 8-GPU nodes: 16 GPUs creates two nodes. Use an image containing
293
+ your framework and RDMA userspace (`libibverbs.so.1` and an mlx5 provider).
294
+
295
+ ```ruby
296
+ params = Daytona::CreateSandboxFromImageParams.new(
297
+ image: 'your-registry/rdma-workload:tag',
298
+ resources: Daytona::Resources.new(gpu: 16, cpu_per_node: [16, 16], memory_per_node: [64, 64], disk_per_node: [100, 100])
299
+ )
300
+ sandbox = daytona.create(params)
301
+ worker = sandbox.nodes[1] # Rank zero is the head.
302
+ worker.process.exec(command: 'hostname')
303
+
304
+ begin
305
+ results = sandbox.nodes.process.exec(
306
+ command: 'hostname', timeout: 120,
307
+ on_stdout: ->(rank, chunk) { print "[rank #{rank}] #{chunk}" }
308
+ )
309
+ puts results.transform_values(&:result)
310
+ rescue Daytona::Sdk::NodeOperationError => error
311
+ puts error.failures # Errors keyed by rank.
312
+ puts error.results # Successful ranks remain available.
313
+ end
314
+ sandbox.nodes.fs.upload_file('hello', '/tmp/shared.txt')
315
+ puts worker.preview_url(8080).url
316
+ ssh = worker.create_ssh_access(60)
317
+ puts ssh.ssh_command
318
+ worker.revoke_ssh_access(ssh.token)
319
+
320
+ sandbox.nodes.add(nodes: [Daytona::NodeResources.new(cpu: 16, memory: 64, disk: 100)])
321
+ sandbox.nodes.release(count: 1) # Releases the highest rank.
322
+ # When a rank fails: sandbox.nodes.replace(rank: rank).
323
+ ```
324
+
325
+ Scalar resources remain supported; arrays specify per-node allocations ordered by rank.
326
+ Node handles expose resources, state, incarnation, failure and fabric health; the sandbox
327
+ exposes `node_count`, `topology_generation` and `degraded`. Call `sandbox.refresh` for current
328
+ metadata. Retained node handles survive refreshes; enumerate the collection again after
329
+ membership changes to find replacements. Existing sandbox services address the head.
330
+
331
+ Membership helpers submit the generation of the displayed nodes and refresh membership after completion.
332
+ After a topology conflict, refresh and inspect the nodes before retrying. The helpers default to `timeout: 600`; zero disables the overall wait limit. A timeout ends the SDK wait without
333
+ canceling the submitted operation. Admission errors propagate directly; the SDK adds no queue.
334
+ Configured transport timeouts still apply.
335
+
336
+ Parallel helpers capture current membership, settle every rank and report rank-specific
337
+ errors. Exec uses a private session on every node even without streaming. Callbacks receive
338
+ `(rank, chunk)` and are serialized. A positive timeout applies per command; zero has no SDK
339
+ execution limit. Session cleanup is attempted after success, error or cancellation, with an
340
+ independent ten-second budget that needs connectivity. Successful commands remain successful
341
+ if cleanup fails; inspect `node.warnings`. RDMA checks warn without blocking execution.
342
+ Uploads are not rolled back on partial failure; IO input is read once before parallel upload.
343
+ Applications must coordinate checkpointing and process restarts after membership changes;
344
+ environment variables in existing processes are not rewritten.
@@ -20,12 +20,35 @@ module Daytona
20
20
  # @return [String, Array<String>, nil] Preferred GPU type for the Sandbox
21
21
  attr_reader :gpu_type
22
22
 
23
+ # @return [Array<Integer>, nil] CPU cores for each node in rank order
24
+ attr_reader :cpu_per_node
25
+
26
+ # @return [Array<Integer>, nil] Memory in GiB for each node in rank order
27
+ attr_reader :memory_per_node
28
+
29
+ # @return [Array<Integer>, nil] Disk space in GiB for each node in rank order
30
+ attr_reader :disk_per_node
31
+
23
32
  # @param cpu [Integer, nil] Number of CPU cores to allocate
24
33
  # @param memory [Integer, nil] Amount of memory in GiB to allocate
25
34
  # @param disk [Integer, nil] Amount of disk space in GiB to allocate
26
35
  # @param gpu [Integer, nil] Number of GPUs to allocate
27
36
  # @param gpu_type [String, Array<String>, nil] Preferred GPU type for the Sandbox
28
- def initialize(cpu: nil, memory: nil, disk: nil, gpu: nil, gpu_type: nil)
37
+ # @param cpu_per_node [Array<Integer>, nil] CPU cores for each node in rank order
38
+ # @param memory_per_node [Array<Integer>, nil] Memory in GiB for each node in rank order
39
+ # @param disk_per_node [Array<Integer>, nil] Disk space in GiB for each node in rank order
40
+ def initialize(cpu: nil, memory: nil, disk: nil, gpu: nil, gpu_type: nil,
41
+ cpu_per_node: nil, memory_per_node: nil, disk_per_node: nil)
42
+ [[cpu, cpu_per_node], [memory, memory_per_node], [disk, disk_per_node]].each do |scalar, values|
43
+ next if values.nil?
44
+ raise Sdk::Error, 'Specify either the scalar or its per-node values' unless scalar.nil?
45
+ next if values.is_a?(Array) && !values.empty? && values.all? { |item| item.is_a?(Integer) && item.positive? }
46
+
47
+ raise Sdk::Error, 'Per-node resources must be non-empty arrays of positive integers'
48
+ end
49
+ @cpu_per_node = cpu_per_node
50
+ @memory_per_node = memory_per_node
51
+ @disk_per_node = disk_per_node
29
52
  @cpu = cpu
30
53
  @memory = memory
31
54
  @disk = disk
@@ -33,7 +56,13 @@ module Daytona
33
56
  @gpu_type = gpu_type
34
57
  end
35
58
 
59
+ # @api private
60
+ def validate_scalar!
61
+ raise Sdk::Error, 'Per-node resources are only supported for sandbox creation' if [cpu_per_node, memory_per_node,
62
+ disk_per_node].any?
63
+ end
64
+
36
65
  # @return [Hash] Hash representation of the resources
37
- def to_h = { cpu:, memory:, disk:, gpu:, gpu_type: }.compact
66
+ def to_h = { cpu:, memory:, disk:, gpu:, gpu_type:, cpu_per_node:, memory_per_node:, disk_per_node: }.compact
38
67
  end
39
68
  end
@@ -170,7 +170,16 @@ module Daytona
170
170
  first_page = false
171
171
  response = fetch_sandbox_page(q, cursor)
172
172
  response.items.each do |sandbox_dto|
173
- yielder << to_sandbox(sandbox_dto: sandbox_dto)
173
+ if sandbox_dto.gpu.to_i > SandboxNodes::GPUS_PER_NODE
174
+ begin
175
+ sandbox = get(sandbox_dto.id)
176
+ rescue Sdk::NotFoundError
177
+ next
178
+ end
179
+ else
180
+ sandbox = to_sandbox(sandbox_dto:)
181
+ end
182
+ yielder << sandbox
174
183
  end
175
184
  cursor = response.next_cursor
176
185
  break if cursor.nil? || (cursor.respond_to?(:empty?) && cursor.empty?)
@@ -333,6 +342,11 @@ module Daytona
333
342
  create_sandbox.cpu = params.resources&.cpu
334
343
  create_sandbox.memory = params.resources&.memory
335
344
  create_sandbox.disk = params.resources&.disk
345
+ if params.resources.is_a?(Resources)
346
+ create_sandbox.cpu_per_node = params.resources.cpu_per_node unless params.resources.cpu_per_node.nil?
347
+ create_sandbox.memory_per_node = params.resources.memory_per_node unless params.resources.memory_per_node.nil?
348
+ create_sandbox.disk_per_node = params.resources.disk_per_node unless params.resources.disk_per_node.nil?
349
+ end
336
350
  create_sandbox.gpu = params.resources&.gpu
337
351
  if params.resources&.gpu_type
338
352
  create_sandbox.gpu_type =
@@ -206,6 +206,15 @@ module Daytona
206
206
  # @return [Daytona::Process]
207
207
  attr_reader :process
208
208
 
209
+ # @return [Daytona::SandboxNodes] Rank-ordered node handles. A gang head includes all ranks. A direct worker lookup includes only that worker.
210
+ attr_reader :nodes
211
+ # @return [Integer] Number of nodes reported by the last refresh
212
+ attr_reader :node_count
213
+ # @return [Integer, nil] Current topology generation
214
+ attr_reader :topology_generation
215
+ # @return [Boolean, nil] Whether the API reports a degraded gang
216
+ attr_reader :degraded
217
+
209
218
  # @return [Daytona::FileSystem]
210
219
  attr_reader :fs
211
220
 
@@ -283,6 +292,8 @@ module Daytona
283
292
  @info_api = info_api
284
293
  @server_api = server_api
285
294
  @system_api = system_api
295
+ @nodes = SandboxNodes.new(self)
296
+ @nodes.send(:update, sandbox_dto)
286
297
 
287
298
  ensure_subscribed
288
299
  end
@@ -794,6 +805,7 @@ module Daytona
794
805
  def resize(resources, timeout = DEFAULT_TIMEOUT)
795
806
  raise Sdk::Error, 'Resources must not be nil' if resources.nil?
796
807
 
808
+ resources.validate_scalar! if resources.is_a?(Resources)
797
809
  if resources.gpu || resources.gpu_type
798
810
  raise Sdk::Error,
799
811
  'Resize does not support changes to gpu or gpu_type — to change GPU, create a new sandbox'
@@ -1130,6 +1142,7 @@ module Daytona
1130
1142
  return if sandbox_dto.nil?
1131
1143
 
1132
1144
  new_state = sandbox_dto.state
1145
+ @node_count ||= 1
1133
1146
 
1134
1147
  # Fields shared by both DaytonaApiClient::Sandbox and DaytonaApiClient::SandboxListItem.
1135
1148
  @id = sandbox_dto.id
@@ -1182,6 +1195,10 @@ module Daytona
1182
1195
  @volumes = sandbox_dto.volumes
1183
1196
  @build_info = sandbox_dto.build_info
1184
1197
  @backup_created_at = sandbox_dto.backup_created_at
1198
+ @node_count = sandbox_dto.node_count unless sandbox_dto.node_count.nil?
1199
+ @topology_generation = sandbox_dto.topology_generation unless sandbox_dto.topology_generation.nil?
1200
+ @degraded = sandbox_dto.degraded unless sandbox_dto.degraded.nil?
1201
+ @nodes&.send(:update, sandbox_dto)
1185
1202
  end
1186
1203
 
1187
1204
  apply_state(new_state)
@@ -1257,6 +1274,8 @@ module Daytona
1257
1274
  mutex = Mutex.new
1258
1275
  state_changed = ConditionVariable.new
1259
1276
  result_state = nil
1277
+ # The error reason that came with result_state; a refresh still in flight may replace error_reason after.
1278
+ result_reason = nil
1260
1279
 
1261
1280
  waiter = {
1262
1281
  matches: lambda do |new_state|
@@ -1267,6 +1286,7 @@ module Daytona
1267
1286
  next if result_state
1268
1287
 
1269
1288
  result_state = new_state
1289
+ result_reason = error_reason
1270
1290
  state_changed.signal
1271
1291
  end
1272
1292
  end
@@ -1302,7 +1322,10 @@ module Daytona
1302
1322
  next if result_state
1303
1323
 
1304
1324
  current = state.to_s
1305
- result_state = current if target_strings.include?(current) || error_strings.include?(current)
1325
+ if target_strings.include?(current) || error_strings.include?(current)
1326
+ result_state = current
1327
+ result_reason = error_reason
1328
+ end
1306
1329
  end
1307
1330
 
1308
1331
  poll_interval = next_wait_for_state_poll_interval(
@@ -1314,7 +1337,7 @@ module Daytona
1314
1337
 
1315
1338
  if result_state && error_strings.include?(result_state)
1316
1339
  raise Sdk::Error,
1317
- "Sandbox #{id} entered error state: #{result_state}, error reason: #{error_reason}"
1340
+ "Sandbox #{id} entered error state: #{result_state}, error reason: #{result_reason}"
1318
1341
  end
1319
1342
  rescue Sdk::TimeoutError => e
1320
1343
  begin
@@ -1455,6 +1478,9 @@ module Daytona
1455
1478
  if event_name == 'sandbox.created'
1456
1479
  process_response(DaytonaApiClient::Sandbox.build_from_hash(raw))
1457
1480
  else
1481
+ # Set before the state: a wait that ends on an error state reports this reason. The event omits the field
1482
+ # when the sandbox has none.
1483
+ @error_reason = raw['errorReason'] if data.key?('sandbox')
1458
1484
  new_state = raw['state'] || data['newState']
1459
1485
  apply_state(new_state) if new_state
1460
1486
  end
@@ -0,0 +1,610 @@
1
+ # Copyright Daytona Platforms Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # frozen_string_literal: true
5
+
6
+ require 'securerandom'
7
+ require 'timeout'
8
+
9
+ module Daytona
10
+ # Resource allocations for one additional whole-GPU node.
11
+ class NodeResources
12
+ attr_reader :cpu
13
+ attr_reader :memory
14
+ attr_reader :disk
15
+
16
+ def initialize(cpu:, memory:, disk:)
17
+ unless [cpu, memory, disk].all? { |v| v.is_a?(Integer) && v.positive? }
18
+ raise Sdk::Error, 'Node CPU, memory and disk must be positive integers'
19
+ end
20
+
21
+ @cpu = cpu
22
+ @memory = memory
23
+ @disk = disk
24
+ end
25
+
26
+ def to_h = { cpu:, memory:, disk: }
27
+ end
28
+
29
+ module Sdk
30
+ # All ranks are allowed to settle; successful results remain available.
31
+ class NodeOperationError < Error
32
+ attr_reader :failures
33
+ attr_reader :results
34
+
35
+ def initialize(failures, results)
36
+ @failures = failures.sort.to_h.freeze
37
+ @results = results.sort.to_h.freeze
38
+ super("Operation failed on node ranks: #{@failures.keys.join(', ')}")
39
+ end
40
+ end
41
+ end
42
+
43
+ # One budget for submission, polling and final refresh. A copied
44
+ # generated client avoids changing timeouts on clients shared by other calls.
45
+ class NodeDeadline
46
+ def initialize(seconds)
47
+ unless seconds.is_a?(Numeric) && seconds.finite? && seconds >= 0
48
+ raise Sdk::Error, 'Timeout must be a finite non-negative number of seconds'
49
+ end
50
+
51
+ @ends_at = now + seconds unless seconds.zero?
52
+ end
53
+
54
+ def remaining
55
+ return 0 unless @ends_at
56
+
57
+ value = @ends_at - now
58
+ raise Sdk::TimeoutError, 'Sandbox node operation exceeded its timeout' unless value.positive?
59
+
60
+ value
61
+ end
62
+
63
+ def call(api, method, *)
64
+ budget = remaining
65
+ client = api.api_client.dup
66
+ client.config = api.api_client.config.dup
67
+ configured = client.config.timeout
68
+ client.config.timeout = if budget.zero?
69
+ configured
70
+ elsif configured && configured.positive?
71
+ [configured, budget].min
72
+ else
73
+ budget
74
+ end
75
+ result = api.class.new(client).public_send(method, *)
76
+ remaining unless result.is_a?(DaytonaApiClient::GangMembershipOperation)
77
+ result
78
+ rescue *Sdk::API_ERROR_CLASSES => e
79
+ remaining
80
+ raise Sdk.wrap_error(e, 'Sandbox node operation failed')
81
+ end
82
+
83
+ def pause(seconds)
84
+ budget = remaining
85
+ sleep(budget.zero? ? seconds : [seconds, budget].min)
86
+ remaining
87
+ end
88
+
89
+ private
90
+
91
+ def now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
92
+ end
93
+ private_constant :NodeDeadline
94
+
95
+ # A stable rank/id handle with its own toolbox route.
96
+ class SandboxNode
97
+ attr_reader :id
98
+ attr_reader :rank
99
+ attr_reader :process
100
+ attr_reader :fs
101
+ attr_reader :process_api
102
+
103
+ def initialize(parent, dto)
104
+ @parent = parent
105
+ @id = dto.id
106
+ @rank = dto.rank
107
+ @warnings = []
108
+ @warning_mutex = Mutex.new
109
+ @rdma_mutex = Mutex.new
110
+ @toolbox_config = parent.send(:build_toolbox_api_config).dup
111
+ client = DaytonaToolboxApiClient::ApiClient.new(@toolbox_config)
112
+ client.default_headers['Authorization'] = "Bearer #{parent.config.api_key || parent.config.jwt_token}"
113
+ client.default_headers['X-Daytona-Source'] = 'sdk-ruby'
114
+ client.default_headers['X-Daytona-SDK-Version'] = Sdk::VERSION
115
+ client.default_headers['X-Daytona-Organization-ID'] = parent.config.organization_id if parent.config.jwt_token
116
+ client.user_agent = "sdk-ruby/#{Sdk::VERSION}"
117
+ @process_api = DaytonaToolboxApiClient::ProcessApi.new(client)
118
+ @process = Process.new(sandbox_id: id, toolbox_api: process_api,
119
+ get_preview_link: method(:preview_url),
120
+ language: (parent.labels || {}).fetch(CODE_TOOLBOX_LANGUAGE_LABEL, 'python'),
121
+ otel_state: parent.send(:otel_state))
122
+ @fs = FileSystem.new(sandbox_id: id, toolbox_api: DaytonaToolboxApiClient::FileSystemApi.new(client),
123
+ otel_state: parent.send(:otel_state))
124
+ update(dto)
125
+ end
126
+
127
+ def update(dto)
128
+ raise Sdk::Error, 'Sandbox node identity changed during refresh' unless dto.id == id && dto.rank == rank
129
+
130
+ update_proxy
131
+ @warning_mutex.synchronize do
132
+ @warnings.delete(@rdma_warning) if @data && incarnation != dto.incarnation
133
+ @data = dto
134
+ end
135
+ end
136
+
137
+ def update_singleton(dto)
138
+ @data.cpu = dto.cpu
139
+ @data.gpu = dto.gpu
140
+ @data.memory = dto.memory
141
+ @data.disk = dto.disk
142
+ @data.state = dto.state if dto.state
143
+ end
144
+
145
+ def update_proxy
146
+ encoded = URI.encode_www_form_component(id).gsub('+', '%20')
147
+ url = URI.parse("#{@parent.toolbox_proxy_url.sub(%r{/+$}, '')}/#{encoded}")
148
+ @toolbox_config.scheme = url.scheme
149
+ @toolbox_config.host = url.host + (url.port == url.default_port ? '' : ":#{url.port}")
150
+ @toolbox_config.base_path = url.path
151
+ end
152
+
153
+ # @return [Integer]
154
+ def cpu = @data.cpu
155
+
156
+ # @return [Integer]
157
+ def gpu = @data.gpu
158
+
159
+ # @return [Integer] Memory in GB
160
+ def memory = @data.memory
161
+
162
+ # @return [Integer] Disk in GB
163
+ def disk = @data.disk
164
+
165
+ # @return [String]
166
+ def state = @data.state
167
+
168
+ # @return [Integer]
169
+ def incarnation = @data.incarnation
170
+
171
+ # @return [DaytonaApiClient::GangNodeFailure, nil]
172
+ def failure = @data.failure
173
+
174
+ # @return [String, nil]
175
+ def fabric_address = @data.fabric_address
176
+
177
+ # @return [Integer, nil]
178
+ def fabric_prefix_length = @data.fabric_prefix_length
179
+
180
+ # @return [Boolean, nil]
181
+ def fabric_healthy = @data.fabric_healthy
182
+
183
+ # @return [String, nil]
184
+ def fabric_unhealthy_since = @data.fabric_unhealthy_since
185
+
186
+ # @return [Array<String>] Advisory preflight and cleanup warnings
187
+ def warnings = @warning_mutex.synchronize { @warnings.dup.freeze }
188
+
189
+ def warn(message)
190
+ @warning_mutex.synchronize { @warnings << message unless @warnings.include?(message) }
191
+ end
192
+
193
+ def cached_rdma_warning
194
+ @rdma_mutex.synchronize do
195
+ current = incarnation
196
+ return @rdma_warning if @rdma_incarnation == current
197
+
198
+ warning = yield
199
+ @warning_mutex.synchronize do
200
+ return '' unless incarnation == current
201
+
202
+ @rdma_warning = warning
203
+ @rdma_incarnation = current
204
+ @warnings << warning unless warning.empty? || @warnings.include?(warning)
205
+ end
206
+ warning
207
+ end
208
+ end
209
+
210
+ private :update, :update_proxy, :update_singleton, :warn, :process_api, :cached_rdma_warning
211
+
212
+ # @return [DaytonaApiClient::PortPreviewUrl] Preview for this member
213
+ def preview_url(port) = api_call(:get_port_preview_url, id, port)
214
+ # @return [DaytonaApiClient::SshAccessDto] SSH access for this member
215
+ def create_ssh_access(expires_in_minutes = nil) = api_call(:create_ssh_access, id, { expires_in_minutes: })
216
+ # @return [DaytonaApiClient::Sandbox] Updated sandbox metadata
217
+ def revoke_ssh_access(token) = api_call(:revoke_ssh_access, id, { token: })
218
+
219
+ private
220
+
221
+ def api_call(method, *)
222
+ @parent.sandbox_api.public_send(method, *)
223
+ rescue *Sdk::API_ERROR_CLASSES => e
224
+ raise Sdk.wrap_error(e, 'Sandbox node request failed')
225
+ end
226
+ end
227
+
228
+ # Rank-ordered nodes, including rank zero. Membership helpers wait by default;
229
+ # timing out ends the SDK wait and does not cancel a submitted operation.
230
+ class SandboxNodes
231
+ include Enumerable
232
+
233
+ GPUS_PER_NODE = 8
234
+ attr_reader :process
235
+ attr_reader :fs
236
+
237
+ def initialize(parent)
238
+ @parent = parent
239
+ @members = [].freeze
240
+ @process = NodeProcess.new(self)
241
+ @fs = NodeFileSystem.new(self)
242
+ end
243
+
244
+ # @yieldparam node [Daytona::SandboxNode]
245
+ # @return [Enumerator, Array<Daytona::SandboxNode>]
246
+ def each(&) = @members.each(&)
247
+ # @param rank [Integer] Index within this Sandbox response; a direct worker lookup has one member
248
+ # @return [Daytona::SandboxNode, nil]
249
+ def [](rank) = @members[rank]
250
+ # @return [Integer] Current membership size
251
+ def size = @members.size
252
+ alias length size
253
+ # @return [Array<Daytona::SandboxNode>] Snapshot of current membership
254
+ def to_a = @members.dup
255
+
256
+ def update(sandbox_dto)
257
+ raw = sandbox_dto.nodes if sandbox_dto.respond_to?(:nodes)
258
+ worker_rank = sandbox_dto.node_rank if sandbox_dto.respond_to?(:head_sandbox_id) && sandbox_dto.head_sandbox_id
259
+ if raw.nil? || raw.empty?
260
+ unless @members.empty?
261
+ @members.each { |node| node.send(:update_proxy) }
262
+ head = @members.first
263
+ if @parent.node_count == 1 && @members.one? && head.rank.zero? && head.id == sandbox_dto.id
264
+ head.send(:update_singleton, sandbox_dto)
265
+ end
266
+ return
267
+ end
268
+ return if worker_rank.nil? && @parent.node_count > 1
269
+
270
+ raw = [DaytonaApiClient::SandboxNode.new(id: @parent.id, rank: worker_rank || 0, incarnation: 1, state: @parent.state,
271
+ cpu: @parent.cpu.to_i, gpu: @parent.gpu.to_i,
272
+ memory: @parent.memory.to_i, disk: @parent.disk.to_i)]
273
+ end
274
+ existing = @members.to_h { |node| [node.id, node] }
275
+ unless raw.all? { |dto| dto.is_a?(DaytonaApiClient::SandboxNode) }
276
+ raise Sdk::Error, 'Invalid sandbox node metadata'
277
+ end
278
+
279
+ ids = raw.map(&:id)
280
+ valid = (!worker_rank || (worker_rank.positive? && raw.one?)) && ids.uniq.size == ids.size &&
281
+ raw.each_with_index.all? do |dto, index|
282
+ rank = index + (worker_rank || 0)
283
+ dto.rank == rank && dto.id.is_a?(String) && !['', '.', '..'].include?(dto.id) &&
284
+ (index != 0 || dto.id == @parent.id) && (!existing[dto.id] || existing[dto.id].rank == rank)
285
+ end
286
+ raise Sdk::Error, 'Invalid sandbox node ordering or identity' unless valid
287
+
288
+ @members = raw.map do |dto|
289
+ existing[dto.id]&.tap { |node| node.send(:update, dto) } || SandboxNode.new(@parent, dto)
290
+ end.freeze
291
+ @membership_generation = if worker_rank.nil? && sandbox_dto.respond_to?(:topology_generation)
292
+ sandbox_dto.topology_generation
293
+ end
294
+ end
295
+
296
+ # @param nodes [Array<Daytona::NodeResources>] Resources in appended rank order
297
+ # @param timeout [Numeric] Overall wait budget in seconds; zero disables it
298
+ # @return [DaytonaApiClient::GangMembershipOperation]
299
+ def add(nodes:, timeout: 600)
300
+ unless nodes.is_a?(Array) && !nodes.empty? && nodes.all? { |node| node.is_a?(NodeResources) }
301
+ raise Sdk::Error, 'Provide a non-empty array of NodeResources'
302
+ end
303
+
304
+ deadline = NodeDeadline.new(timeout)
305
+ body = DaytonaApiClient::AddGangNodes.new(expected_generation: generation, nodes: nodes.map do |node|
306
+ DaytonaApiClient::GangNodeResources.new(node.to_h)
307
+ end)
308
+ submit(:add_sandbox_nodes, body, deadline)
309
+ end
310
+
311
+ # @param count [Integer] Number of highest ranks to release
312
+ # @param timeout [Numeric] Overall wait budget in seconds. Zero disables the limit.
313
+ # @return [DaytonaApiClient::GangMembershipOperation]
314
+ def release(count: 1, timeout: 600)
315
+ raise Sdk::Error, 'Node release count must be a positive integer' unless count.is_a?(Integer) && count.positive?
316
+
317
+ deadline = NodeDeadline.new(timeout)
318
+ body = DaytonaApiClient::RemoveGangNodes.new(count:, expected_generation: generation)
319
+ submit(:remove_sandbox_nodes, body, deadline)
320
+ end
321
+
322
+ # @param rank [Integer] Failed logical rank to replace
323
+ # @param timeout [Numeric] Overall wait budget in seconds. Zero disables the limit.
324
+ # @return [DaytonaApiClient::GangMembershipOperation]
325
+ def replace(rank:, timeout: 600)
326
+ raise Sdk::Error, 'Node rank must be a non-negative integer' unless rank.is_a?(Integer) && rank >= 0
327
+
328
+ deadline = NodeDeadline.new(timeout)
329
+ body = DaytonaApiClient::ReplaceGangNode.new(expected_generation: generation)
330
+ submit(:replace_sandbox_node, body, deadline, rank.to_s)
331
+ end
332
+
333
+ # Capture membership before starting threads. On interruption, allow each
334
+ # task's ensure block to remove its private session before returning.
335
+ def parallel
336
+ members = @members
337
+ raise Sdk::Error, 'Node membership is unavailable. Call refresh and retry.' if members.empty?
338
+
339
+ threads = members.map do |node|
340
+ [node.rank, Thread.new do
341
+ [yield(node), nil]
342
+ rescue StandardError => e
343
+ [nil, e]
344
+ end]
345
+ end
346
+ results = {}
347
+ failures = {}
348
+ threads.each do |rank, thread|
349
+ result, error = thread.value
350
+ error ? failures[rank] = error : results[rank] = result
351
+ end
352
+ raise Sdk::NodeOperationError.new(failures, results) unless failures.empty?
353
+
354
+ results.sort.to_h
355
+ ensure
356
+ threads&.each { |_, thread| thread.kill if thread.alive? }
357
+ threads&.each { |_, thread| thread.join }
358
+ end
359
+
360
+ private :update, :parallel
361
+
362
+ private
363
+
364
+ def generation
365
+ @membership_generation || (raise Sdk::Error, 'Sandbox does not expose a topology generation')
366
+ end
367
+
368
+ def refresh(deadline)
369
+ dto = deadline.call(@parent.sandbox_api, :get_sandbox, @parent.id)
370
+ @parent.send(:process_response, dto)
371
+ end
372
+
373
+ def submit(method, body, deadline, rank = nil)
374
+ args = [@parent.id, rank, body].compact
375
+ op = deadline.call(@parent.sandbox_api, method, *args)
376
+ begin
377
+ until %w[COMPLETED FAILED].include?(op.status)
378
+ deadline.pause(1)
379
+ op = deadline.call(@parent.sandbox_api, :get_gang_membership_operation, @parent.id, op.id)
380
+ end
381
+ raise Sdk::Error, op.error_reason || 'Node membership operation failed' if op.status == 'FAILED'
382
+ rescue Sdk::Error => e
383
+ e.operation_id = op.id
384
+ raise
385
+ end
386
+
387
+ begin
388
+ refresh(deadline)
389
+ rescue StandardError => e
390
+ Sdk.logger.debug("Membership operation #{op.id} completed; cached nodes could not be refreshed: #{e.message}")
391
+ end
392
+ op
393
+ end
394
+ end
395
+
396
+ class NodeProcess
397
+ RDMA_CHECK = 'sh -lc \'ldconfig -p 2>/dev/null | grep -q libibverbs.so.1 && find /usr/lib /lib -name "libmlx5-rdmav*.so" -print -quit 2>/dev/null | grep -q .\''
398
+ RDMA_WARNING = 'WARNING: rdma-core userspace (libibverbs.so.1 and an mlx5 provider) is missing; NCCL may fall back to sockets.'
399
+
400
+ def initialize(nodes) = @nodes = nodes
401
+
402
+ # Callbacks receive (rank, chunk). A positive timeout bounds each command;
403
+ # private session cleanup has its own ten-second budget after expiration.
404
+ # @param command [String] Shell command to execute on each current member
405
+ # @param timeout [Numeric] Execution limit in seconds per rank. The default of zero disables the limit.
406
+ # @param on_stdout [Proc, nil] Callback receiving (rank, chunk)
407
+ # @param on_stderr [Proc, nil] Callback receiving (rank, chunk)
408
+ # @return [Hash<Integer, Daytona::ExecuteResponse>] Results keyed by rank
409
+ # @raise [Daytona::Sdk::NodeOperationError] After all ranks finish, failures contains errors by rank and results contains successful responses.
410
+ def exec(command:, timeout: 0, on_stdout: nil, on_stderr: nil)
411
+ NodeDeadline.new(timeout)
412
+ lock = Mutex.new
413
+ active = true
414
+ stdout = ->(rank, chunk) { lock.synchronize { on_stdout&.call(rank, chunk) if active } }
415
+ stderr = ->(rank, chunk) { lock.synchronize { on_stderr&.call(rank, chunk) if active } }
416
+ check_rdma = @nodes.size > 1
417
+ @nodes.send(:parallel) do |node|
418
+ NodeExecution.new(
419
+ node,
420
+ command,
421
+ timeout:,
422
+ callbacks: { stdout: on_stdout && stdout, stderr: on_stderr && stderr },
423
+ check_rdma:
424
+ ).run
425
+ end
426
+ ensure
427
+ lock&.synchronize { active = false }
428
+ end
429
+ end
430
+
431
+ # One command's private session; state is never shared across concurrent calls.
432
+ class NodeExecution
433
+ RDMA_CHECK = NodeProcess::RDMA_CHECK
434
+ RDMA_WARNING = NodeProcess::RDMA_WARNING
435
+
436
+ def initialize(node, command, timeout:, callbacks:, check_rdma:)
437
+ @node = node
438
+ @api = node.send(:process_api)
439
+ @command = command
440
+ @timeout = timeout
441
+ @callbacks = callbacks
442
+ @check_rdma = check_rdma
443
+ @session = "daytona-nodes-exec-#{SecureRandom.uuid}"
444
+ end
445
+
446
+ def run
447
+ @warning = @check_rdma ? @node.send(:cached_rdma_warning) { rdma_warning } : ''
448
+ emit_warning
449
+ begin
450
+ NodeDeadline.new(10).call(@api, :create_session,
451
+ DaytonaToolboxApiClient::CreateSessionRequest.new(session_id: @session))
452
+ execute_command
453
+ rescue StandardError => e
454
+ failure = e
455
+ raise
456
+ ensure
457
+ cleanup(failure)
458
+ end
459
+ end
460
+
461
+ private
462
+
463
+ def rdma_warning
464
+ request = DaytonaToolboxApiClient::ExecuteRequest.new(command: RDMA_CHECK, timeout: 5)
465
+ response = NodeDeadline.new(5).call(@api, :execute_command, request)
466
+ response.exit_code.zero? ? '' : RDMA_WARNING
467
+ rescue StandardError
468
+ 'WARNING: Could not check RDMA userspace; continuing without verification.'
469
+ end
470
+
471
+ def emit_warning
472
+ return if @warning.empty?
473
+
474
+ @callbacks[:stderr]&.call(@node.rank, "#{@warning}\n")
475
+ end
476
+
477
+ def execute_command
478
+ deadline = NodeDeadline.new(@timeout)
479
+ req = DaytonaToolboxApiClient::SessionExecuteRequest.new(command: @command, run_async: true)
480
+ command_id = deadline.call(@api, :session_execute_command, @session, req).cmd_id
481
+ raise Sdk::Error, 'Session execution returned no command ID' if command_id.nil? || command_id.empty?
482
+
483
+ stream(command_id, deadline) if @callbacks.values.any?
484
+ completed = wait_for_command(command_id, deadline)
485
+ logs = deadline.call(@api, :get_session_command_logs, @session, command_id)
486
+ result(completed, logs)
487
+ end
488
+
489
+ def stream(command_id, deadline)
490
+ NodeLogStream.new(@node, @session, command_id, deadline, @callbacks).run
491
+ end
492
+
493
+ def wait_for_command(command_id, deadline)
494
+ loop do
495
+ completed = deadline.call(@api, :get_session_command, @session, command_id)
496
+ return completed unless completed.exit_code.nil?
497
+
498
+ deadline.pause(0.1)
499
+ end
500
+ end
501
+
502
+ def result(completed, logs)
503
+ prefix = @warning.empty? ? '' : "#{@warning}\n"
504
+ ExecuteResponse.new(exit_code: completed.exit_code,
505
+ result: prefix + (logs.output || "#{logs.stdout}#{logs.stderr}"),
506
+ artifacts: ExecutionArtifacts.new(prefix + (logs.stdout || '')))
507
+ end
508
+
509
+ def cleanup(failure)
510
+ NodeDeadline.new(10).call(@api, :delete_session, @session)
511
+ rescue StandardError => e
512
+ prefix = failure ? 'Session cleanup also failed' : "Session #{@session} cleanup failed"
513
+ @node.send(:warn, "#{prefix}: #{e.message}")
514
+ end
515
+ end
516
+ private_constant :NodeExecution
517
+
518
+ # Owns the stream socket so timeouts cannot leave an idle reader behind.
519
+ class NodeLogStream
520
+ def initialize(node, session, command, deadline, callbacks)
521
+ @node = node
522
+ @deadline = deadline
523
+ @callbacks = callbacks
524
+ client = node.send(:process_api).api_client
525
+ @headers = client.default_headers.dup
526
+ @url = URI.parse(client.config.base_url)
527
+ @url.scheme = @url.scheme == 'https' ? 'wss' : 'ws'
528
+ @url.path = "#{@url.path.sub(%r{/+$}, '')}/process/session/#{session}/command/#{command}/logs"
529
+ @url.query = 'follow=true'
530
+ @completion = Queue.new
531
+ @lock = Mutex.new
532
+ @active = true
533
+ end
534
+
535
+ def run
536
+ timeout = @deadline.remaining
537
+ if timeout.zero?
538
+ connect_and_wait
539
+ else
540
+ Timeout.timeout(timeout, Sdk::TimeoutError, 'Session log stream exceeded its timeout') { connect_and_wait }
541
+ end
542
+ ensure
543
+ @lock.synchronize { @active = false }
544
+ close_socket
545
+ end
546
+
547
+ private
548
+
549
+ def connect_and_wait
550
+ Common::WebSocketDialer.connect(@url.to_s, headers: @headers) do |socket|
551
+ @socket = socket
552
+ socket.on(:message) { |message| on_message(message) }
553
+ socket.on(:close) { @completion.push(nil) }
554
+ socket.on(:error) { |error| @completion.push(Sdk::Error.new("WebSocket error: #{error.message}")) }
555
+ end
556
+ failure = @completion.pop
557
+ raise failure if failure
558
+ end
559
+
560
+ def on_message(message)
561
+ return @completion.push(nil) if message.type == :close
562
+
563
+ stdout, stderr = Util.demux(message.data.to_s)
564
+ @lock.synchronize do
565
+ return unless @active
566
+
567
+ @deadline.remaining
568
+ @callbacks[:stdout]&.call(@node.rank, stdout) unless stdout.empty?
569
+ @callbacks[:stderr]&.call(@node.rank, stderr) unless stderr.empty?
570
+ end
571
+ rescue StandardError => e
572
+ @completion.push(e)
573
+ end
574
+
575
+ def close_socket
576
+ @socket&.close
577
+ rescue StandardError => e
578
+ @node.send(:warn, "Log stream cleanup failed: #{e.message}")
579
+ end
580
+ end
581
+ private_constant :NodeLogStream
582
+
583
+ class NodeFileSystem
584
+ def initialize(nodes) = @nodes = nodes
585
+
586
+ # Copies an IO once to a temporary file so every rank receives the same bytes.
587
+ # @param source [String, IO] File contents, a local file path, or a readable IO.
588
+ # @param remote_path [String] Destination path on each node.
589
+ # @return [void]
590
+ # @raise [Daytona::Sdk::NodeOperationError] After all uploads finish, failures contains errors by rank
591
+ # and results contains the ranks whose uploads succeeded.
592
+ def upload_file(source, remote_path)
593
+ upload = lambda { |path_or_content|
594
+ @nodes.send(:parallel) do |node|
595
+ node.fs.upload_file(path_or_content, remote_path)
596
+ end
597
+ }
598
+ if source.respond_to?(:read)
599
+ Tempfile.create('daytona-node-upload', binmode: true) do |file|
600
+ IO.copy_stream(source, file)
601
+ file.flush
602
+ upload.call(file.path)
603
+ end
604
+ else
605
+ upload.call(source)
606
+ end
607
+ nil
608
+ end
609
+ end
610
+ end
@@ -31,6 +31,9 @@ module Daytona
31
31
  # puts e.status_code, e.code, e.source
32
32
  # end
33
33
  class Error < StandardError
34
+ # Accepted membership operation to inspect when a wait fails.
35
+ attr_accessor :operation_id
36
+
34
37
  def initialize(message = nil, status_code: nil, code: nil, source: nil, headers: nil)
35
38
  super(message)
36
39
  @status_code = status_code
@@ -5,6 +5,6 @@
5
5
 
6
6
  module Daytona
7
7
  module Sdk
8
- VERSION = '0.232.0'
8
+ VERSION = '0.233.0'
9
9
  end
10
10
  end
data/lib/daytona/sdk.rb CHANGED
@@ -51,6 +51,7 @@ require_relative 'volume_service'
51
51
  require_relative 'warm_pool'
52
52
  require_relative 'warm_pool_service'
53
53
  require_relative 'process'
54
+ require_relative 'sandbox_nodes'
54
55
 
55
56
  module Daytona
56
57
  module Sdk
@@ -90,6 +90,7 @@ module Daytona
90
90
  # print chunk
91
91
  # end
92
92
  def create(params, on_logs: nil) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
93
+ params.resources.validate_scalar! if params.resources.is_a?(Resources)
93
94
  create_snapshot_req = DaytonaApiClient::CreateSnapshot.new(name: params.name)
94
95
 
95
96
  if params.image.is_a?(String)
@@ -16,6 +16,11 @@ CLASSES_TO_DOCUMENT = [
16
16
  ['config.rb', 'config.mdx', 'Daytona::Config'],
17
17
  ['daytona.rb', 'daytona.mdx', 'Daytona::Daytona'],
18
18
  ['sandbox.rb', 'sandbox.mdx', 'Daytona::Sandbox'],
19
+ ['sandbox_nodes.rb', 'sandbox-node.mdx', 'Daytona::SandboxNode'],
20
+ ['sandbox_nodes.rb', 'sandbox-nodes.mdx', 'Daytona::SandboxNodes'],
21
+ ['sandbox_nodes.rb', 'node-process.mdx', 'Daytona::NodeProcess'],
22
+ ['sandbox_nodes.rb', 'node-file-system.mdx', 'Daytona::NodeFileSystem'],
23
+ ['sandbox_nodes.rb', 'node-resources.mdx', 'Daytona::NodeResources'],
19
24
  ['file_system.rb', 'file-system.mdx', 'Daytona::FileSystem'],
20
25
  ['git.rb', 'git.mdx', 'Daytona::Git'],
21
26
  ['process.rb', 'process.mdx', 'Daytona::Process'],
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: daytona
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.232.0
4
+ version: 0.233.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daytona Platforms Inc.
@@ -91,42 +91,42 @@ dependencies:
91
91
  requirements:
92
92
  - - '='
93
93
  - !ruby/object:Gem::Version
94
- version: 0.232.0
94
+ version: 0.233.0
95
95
  type: :runtime
96
96
  prerelease: false
97
97
  version_requirements: !ruby/object:Gem::Requirement
98
98
  requirements:
99
99
  - - '='
100
100
  - !ruby/object:Gem::Version
101
- version: 0.232.0
101
+ version: 0.233.0
102
102
  - !ruby/object:Gem::Dependency
103
103
  name: daytona_api_client
104
104
  requirement: !ruby/object:Gem::Requirement
105
105
  requirements:
106
106
  - - '='
107
107
  - !ruby/object:Gem::Version
108
- version: 0.232.0
108
+ version: 0.233.0
109
109
  type: :runtime
110
110
  prerelease: false
111
111
  version_requirements: !ruby/object:Gem::Requirement
112
112
  requirements:
113
113
  - - '='
114
114
  - !ruby/object:Gem::Version
115
- version: 0.232.0
115
+ version: 0.233.0
116
116
  - !ruby/object:Gem::Dependency
117
117
  name: daytona_toolbox_api_client
118
118
  requirement: !ruby/object:Gem::Requirement
119
119
  requirements:
120
120
  - - '='
121
121
  - !ruby/object:Gem::Version
122
- version: 0.232.0
122
+ version: 0.233.0
123
123
  type: :runtime
124
124
  prerelease: false
125
125
  version_requirements: !ruby/object:Gem::Requirement
126
126
  requirements:
127
127
  - - '='
128
128
  - !ruby/object:Gem::Version
129
- version: 0.232.0
129
+ version: 0.233.0
130
130
  - !ruby/object:Gem::Dependency
131
131
  name: dotenv
132
132
  requirement: !ruby/object:Gem::Requirement
@@ -233,6 +233,7 @@ files:
233
233
  - lib/daytona/otel.rb
234
234
  - lib/daytona/process.rb
235
235
  - lib/daytona/sandbox.rb
236
+ - lib/daytona/sandbox_nodes.rb
236
237
  - lib/daytona/sdk.rb
237
238
  - lib/daytona/sdk/deprecated.rb
238
239
  - lib/daytona/sdk/errors.rb