Class: Aspera::Plugins::Transferd::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/plugins/transferd/api.rb

Overview

Client of a running Transfer Daemon (transferd): gRPC calls, no CLI. Requires the optional gem grpc.

Defined Under Namespace

Classes: ApiKeyInterceptor

Constant Summary collapse

CALL_TIMEOUT_SEC =

Default timeout in seconds of the calls of transfer_status and transfer_cancel (agent_params['timeout'])

10
FINAL_STATUSES =

Statuses of the daemon after which a transfer does not change

%i[COMPLETED FAILED CANCELED].freeze

Class Method Summary collapse

Class Method Details

.client(agent_params) ⇒ Transferd::Api::TransferService::Stub

Returns Client of the daemon.

Parameters:

  • agent_params (Hash) —

    url: endpoint of the daemon (see create_client); optional api_key, ca_file

Returns:



78
79
80
81
# File 'lib/aspera/plugins/transferd/api.rb', line 78

def client(agent_params)
  Aspera.assert(agent_params['url'].is_a?(String) && !agent_params['url'].empty?) { 'agent_params: missing url' }
  create_client(agent_params['url'], api_key: agent_params['api_key'], ca_file: agent_params['ca_file'])
end

.create_client(url, api_key: nil, ca_file: nil) ⇒ Transferd::Api::TransferService::Stub

Client of a daemon

Parameters:

  • url (String) —

    Endpoint of the daemon, e.g. 127.0.0.1:55002, or :55002 for address 127.0.0.1 (see endpoint)

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

    API key, if the daemon has authentication enabled

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

    File with the certificate authority of the daemon (PEM), if the daemon has tls enabled

Returns:



69
70
71
72
73
74
# File 'lib/aspera/plugins/transferd/api.rb', line 69

def create_client(url, api_key: nil, ca_file: nil)
  url = endpoint(url)
  credentials = ca_file.nil? ? :this_channel_is_insecure : GRPC::Core::ChannelCredentials.new(File.read(ca_file))
  return ::Transferd::Api::TransferService::Stub.new(url, credentials) if api_key.nil?
  ::Transferd::Api::TransferService::Stub.new(url, credentials, interceptors: [ApiKeyInterceptor.new(api_key)])
end

.endpoint(url) ⇒ String

Returns The endpoint, with address 127.0.0.1 if it has none.

Parameters:

  • url (String) —

    Endpoint of a daemon, e.g. 127.0.0.1:55002, or only its port, e.g. :55002

Returns:

  • (String) —

    The endpoint, with address 127.0.0.1 if it has none



60
61
62
# File 'lib/aspera/plugins/transferd/api.rb', line 60

def endpoint(url)
  url.match?(/\A:[0-9]+\z/) ? "#{LOCAL_ADDRESS}#{url}" : url
end

.info(agent_params) ⇒ Hash

Information on a running daemon (unary call GetInfo)

Parameters:

  • agent_params (Hash) —

    url: endpoint of the daemon; optional timeout: seconds, api_key, ca_file

Returns:

  • (Hash) —

    Version of the API (apiVersion) and information on the instance (info)

Raises:



106
107
108
109
110
111
112
113
# File 'lib/aspera/plugins/transferd/api.rb', line 106

def info(agent_params)
  response = client(agent_params).get_info(::Transferd::Api::InstanceInfoRequest.new, deadline: deadline(agent_params))
  error = response.error&.description.to_s
  Aspera.assert(error.empty?, type: Aspera::Transfer::Error) { error }
  JSON.parse(response.to_h.except(:error).to_json)
rescue GRPC::BadStatus => e
  raise Aspera::Transfer::Error, "#{e.class.name.split('::').last}: #{e.details}"
end

.normalize_status(response) ⇒ Hash

Returns Normalized status, see transfer_status.

Parameters:

Returns:

  • (Hash) —

    Normalized status, see transfer_status



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/aspera/plugins/transferd/api.rb', line 130

def normalize_status(response)
  info = response.transferInfo
  result = {
    'status'            => ASYNC_STATUS.fetch(response.status, 'running'),
    'state'             => response.status.to_s.downcase,
    'bytes_transferred' => info&.bytesTransferred.to_i
  }
  return result if info.nil?
  result.merge!(
    'bytes_written'    => info.bytesWritten,
    'files_completed'  => info.filesCompleted,
    'rate_kbps'        => info.averageRateKbps,
    'target_rate_kbps' => info.targetRateKbps,
    'elapsed_sec'      => info.elapsedUsec / 1_000_000.0,
    'started_at'       => epoch_time(info.startTimeUsec),
    'ended_at'         => epoch_time(info.endTimeUsec)
  )
  if FINAL_STATUSES.include?(response.status)
    result['ended_at'] ||= Time.now.utc.iso8601
  else
    result.delete('ended_at')
  end
  error = info.errorDescription.to_s.strip
  error = response.error&.description.to_s if error.empty?
  unless error.empty?
    result['error_code'] = info.errorCode
    result['error'] = error
  end
  result.compact
end

.transfer_cancel(transfer_id, agent_params) ⇒ Boolean

Stop a transfer (call StopTransfer)

Parameters:

  • transfer_id (String) —

    Identifier of transfer, given by the daemon

  • agent_params (Hash) —

    url: endpoint of the daemon; optional timeout: seconds, api_key, ca_file

Returns:

  • (Boolean) —

    true: stopped

Raises:



120
121
122
123
124
125
126
# File 'lib/aspera/plugins/transferd/api.rb', line 120

def transfer_cancel(transfer_id, agent_params)
  response = client(agent_params).stop_transfer(::Transferd::Api::StopTransferRequest.new(transferId: [transfer_id]), deadline: deadline(agent_params))
  result = response.stopResult.find { |item| item.transferId.eql?(transfer_id) }
  Aspera.assert(!result.nil?, type: Aspera::Transfer::Error) { "transfer id=#{transfer_id}: no result of stop" }
  Aspera.assert(result.stopped, type: Aspera::Transfer::Error) { result.error&.description || "transfer id=#{transfer_id}: not stopped" }
  true
end

.transfer_status(transfer_id, agent_params) ⇒ Hash

Re-query a previously started transfer from a running transferd daemon (unary call QueryTransfer). The daemon keeps a transfer for some time after its end (workers.transfer_max_age of its configuration): then it is unknown.

Parameters:

  • transfer_id (String) —

    Identifier of transfer, given by the daemon (transfer_id)

  • agent_params (Hash) —

    url: endpoint of the daemon, e.g. 127.0.0.1:55002; optional timeout: seconds, api_key, ca_file

Returns:

  • (Hash) —

    Normalized status: status (running, completed, failed, cancelled, or unknown if the daemon cannot tell), bytes_transferred, and when known: state (status of the daemon), bytes_written (by the receiver, with the bytes of a resumed transfer), files_completed, rate_kbps (average), target_rate_kbps, elapsed_sec, started_at, ended_at, error_code, error



91
92
93
94
95
96
97
98
99
100
# File 'lib/aspera/plugins/transferd/api.rb', line 91

def transfer_status(transfer_id, agent_params)
  response = client(agent_params).query_transfer(::Transferd::Api::TransferInfoRequest.new(transferId: transfer_id), deadline: deadline(agent_params))
  # An unknown transfer is not an exception: status is not set, and error has code 404
  error = response.error&.description.to_s
  return {'status' => 'unknown', 'bytes_transferred' => 0, 'error' => error} if response.status.eql?(:UNKNOWN_STATUS) && !error.empty?
  normalize_status(response)
rescue GRPC::BadStatus => e
  # Daemon not reachable, or timeout: the transfer may still run
  {'status' => 'unknown', 'bytes_transferred' => 0, 'error' => "#{e.class.name.split('::').last}: #{e.details}"}
end