Class: Aspera::Plugins::Node::Emulator

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/plugins/node/emulator.rb

Overview

Node API transfers executed by transferd. Only transfers started through the emulator are known (kept in memory).

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(retention_sec:, docroot: nil, transfer_client: nil) ⇒ Emulator

Create an emulator, start a transferd daemon if no client is given

Parameters:

  • docroot (String, nil) (defaults to: nil) —

    folder of the node files, default: current folder

  • transfer_client (Transferd::Api::TransferService::Stub, nil) (defaults to: nil) —

    gRPC client (wrapped by the agent transferd), default: start a transferd daemon

  • retention_sec (Integer) —

    time a transfer is kept after it ended (CLI default in schema)



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/aspera/plugins/node/emulator.rb', line 296

def initialize(retention_sec:, docroot: nil, transfer_client: nil)
  Aspera.assert(retention_sec.is_a?(Integer) && retention_sec.positive?) { "retention_sec must be a positive integer: #{retention_sec.inspect}" }
  # paths of browse and local paths of transfers are relative to it
  @docroot = File.realpath(docroot || Dir.pwd)
  # the daemon is stopped at exit by the agent
  agent_class = self.class.send(:transferd_agent_class, refresh: true)
  @transfer_client =
    if transfer_client.nil?
      Aspera::Agent::Factory.instance.create(:transferd, {}).client
    else
      agent_class.wrap_client(transfer_client)
    end
  @retention_sec = retention_sec
  # transfer id → store entry: `start_spec` (secrets hidden), last `status`, last `info`, `sessions` by id, `files` by id, current `rates` by session id, `error`,
  # `ended` (monotonic time of the end), accessed with `store`
  @transfers = {}
  # WEBrick serves each request in a thread, monitoring runs in threads
  @mutex = Mutex.new
  # identifiers of the simulated node, in node information and in sessions
  @node_id = SecureRandom.uuid
  @cluster_id = SecureRandom.uuid
  # transferd runs as the user of the emulator
  @transfer_user = Etc.getpwuid(::Process.euid)&.name || Etc.getlogin.to_s
end

Class Method Details

.file_to_node(file) ⇒ Hash

Convert a transferd file to a Node API file

Parameters:

Returns:

  • (Hash) —

    Node API file (fileMetadata)



219
220
221
222
223
224
225
226
# File 'lib/aspera/plugins/node/emulator.rb', line 219

def file_to_node(file)
  result = message_to_hash(file, FILE_OVERRIDES).slice(*FILE_FIELDS)
  status = file.status.downcase
  result['status'] = FILE_STATUS.fetch(status, status)
  terminal = !result['status'].eql?('running') && result['start_time_usec'].positive?
  result['end_time_usec'] = terminal ? result['start_time_usec'] + result['elapsed_usec'] : 0
  result
end

.info_to_node(info, node_id:, cluster_id:, docroot:, transfer_user:) ⇒ Hash

Build Node API node information from transferd instance information

Parameters:

Returns:

  • (Hash) —

    Node API node information (info-get-200)



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/aspera/plugins/node/emulator.rb', line 235

def info_to_node(info, node_id:, cluster_id:, docroot:, transfer_user:)
  ascp = info.asperaInfo.find { |binary| binary.asperaBinary.eql?('ascp') } || transferd_agent_class.empty_message(:aspera_info)
  license = info.licenseInfo || transferd_agent_class.empty_message(:license_info)
  {
    'application'             => 'node',
    # without build id
    'version'                 => ascp.asperaVersion.sub(/ .*$/, ''),
    'current_time'            => Time.now.utc.iso8601(0),
    'license_expiration_date' => license.license[%r{<expiration_date>([^<]*)</expiration_date>}, 1].to_s,
    'license_max_rate'        => license.maxRate,
    'os'                      => ascp.operatingSystem,
    'node_id'                 => node_id,
    'cluster_id'              => cluster_id,
    'transfer_user'           => transfer_user,
    'docroot'                 => "file:///#{docroot}"
  }.merge(INFO_STATIC)
end

.message_to_hash(message, overrides) ⇒ Hash

Convert a transferd message to a hash with Node API field names

Parameters:

  • message (Google::Protobuf::AbstractMessage) —

    transferd message

  • overrides (Hash) —

    field name → Node API name (nil: ignored)

Returns:

  • (Hash) —

    all fields (including default values), keys in snake case, time stamps in microseconds



130
131
132
133
134
135
136
137
138
# File 'lib/aspera/plugins/node/emulator.rb', line 130

def message_to_hash(message, overrides)
  message.class.descriptor.each_with_object({}) do |field, hash|
    key = overrides.fetch(field.name) { field.name.capital_to_snake }
    next if key.nil?
    value = message[field.name]
    value *= 1000 if key.end_with?('_time_usec') && value.positive? && value < MAX_MSEC
    hash[key] = value
  end
end

.node_status(status) ⇒ String

Convert a transferd transfer status to a Node API status

Parameters:

  • status (Symbol) —

    transferd TransferStatus

Returns:

  • (String) —

    Node API transfer status



122
123
124
# File 'lib/aspera/plugins/node/emulator.rb', line 122

def node_status(status)
  STATUS.fetch(status, 'waiting')
end

.session_to_node(session, retry_timeout: 0, node_id: '') ⇒ Hash

Convert a transferd session to a Node API session

Parameters:

Returns:

  • (Hash) —

    Node API session (transferResponseSessions)



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/aspera/plugins/node/emulator.rb', line 192

def session_to_node(session, retry_timeout: 0, node_id: '')
  source = message_to_hash(session, SESSION_OVERRIDES)
  status = session.status.downcase
  status = SESSION_STATUS.fetch(status, status)
  result = source.slice(*SESSION_FIELDS)
  # transferd provides the address of the remote side only: the server
  result['server_ip_address'] = source['remote_address'] if result['server_ip_address'].empty?
  # transferd provides the node id of the remote side only: the local side is the emulator
  result['client_node_id'] = node_id if result['client_node_id'].empty?
  precalc = PRECALC.transform_values { |field| source[field] }
  result.merge(
    'status'            => status,
    'retry_count'       => 0,
    'retry_timeout'     => retry_timeout,
    'stalled'           => false,
    'avg_rate_kbps'     => source['elapsed_usec'].positive? ? (source['bytes_transferred'] * 8000.0 / source['elapsed_usec']).round(2) : 0,
    'source_statistics' => SOURCE_STATISTICS.transform_values { |field| source[field] },
    'precalc'           => precalc.merge(
      'enabled' => session.precalc.casecmp?('yes'),
      'status'  => precalc_status(precalc['bytes_expected'], !ACTIVE.include?(status))
    )
  )
end

.transfer_to_node(id, entry, node_id: '') ⇒ Hash

Build a Node API transfer from a store entry

Parameters:

  • id (String) —

    transfer id

  • entry (Hash) —

    store entry

  • node_id (String) (defaults to: '') —

    node id of the emulator

Returns:

  • (Hash) —

    Node API transfer (transferResponseSessionSpec)



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/aspera/plugins/node/emulator.rb', line 161

def transfer_to_node(id, entry, node_id: '')
  info = message_to_hash(entry[:info] || transferd_agent_class.empty_message(:transfer_info), TRANSFER_OVERRIDES)
  terminal = TERMINAL.include?(entry[:status])
  retry_timeout = xfer_retry(entry[:start_spec])
  sessions = entry[:sessions].map { |session_id, session| session_to_node(session, retry_timeout: retry_timeout, node_id: node_id).merge(entry[:rates].fetch(session_id, {})) }
  error_desc = info['error_desc'].strip
  error_desc = entry[:error].to_s if error_desc.empty?
  precalc = PRECALC.keys.to_h { |field| [field, sessions.sum { |session| session['precalc'][field] }] }
  info.slice(*TRANSFER_FIELDS).merge(
    'id'              => id,
    'status'          => node_status(entry[:status]),
    'start_spec'      => entry[:start_spec],
    'sessions'        => sessions,
    # transferd does not provide the start time of the transfer
    'start_time_usec' => sessions.map { |session| session['start_time_usec'] }.select(&:positive?).min || 0,
    'end_time_usec'   => terminal ? info['end_time_usec'] : 0,
    'error_code'      => info['error_code'].to_i,
    'error_desc'      => error_desc,
    'precalc'         => precalc.merge(
      'enabled' => sessions.any? { |session| session['precalc']['enabled'] },
      'status'  => precalc_status(precalc['bytes_expected'], terminal)
    ),
    'files'           => entry[:files].values.map { |file| file_to_node(file) }
  )
end

.update_entry(entry, response) ⇒ Object

Update a store entry with a transferd event

Parameters:



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/aspera/plugins/node/emulator.rb', line 143

def update_entry(entry, response)
  entry[:status] = response.status
  entry[:info] = response.transferInfo unless response.transferInfo.nil?
  session = response.sessionInfo
  entry[:sessions][session.sessionId] = session unless session.nil? || session.sessionId.empty?
  # event ARG_STOP has a file without id
  file = response.fileInfo
  entry[:files][file.fileId] = file unless file.nil? || file.fileId.empty?
  entry[:error] = response.error.description unless response.error.nil? || response.error.description.empty?
  # session information keeps the initial rates, the ascp management message has the current ones
  entry[:rates][session.sessionId] = management_rates(response.message) if response.transferEvent.eql?(:RATE_MODIFICATION) && entry[:sessions].key?(session&.sessionId)
end

Instance Method Details

#browse(path, skip: 0, count: nil) ⇒ Hash

List a folder of the docroot

Parameters:

  • path (String) —

    folder to list, relative to the docroot

  • skip (Integer) (defaults to: 0) —

    number of items to skip (paging)

  • count (Integer) (defaults to: nil) —

    max number of items returned (paging)

Returns:

  • (Hash) —

    Node API folder content, paths relative to the docroot



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/aspera/plugins/node/emulator.rb', line 335

def browse(path, skip: 0, count: nil)
  folder_path = real_path(path)
  # symbolic links shall not lead out of the docroot
  Aspera.assert(in_docroot?(File.realpath(folder_path))) { "Path outside docroot: #{path}" }
  Aspera.assert(File.directory?(folder_path)) { "Not a folder: #{path}" }
  folder_virtual = virtual_path(folder_path)
  # stable order for paging: only the items of the page are read
  names = Dir.children(folder_path).sort
  items = names.drop(skip).first(count || names.length).map do |name|
    item_path = File.join(folder_path, name)
    # a symbolic link is not followed
    item = item_info(item_path, File.join(folder_virtual, name), File.lstat(item_path))
    case item['type']
    when 'file' then item['partial_file'] = false
    when 'symbolic_link' then item['target'] = link_target(item_path)
    when 'unknown' then item['note'] = 'File type could not be determined'
    end
    item
  end
  {
    'self'        => item_info(folder_path, folder_virtual, File.stat(folder_path)),
    'items'       => items,
    'item_count'  => items.length,
    'total_count' => names.length
  }
end

#cancel(id) ⇒ Boolean

Stop a transfer: its status becomes canceled when transferd notifies it

Parameters:

Returns:

  • (Boolean) —

    false if unknown



410
411
412
413
414
415
416
417
# File 'lib/aspera/plugins/node/emulator.rb', line 410

def cancel(id)
  return false unless known?(id)
  response = @transfer_client.stop(id)
  Log.dump(:stop_response, response.to_h, level: :trace2)
  result = response.stopResult.find { |info| info.transferId.eql?(id) }
  Aspera.assert(result&.stopped, type: Aspera::Transfer::Error) { result&.error&.description || 'Transfer not stopped by transferd' }
  true
end

#info ⇒ Hash

Get the node information

Returns:

  • (Hash) —

    Node API node information, from transferd



323
324
325
326
327
328
# File 'lib/aspera/plugins/node/emulator.rb', line 323

def info
  response = @transfer_client.instance_info
  Log.dump(:get_info_response, response.to_h, level: :trace2)
  Aspera.assert(response.error.nil? || response.error.description.empty?, type: RuntimeError) { response.error.description }
  self.class.info_to_node(response.info || self.class.send(:transferd_agent_class).empty_message(:instance_info), node_id: @node_id, cluster_id: @cluster_id, docroot: @docroot, transfer_user: @transfer_user)
end

#modify(id, changes) ⇒ Boolean

Modify the rates or the policy of a transfer

Parameters:

  • id (String) —

    transfer id

  • changes (Hash) —

    new values of transfer spec fields: target_rate_kbps, min_rate_kbps, rate_policy

Returns:

  • (Boolean) —

    false if unknown



423
424
425
426
427
428
429
# File 'lib/aspera/plugins/node/emulator.rb', line 423

def modify(id, changes)
  return false unless known?(id)
  response = @transfer_client.modify(id, changes.to_json)
  Log.dump(:modify_response, response.to_h, level: :trace2)
  Aspera.assert(response.error.nil? || response.error.description.empty?, type: Aspera::Transfer::Error) { response.error.description }
  true
end

#start(transfer_spec) ⇒ String

Start a transfer, and monitor it in a thread until terminated

Parameters:

  • transfer_spec (Hash) —

    transfer spec, local paths relative to the docroot (modified)

Returns:

Raises:



365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/aspera/plugins/node/emulator.rb', line 365

def start(transfer_spec)
  Aspera::Transfer::Spec.fix_transferd_resume_policy(transfer_spec)
  # copy without secrets, returned in transfer `start_spec`
  start_spec = Secret::Hider.instance.hidden_copy(transfer_spec)
  Log.dump(:start_spec, start_spec)
  request = apply_docroot(transfer_spec).to_json
  first_event = Thread::Queue.new
  Thread.new { monitor(request, start_spec, first_event) }
  result = first_event.pop(timeout: START_TIMEOUT_SEC)
  raise Aspera::Transfer::Error, "No event from transferd after #{START_TIMEOUT_SEC}s" if result.nil?
  raise result if result.is_a?(Exception)
  return result
end

#transfer(id) ⇒ Hash?

Get a transfer started by the emulator

Parameters:

Returns:

  • (Hash, nil) —

    Node API transfer, nil if unknown



382
383
384
385
386
387
388
389
390
391
392
# File 'lib/aspera/plugins/node/emulator.rb', line 382

def transfer(id)
  entry = store do |transfers|
    found = transfers[id]
    found&.merge(sessions: found[:sessions].dup, files: found[:files].dup, rates: found[:rates].dup)
  end
  return if entry.nil?
  result = self.class.transfer_to_node(id, entry, node_id: @node_id)
  # transferd gives real paths of local files
  result['files'].each { |file| file['path'] = virtual_path(file['path']) if in_docroot?(file['path']) }
  result
end

#transfers(active_only: nil, direction: nil, count: nil) ⇒ Array<Hash>

List the transfers started by the emulator

Parameters:

  • active_only (Boolean, nil) (defaults to: nil) —

    true: only waiting or running, false: only terminated, nil: all

  • direction (String, nil) (defaults to: nil) —

    send or receive

  • count (Integer, nil) (defaults to: nil) —

    max number of transfers, oldest first

Returns:

  • (Array<Hash>) —

    Node API transfers



399
400
401
402
403
404
405
# File 'lib/aspera/plugins/node/emulator.rb', line 399

def transfers(active_only: nil, direction: nil, count: nil)
  # a transfer may expire between the two calls
  result = store(&:keys).filter_map { |id| transfer(id) }
  result.select! { |transfer| ACTIVE.include?(transfer['status']).eql?(active_only) } unless active_only.nil?
  result.select! { |transfer| transfer['start_spec']['direction'].eql?(direction) } unless direction.nil?
  count.nil? ? result : result.first(count)
end