daytona 0.232.0 → 0.234.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,615 @@
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
+ # The parent applies the response's state only after this update, so take it from the response. One
271
+ # without a state (older servers) cannot describe the node; a later refresh will.
272
+ node_state = sandbox_dto.state if sandbox_dto.respond_to?(:state)
273
+ return if node_state.nil?
274
+
275
+ raw = [DaytonaApiClient::SandboxNode.new(id: @parent.id, rank: worker_rank || 0, incarnation: 1, state: node_state,
276
+ cpu: @parent.cpu.to_i, gpu: @parent.gpu.to_i,
277
+ memory: @parent.memory.to_i, disk: @parent.disk.to_i)]
278
+ end
279
+ existing = @members.to_h { |node| [node.id, node] }
280
+ unless raw.all? { |dto| dto.is_a?(DaytonaApiClient::SandboxNode) }
281
+ raise Sdk::Error, 'Invalid sandbox node metadata'
282
+ end
283
+
284
+ ids = raw.map(&:id)
285
+ valid = (!worker_rank || (worker_rank.positive? && raw.one?)) && ids.uniq.size == ids.size &&
286
+ raw.each_with_index.all? do |dto, index|
287
+ rank = index + (worker_rank || 0)
288
+ dto.rank == rank && dto.id.is_a?(String) && !['', '.', '..'].include?(dto.id) &&
289
+ (index != 0 || dto.id == @parent.id) && (!existing[dto.id] || existing[dto.id].rank == rank)
290
+ end
291
+ raise Sdk::Error, 'Invalid sandbox node ordering or identity' unless valid
292
+
293
+ @members = raw.map do |dto|
294
+ existing[dto.id]&.tap { |node| node.send(:update, dto) } || SandboxNode.new(@parent, dto)
295
+ end.freeze
296
+ @membership_generation = if worker_rank.nil? && sandbox_dto.respond_to?(:topology_generation)
297
+ sandbox_dto.topology_generation
298
+ end
299
+ end
300
+
301
+ # @param nodes [Array<Daytona::NodeResources>] Resources in appended rank order
302
+ # @param timeout [Numeric] Overall wait budget in seconds; zero disables it
303
+ # @return [DaytonaApiClient::GangMembershipOperation]
304
+ def add(nodes:, timeout: 600)
305
+ unless nodes.is_a?(Array) && !nodes.empty? && nodes.all? { |node| node.is_a?(NodeResources) }
306
+ raise Sdk::Error, 'Provide a non-empty array of NodeResources'
307
+ end
308
+
309
+ deadline = NodeDeadline.new(timeout)
310
+ body = DaytonaApiClient::AddGangNodes.new(expected_generation: generation, nodes: nodes.map do |node|
311
+ DaytonaApiClient::GangNodeResources.new(node.to_h)
312
+ end)
313
+ submit(:add_sandbox_nodes, body, deadline)
314
+ end
315
+
316
+ # @param count [Integer] Number of highest ranks to release
317
+ # @param timeout [Numeric] Overall wait budget in seconds. Zero disables the limit.
318
+ # @return [DaytonaApiClient::GangMembershipOperation]
319
+ def release(count: 1, timeout: 600)
320
+ raise Sdk::Error, 'Node release count must be a positive integer' unless count.is_a?(Integer) && count.positive?
321
+
322
+ deadline = NodeDeadline.new(timeout)
323
+ body = DaytonaApiClient::RemoveGangNodes.new(count:, expected_generation: generation)
324
+ submit(:remove_sandbox_nodes, body, deadline)
325
+ end
326
+
327
+ # @param rank [Integer] Failed logical rank to replace
328
+ # @param timeout [Numeric] Overall wait budget in seconds. Zero disables the limit.
329
+ # @return [DaytonaApiClient::GangMembershipOperation]
330
+ def replace(rank:, timeout: 600)
331
+ raise Sdk::Error, 'Node rank must be a non-negative integer' unless rank.is_a?(Integer) && rank >= 0
332
+
333
+ deadline = NodeDeadline.new(timeout)
334
+ body = DaytonaApiClient::ReplaceGangNode.new(expected_generation: generation)
335
+ submit(:replace_sandbox_node, body, deadline, rank.to_s)
336
+ end
337
+
338
+ # Capture membership before starting threads. On interruption, allow each
339
+ # task's ensure block to remove its private session before returning.
340
+ def parallel
341
+ members = @members
342
+ raise Sdk::Error, 'Node membership is unavailable. Call refresh and retry.' if members.empty?
343
+
344
+ threads = members.map do |node|
345
+ [node.rank, Thread.new do
346
+ [yield(node), nil]
347
+ rescue StandardError => e
348
+ [nil, e]
349
+ end]
350
+ end
351
+ results = {}
352
+ failures = {}
353
+ threads.each do |rank, thread|
354
+ result, error = thread.value
355
+ error ? failures[rank] = error : results[rank] = result
356
+ end
357
+ raise Sdk::NodeOperationError.new(failures, results) unless failures.empty?
358
+
359
+ results.sort.to_h
360
+ ensure
361
+ threads&.each { |_, thread| thread.kill if thread.alive? }
362
+ threads&.each { |_, thread| thread.join }
363
+ end
364
+
365
+ private :update, :parallel
366
+
367
+ private
368
+
369
+ def generation
370
+ @membership_generation || (raise Sdk::Error, 'Sandbox does not expose a topology generation')
371
+ end
372
+
373
+ def refresh(deadline)
374
+ dto = deadline.call(@parent.sandbox_api, :get_sandbox, @parent.id)
375
+ @parent.send(:process_response, dto)
376
+ end
377
+
378
+ def submit(method, body, deadline, rank = nil)
379
+ args = [@parent.id, rank, body].compact
380
+ op = deadline.call(@parent.sandbox_api, method, *args)
381
+ begin
382
+ until %w[COMPLETED FAILED].include?(op.status)
383
+ deadline.pause(1)
384
+ op = deadline.call(@parent.sandbox_api, :get_gang_membership_operation, @parent.id, op.id)
385
+ end
386
+ raise Sdk::Error, op.error_reason || 'Node membership operation failed' if op.status == 'FAILED'
387
+ rescue Sdk::Error => e
388
+ e.operation_id = op.id
389
+ raise
390
+ end
391
+
392
+ begin
393
+ refresh(deadline)
394
+ rescue StandardError => e
395
+ Sdk.logger.debug("Membership operation #{op.id} completed; cached nodes could not be refreshed: #{e.message}")
396
+ end
397
+ op
398
+ end
399
+ end
400
+
401
+ class NodeProcess
402
+ 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 .\''
403
+ RDMA_WARNING = 'WARNING: rdma-core userspace (libibverbs.so.1 and an mlx5 provider) is missing; NCCL may fall back to sockets.'
404
+
405
+ def initialize(nodes) = @nodes = nodes
406
+
407
+ # Callbacks receive (rank, chunk). A positive timeout bounds each command;
408
+ # private session cleanup has its own ten-second budget after expiration.
409
+ # @param command [String] Shell command to execute on each current member
410
+ # @param timeout [Numeric] Execution limit in seconds per rank. The default of zero disables the limit.
411
+ # @param on_stdout [Proc, nil] Callback receiving (rank, chunk)
412
+ # @param on_stderr [Proc, nil] Callback receiving (rank, chunk)
413
+ # @return [Hash<Integer, Daytona::ExecuteResponse>] Results keyed by rank
414
+ # @raise [Daytona::Sdk::NodeOperationError] After all ranks finish, failures contains errors by rank and results contains successful responses.
415
+ def exec(command:, timeout: 0, on_stdout: nil, on_stderr: nil)
416
+ NodeDeadline.new(timeout)
417
+ lock = Mutex.new
418
+ active = true
419
+ stdout = ->(rank, chunk) { lock.synchronize { on_stdout&.call(rank, chunk) if active } }
420
+ stderr = ->(rank, chunk) { lock.synchronize { on_stderr&.call(rank, chunk) if active } }
421
+ check_rdma = @nodes.size > 1
422
+ @nodes.send(:parallel) do |node|
423
+ NodeExecution.new(
424
+ node,
425
+ command,
426
+ timeout:,
427
+ callbacks: { stdout: on_stdout && stdout, stderr: on_stderr && stderr },
428
+ check_rdma:
429
+ ).run
430
+ end
431
+ ensure
432
+ lock&.synchronize { active = false }
433
+ end
434
+ end
435
+
436
+ # One command's private session; state is never shared across concurrent calls.
437
+ class NodeExecution
438
+ RDMA_CHECK = NodeProcess::RDMA_CHECK
439
+ RDMA_WARNING = NodeProcess::RDMA_WARNING
440
+
441
+ def initialize(node, command, timeout:, callbacks:, check_rdma:)
442
+ @node = node
443
+ @api = node.send(:process_api)
444
+ @command = command
445
+ @timeout = timeout
446
+ @callbacks = callbacks
447
+ @check_rdma = check_rdma
448
+ @session = "daytona-nodes-exec-#{SecureRandom.uuid}"
449
+ end
450
+
451
+ def run
452
+ @warning = @check_rdma ? @node.send(:cached_rdma_warning) { rdma_warning } : ''
453
+ emit_warning
454
+ begin
455
+ NodeDeadline.new(10).call(@api, :create_session,
456
+ DaytonaToolboxApiClient::CreateSessionRequest.new(session_id: @session))
457
+ execute_command
458
+ rescue StandardError => e
459
+ failure = e
460
+ raise
461
+ ensure
462
+ cleanup(failure)
463
+ end
464
+ end
465
+
466
+ private
467
+
468
+ def rdma_warning
469
+ request = DaytonaToolboxApiClient::ExecuteRequest.new(command: RDMA_CHECK, timeout: 5)
470
+ response = NodeDeadline.new(5).call(@api, :execute_command, request)
471
+ response.exit_code.zero? ? '' : RDMA_WARNING
472
+ rescue StandardError
473
+ 'WARNING: Could not check RDMA userspace; continuing without verification.'
474
+ end
475
+
476
+ def emit_warning
477
+ return if @warning.empty?
478
+
479
+ @callbacks[:stderr]&.call(@node.rank, "#{@warning}\n")
480
+ end
481
+
482
+ def execute_command
483
+ deadline = NodeDeadline.new(@timeout)
484
+ req = DaytonaToolboxApiClient::SessionExecuteRequest.new(command: @command, run_async: true)
485
+ command_id = deadline.call(@api, :session_execute_command, @session, req).cmd_id
486
+ raise Sdk::Error, 'Session execution returned no command ID' if command_id.nil? || command_id.empty?
487
+
488
+ stream(command_id, deadline) if @callbacks.values.any?
489
+ completed = wait_for_command(command_id, deadline)
490
+ logs = deadline.call(@api, :get_session_command_logs, @session, command_id)
491
+ result(completed, logs)
492
+ end
493
+
494
+ def stream(command_id, deadline)
495
+ NodeLogStream.new(@node, @session, command_id, deadline, @callbacks).run
496
+ end
497
+
498
+ def wait_for_command(command_id, deadline)
499
+ loop do
500
+ completed = deadline.call(@api, :get_session_command, @session, command_id)
501
+ return completed unless completed.exit_code.nil?
502
+
503
+ deadline.pause(0.1)
504
+ end
505
+ end
506
+
507
+ def result(completed, logs)
508
+ prefix = @warning.empty? ? '' : "#{@warning}\n"
509
+ ExecuteResponse.new(exit_code: completed.exit_code,
510
+ result: prefix + (logs.output || "#{logs.stdout}#{logs.stderr}"),
511
+ artifacts: ExecutionArtifacts.new(prefix + (logs.stdout || '')))
512
+ end
513
+
514
+ def cleanup(failure)
515
+ NodeDeadline.new(10).call(@api, :delete_session, @session)
516
+ rescue StandardError => e
517
+ prefix = failure ? 'Session cleanup also failed' : "Session #{@session} cleanup failed"
518
+ @node.send(:warn, "#{prefix}: #{e.message}")
519
+ end
520
+ end
521
+ private_constant :NodeExecution
522
+
523
+ # Owns the stream socket so timeouts cannot leave an idle reader behind.
524
+ class NodeLogStream
525
+ def initialize(node, session, command, deadline, callbacks)
526
+ @node = node
527
+ @deadline = deadline
528
+ @callbacks = callbacks
529
+ client = node.send(:process_api).api_client
530
+ @headers = client.default_headers.dup
531
+ @url = URI.parse(client.config.base_url)
532
+ @url.scheme = @url.scheme == 'https' ? 'wss' : 'ws'
533
+ @url.path = "#{@url.path.sub(%r{/+$}, '')}/process/session/#{session}/command/#{command}/logs"
534
+ @url.query = 'follow=true'
535
+ @completion = Queue.new
536
+ @lock = Mutex.new
537
+ @active = true
538
+ end
539
+
540
+ def run
541
+ timeout = @deadline.remaining
542
+ if timeout.zero?
543
+ connect_and_wait
544
+ else
545
+ Timeout.timeout(timeout, Sdk::TimeoutError, 'Session log stream exceeded its timeout') { connect_and_wait }
546
+ end
547
+ ensure
548
+ @lock.synchronize { @active = false }
549
+ close_socket
550
+ end
551
+
552
+ private
553
+
554
+ def connect_and_wait
555
+ Common::WebSocketDialer.connect(@url.to_s, headers: @headers) do |socket|
556
+ @socket = socket
557
+ socket.on(:message) { |message| on_message(message) }
558
+ socket.on(:close) { @completion.push(nil) }
559
+ socket.on(:error) { |error| @completion.push(Sdk::Error.new("WebSocket error: #{error.message}")) }
560
+ end
561
+ failure = @completion.pop
562
+ raise failure if failure
563
+ end
564
+
565
+ def on_message(message)
566
+ return @completion.push(nil) if message.type == :close
567
+
568
+ stdout, stderr = Util.demux(message.data.to_s)
569
+ @lock.synchronize do
570
+ return unless @active
571
+
572
+ @deadline.remaining
573
+ @callbacks[:stdout]&.call(@node.rank, stdout) unless stdout.empty?
574
+ @callbacks[:stderr]&.call(@node.rank, stderr) unless stderr.empty?
575
+ end
576
+ rescue StandardError => e
577
+ @completion.push(e)
578
+ end
579
+
580
+ def close_socket
581
+ @socket&.close
582
+ rescue StandardError => e
583
+ @node.send(:warn, "Log stream cleanup failed: #{e.message}")
584
+ end
585
+ end
586
+ private_constant :NodeLogStream
587
+
588
+ class NodeFileSystem
589
+ def initialize(nodes) = @nodes = nodes
590
+
591
+ # Copies an IO once to a temporary file so every rank receives the same bytes.
592
+ # @param source [String, IO] File contents, a local file path, or a readable IO.
593
+ # @param remote_path [String] Destination path on each node.
594
+ # @return [void]
595
+ # @raise [Daytona::Sdk::NodeOperationError] After all uploads finish, failures contains errors by rank
596
+ # and results contains the ranks whose uploads succeeded.
597
+ def upload_file(source, remote_path)
598
+ upload = lambda { |path_or_content|
599
+ @nodes.send(:parallel) do |node|
600
+ node.fs.upload_file(path_or_content, remote_path)
601
+ end
602
+ }
603
+ if source.respond_to?(:read)
604
+ Tempfile.create('daytona-node-upload', binmode: true) do |file|
605
+ IO.copy_stream(source, file)
606
+ file.flush
607
+ upload.call(file.path)
608
+ end
609
+ else
610
+ upload.call(source)
611
+ end
612
+ nil
613
+ end
614
+ end
615
+ 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.234.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'],