daytona 0.231.1 → 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.
@@ -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.231.1'
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'],