Class: Aspera::Plugins::Xfer::TransferAgent
- Inherits:
-
Object
- Object
- Aspera::Plugins::Xfer::TransferAgent
- Extended by:
- Cli::Option::Declarator
- Defined in:
- lib/aspera/plugins/xfer/transfer_agent.rb
Overview
The Transfer agent is a common interface to start a transfer using
one of the supported transfer agents.
Provide CLI options to select one of the transfer agents (FASP/ascp client)
Service transfer of the bundle (manifest services): created once per context, see Cli::Context#service
Constant Summary collapse
- STATUS_FIELD =
Plugins store transfer result using this key and use
result_transfer_multiple 'status'- TRANSFER_OPTION_SCHEMA =
Schema of option
transfer, in the schemas of the bundle (manifestschemas): its variants are the agents (extension pointagent) 'transfer_opts:components.schemas.TransferAgentOptions'- FILE_LIST_FROM_ARGS =
@argsspecial value for --sources : read file list from arguments '@args'- CP4I_REMOTE_HOST_LB =
'N/A'
Instance Attribute Summary collapse
-
#user_transfer_spec ⇒ Object
Returns the value of attribute user_transfer_spec.
Class Method Summary collapse
-
.result_object_transfer(object, transfer_result) ⇒ Cli::Result::SingleObject
Result of a command that creates an object and transfers its files, e.g.
-
.result_transfer(transfer_result) ⇒ Cli::Result
Process the typed result of a finished (or submitted) transfer.
-
.result_transfer_multiple(status_table) ⇒ Cli::Result
Used when one command executes several transfer jobs (each job being possibly multi session).
Instance Method Summary collapse
-
#agent_instance ⇒ Object
analyze options and create new agent if not already created or set.
- #agent_instance=(instance) ⇒ Object
-
#agent_name ⇒ String
Name of the agent in use (resolved name, not an abbreviation of option
transfer), also if the instance was given. -
#assert_no_dry_run ⇒ Object
For a command that changes something before its transfer (e.g. creates a package), or that does not transfer with
start: fail before any change with optiondry_run. -
#async_store ⇒ Object
Lazy accessor for the async transfer store (shared with TransferActions via context.transfer).
-
#destination_folder(direction) ⇒ String
Get destination folder.
-
#dry_run? ⇒ Boolean
trueif optiondry_runis set: transfers are not started (seestart). - #httpgw_url_cb=(httpgw_url_proc) ⇒ Object
-
#initialize(context) ⇒ TransferAgent
constructor
A new instance of TransferAgent.
-
#list_to_paths(file_list) ⇒ Object
Transform the list of paths to a list of hash with source/dest.
-
#paths_argument(direction) ⇒ Cli::Argument
Argument shown in the help of a command with
transfer_paths: the files are read byts_source_paths. -
#shutdown ⇒ Object
shut down if agent requires it.
-
#source_list ⇒ Array
List of source files.
-
#start(transfer_spec, oauth_api: nil) ⇒ Object
Start a transfer and wait for completion, plugins shall use this method.
-
#sync_agent_options ⇒ Hash
Options to create the
directagent that runs the localasyncprogram for asynccommand. -
#transfer_options ⇒ Hash
Agent type (key
agent) and agent parameters, from optionstransferand deprecatedtransfer_info. -
#ts_source_paths(default: nil) ⇒ Array?
This is how the list of files to be transferred is specified get paths suitable for transfer spec from command line computation is done only once, cache is kept in @transfer_paths.
Methods included from Cli::Option::Declarator
declare_options, option, option_specs, register_option_spec
Constructor Details
#initialize(context) ⇒ TransferAgent
Returns a new instance of TransferAgent.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 136 def initialize(context) Aspera.assert_type(context, Cli::Context) { 'context' } Aspera.assert_type(context., Cli::Parser) { 'context.options' } @context = context # Runtime of transfers: SDK downloads refer to the version of the gem, file lists are in the configuration folder (if any, else a temporary folder) Ascp::Installation.instance.referer_url = "#{Cli::Info::GEM_URL}/versions/#{Cli::VERSION}" Aspera::Transfer::Parameters.file_list_folder = File.join(@context.main_folder, FILE_LIST_FOLDER_NAME) unless @context.main_folder.nil? # Command line can override transfer spec @user_transfer_spec = TS_DEFAULTS.dup # the currently selected transfer agent @agent = nil # source/destination pair, like "paths" of transfer spec @transfer_paths = nil # HTTPGW URL provided by webapp @httpgw_url_lambda = nil # Instance variables used by `on_set` callbacks are set above self.class.(@context., target: self) @context.. @notification_cb = nil if !@context..get_option(:notify_to).nil? @notification_cb = ->(transfer_spec, global_status) do @context.mailer.send_email_template(email_template_default: DEFAULT_TRANSFER_NOTIFY_TEMPLATE, values: { subject: "#{Cli::Info::CMD_NAME} transfer: #{global_status}", status: global_status, ts: transfer_spec }) end end end |
Instance Attribute Details
#user_transfer_spec ⇒ Object
Returns the value of attribute user_transfer_spec.
166 167 168 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 166 def user_transfer_spec @user_transfer_spec end |
Class Method Details
.result_object_transfer(object, transfer_result) ⇒ Cli::Result::SingleObject
Result of a command that creates an object and transfers its files, e.g. packages send.
103 104 105 106 107 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 103 def result_object_transfer(object, transfer_result) status = result_transfer(transfer_result) object = object.merge('transfer' => status.data) if status.is_a?(Cli::Result::SingleObject) Cli::Result::SingleObject.new(object) end |
.result_transfer(transfer_result) ⇒ Cli::Result
Process the typed result of a finished (or submitted) transfer.
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 82 def result_transfer(transfer_result) case transfer_result when Aspera::Transfer::Result::Async return Cli::Result::SingleObject.new(transfer_result.to_h) when Aspera::Transfer::Result::Error raise transfer_result.exception when Aspera::Transfer::Result::Success return Cli::Result::Nothing.new when Aspera::Transfer::Result::DryRun # Secrets are hidden by the formatter, as in any result return Cli::Result::SingleObject.new(transfer_result.transfer_spec) else raise "Unexpected transfer result type: #{transfer_result.class}" end end |
.result_transfer_multiple(status_table) ⇒ Cli::Result
Used when one command executes several transfer jobs (each job being possibly multi session)
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 112 def result_transfer_multiple(status_table) failed_result = nil status_table.each do |item| tr = item[STATUS_FIELD] case tr when Aspera::Transfer::Result::Error failed_result ||= tr item[STATUS_FIELD] = tr.exception. when Aspera::Transfer::Result::Success item[STATUS_FIELD] = 'success' when Aspera::Transfer::Result::Async item[STATUS_FIELD] = "async:#{tr.job_id}" when Aspera::Transfer::Result::DryRun item[STATUS_FIELD] = 'dry_run' else item[STATUS_FIELD] = tr.to_s end end raise failed_result.exception unless failed_result.nil? return Cli::Result::ObjectList.new(status_table) end |
Instance Method Details
#agent_instance ⇒ Object
analyze options and create new agent if not already created or set
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 223 def agent_instance return @agent unless @agent.nil? # agent type: from composite option 'agent' key, default :direct raw_type = ['agent'] || :direct # An agent of an unavailable bundle is given as is: creating it tells why it is unavailable agent_type = Aspera::Agent::Factory.instance.unavailable_reason(raw_type).nil? ? Cli::Parser.get_from_list(raw_type.to_s, 'transfer agent', Aspera::Agent::Factory::ALL.keys) : raw_type.to_s # set keys as symbols, strip internal keys not forwarded to the agent constructor = .except('agent', 'asynchronous').symbolize_keys # get agent instance begin agent_class = Aspera::Agent::Factory.instance.agent_class(agent_type) # A transfer agent that runs on the local host (local `ascp`, a local daemon, a local application) is refused at level `high`: # at `high`, transfers use a remote agent (e.g. `node`, or `transferd` attached to a remote daemon) that the user controls. # Checked before the base options are built: the decision needs only the agent parameters (e.g. the daemon `url`). unless Cli::Security.instance.allowed?(agent_class.required_security_level()) raise Cli::BadArgument, "transfer agent #{agent_type}: runs on the local host, disabled by security level #{Cli::Security.instance.level}. " \ 'Use a remote agent (--transfer.agent=node, or --transfer.agent=transferd with a url to a remote daemon), or a lower security level' end # Same base options for every agent, each agent uses those it needs (see `Aspera::Agent::Base#initialize`) # JRuby: given value, else trusted certificates of the HTTP configuration [:trusted_certs] = @context.http_config.trusted_cert_locations unless .key?(:trusted_certs) .merge!() self.agent_instance = Aspera::Agent::Factory.instance.create(agent_type, ) @agent_type = agent_type.to_s rescue BundleRegistry::Unavailable => e # Agent of a bundle that cannot be loaded (e.g. missing gem): same error as an unavailable plugin raise Cli::Error, e. end Log.log.debug { "transfer agent is a #{@agent.class}" } return @agent end |
#agent_instance=(instance) ⇒ Object
209 210 211 212 213 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 209 def agent_instance=(instance) @agent = instance # Name of the agent is found from the instance when needed, see `agent_name` @agent_type = nil end |
#agent_name ⇒ String
Returns Name of the agent in use (resolved name, not an abbreviation of option transfer), also if the instance was given.
216 217 218 219 220 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 216 def agent_name @agent_type ||= Aspera::Agent::Factory.instance.agent_name(agent_instance)&.to_s Aspera.assert(@agent_type) { "unknown agent class: #{agent_instance.class}" } @agent_type end |
#assert_no_dry_run ⇒ Object
For a command that changes something before its transfer (e.g. creates a package), or that does not transfer with start:
fail before any change with option dry_run
436 437 438 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 436 def assert_no_dry_run Aspera.assert(!dry_run?, type: Cli::BadArgument) { 'Option dry_run is not supported by this command' } end |
#async_store ⇒ Object
Lazy accessor for the async transfer store (shared with TransferActions via context.transfer).
446 447 448 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 446 def async_store @async_store ||= AsyncTransferStore.new(@context.persistency) end |
#destination_folder(direction) ⇒ String
Get destination folder
259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 259 def destination_folder(direction) dest_folder = @context..get_option(:to_folder) # do not expand path, if user wants to expand path: user @path: return dest_folder unless dest_folder.nil? dest_folder = @user_transfer_spec['destination_root'] return dest_folder unless dest_folder.nil? # default: / on remote, . on local case direction.to_s when Aspera::Transfer::Spec::DIRECTION_SEND then dest_folder = '/' when Aspera::Transfer::Spec::DIRECTION_RECEIVE then dest_folder = '.' else Aspera.error_unexpected_value(direction) end return dest_folder end |
#dry_run? ⇒ Boolean
Returns true if option dry_run is set: transfers are not started (see start).
429 430 431 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 429 def dry_run? @context..get_option(:dry_run) end |
#httpgw_url_cb=(httpgw_url_proc) ⇒ Object
282 283 284 285 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 282 def httpgw_url_cb=(httpgw_url_proc) Aspera.assert_type(httpgw_url_proc, Proc) { 'httpgw_url_cb' } @httpgw_url_lambda = httpgw_url_proc end |
#list_to_paths(file_list) ⇒ Object
Transform the list of paths to a list of hash with source/dest
289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 289 def list_to_paths(file_list) source_type = @context..get_option(:src_type, mandatory: true) @transfer_paths = case source_type when :list # when providing a list, just specify source file_list.map { |i| {'source' => i} } when :pair Aspera.assert(file_list.length.even?, type: Cli::BadArgument) { "When using pair, provide an even number of paths: #{file_list.length}" } file_list.each_slice(2).map { |s, d| {'source' => s, 'destination' => d} } else Aspera.error_unexpected_value(source_type) end end |
#paths_argument(direction) ⇒ Cli::Argument
Argument shown in the help of a command with transfer_paths: the files are read by ts_source_paths
171 172 173 174 175 176 177 178 179 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 171 def paths_argument(direction) description = case direction when :receive then "Remote path(s) to download (default --sources=#{FILE_LIST_FROM_ARGS}; see also --to-folder)" when :send then "Source file(s) to upload (default --sources=#{FILE_LIST_FROM_ARGS}; see also --src-type, --to-folder)" else Aspera.error_unexpected_value(direction) { 'transfer_paths' } end Cli::Argument.new(name: :source_file, description: description, mandatory: false, multiple: true) end |
#shutdown ⇒ Object
shut down if agent requires it
441 442 443 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 441 def shutdown @agent.shutdown if @agent.respond_to?(:shutdown) end |
#source_list ⇒ Array
Returns list of source files.
275 276 277 278 279 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 275 def source_list return ts_source_paths.map do |i| i['source'] end end |
#start(transfer_spec, oauth_api: nil) ⇒ Object
Start a transfer and wait for completion, plugins shall use this method
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 346 def start(transfer_spec, oauth_api: nil) # check parameters Aspera.assert_type(transfer_spec, Hash) { 'transfer_spec' } raise "Wrong remote host: #{CP4I_REMOTE_HOST_LB}" if transfer_spec['remote_host'].eql?(CP4I_REMOTE_HOST_LB) # process :src option case transfer_spec['direction'] when Aspera::Transfer::Spec::DIRECTION_RECEIVE # init default if required in any case @user_transfer_spec['destination_root'] ||= destination_folder(transfer_spec['direction']) when Aspera::Transfer::Spec::DIRECTION_SEND if transfer_spec.dig('tags', Aspera::Transfer::Spec::TAG_RESERVED, 'node', 'access_key') # gen4 @user_transfer_spec.delete('destination_root') if @user_transfer_spec.key?('destination_root_id') elsif transfer_spec.key?('token') # gen3 # in that case, destination is set in return by application (API/upload_setup) # but to_folder was used in initial API call @user_transfer_spec.delete('destination_root') else # init default if required @user_transfer_spec['destination_root'] ||= destination_folder(transfer_spec['direction']) end end # update command line paths, unless destination already has one @user_transfer_spec['paths'] = transfer_spec['paths'] || ts_source_paths # updated transfer spec with command line application_host = transfer_spec['remote_host'] transfer_spec.deep_merge!(@user_transfer_spec) # The credentials of the transfer spec of the command are for its host Cli::Security.instance.check_transfer_host(transfer_spec, @user_transfer_spec, application_host: application_host) # Files are written where the client chooses, see Security: only for an agent that writes on the local system receives_locally = transfer_spec['direction'].eql?(Aspera::Transfer::Spec::DIRECTION_RECEIVE) && agent_instance.local_destination? transfer_spec['destination_root'] = Cli::Security.instance.writable_path(transfer_spec['destination_root']) if receives_locally && transfer_spec['destination_root'] # resolve pseudo-parameter: target_rate -> target_rate_kbps (overrides target_rate_kbps if both are present) Aspera::Transfer::Spec.resolve_target_rate(transfer_spec) Aspera::Transfer::Spec.stringify_exclude_times(transfer_spec) # recursively remove values that are nil (user wants to delete) transfer_spec.deep_do { |hash, key, value, _unused| hash.delete(key) if value.nil? } # if TS from app has content_protection (e.g. F5), that means content is protected: ask password if not provided transfer_spec['content_protection_password'] = @context..prompt_user_input('content protection password', sensitive: true) if transfer_spec['content_protection'].eql?('decrypt') && !transfer_spec.key?('content_protection_password') # Secrets of transfer spec (e.g. `token` from the application) are hidden wherever they appear (logs, results) Secret::Hider.instance.add_secrets_in(transfer_spec) # Option `dry_run`: no transfer, the final transfer spec is the result return Aspera::Transfer::Result.dry_run(transfer_spec) if dry_run? # Renews the bearer token of the transfer: only possible with OAuth token_regenerator = -> { oauth_api.oauth. } if oauth_api&.auth_params&.fetch(:type, nil).eql?(:oauth2) # create transfer agent agent_instance.start_transfer(transfer_spec, token_regenerator: token_regenerator) # --- async mode --- if ['asynchronous'] # In-process agents (direct, httpgw) expose last_job_id directly. # Remote-daemon agents do not override last_job_id (returns nil): generate a UUID. agent_type = agent_name job_id = agent_instance.last_job_id || SecureRandom.uuid # Base agent_params from transfer options (strip internal keys), and connection details resolved by the agent (daemon agents) agent_params = .except('agent', 'asynchronous').merge(agent_instance.async_params) # Register an in-process agent reference for direct/httpgw agents so that # config transfer status can re-query them while the same process is alive # (e.g. MCP server mode). The ref is stored in AsyncTransferStore's memory map, # never on disk. async_store.register_agent_ref(job_id, agent_instance) if agent_instance.in_process? async_store.write(job_id, { 'job_id' => job_id, 'agent_type' => agent_type, 'transfer_id' => agent_instance.transfer_id.to_s, 'agent_params' => agent_params, 'status' => 'running', 'bytes_transferred' => 0, 'started_at' => Time.now.utc.iso8601, 'ended_at' => nil, 'error' => nil }) # The result gives the job_id and status Log.log.debug { "Async transfer started: job_id=#{job_id}, agent=#{agent_type}" } return Aspera::Transfer::Result.async(job_id: job_id) end # --- synchronous mode (default) --- result = agent_instance.wait_for_completion @notification_cb&.call(transfer_spec, result) return result end |
#sync_agent_options ⇒ Hash
Options to create the direct agent that runs the local async program for a sync command.
sync always uses the direct agent, whatever the agent key of option transfer, so the parameters of
transfer (and the deprecated transfer_info) are forwarded only when they are those of the direct agent
(its default); parameters meant for another agent (e.g. the url of node) are ignored. For async, quiet
and spawn_timeout_sec have an effect; the ascp-only parameters (e.g. ascp_args, wss, resume) do not.
The base options (e.g. progress, config_dir) are always given, as for any agent.
202 203 204 205 206 207 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 202 def raw_type = ['agent'] = raw_type.nil? || raw_type.to_s.eql?('direct') ? .except('agent', 'asynchronous').symbolize_keys : {} [:trusted_certs] = @context.http_config.trusted_cert_locations unless .key?(:trusted_certs) .merge() end |
#transfer_options ⇒ Hash
Returns agent type (key agent) and agent parameters, from options transfer and deprecated transfer_info.
188 189 190 191 192 193 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 188 def result = @context..get_option(:transfer_info).deep_merge(@context..get_option(:transfer)) # e.g. the `url` of agent `node` from one option, its `password` from the other Cli::Security.instance.check_credentials_in(result, what: 'option transfer') result end |
#ts_source_paths(default: nil) ⇒ Array?
This is how the list of files to be transferred is specified get paths suitable for transfer spec from command line computation is done only once, cache is kept in @transfer_paths
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
# File 'lib/aspera/plugins/xfer/transfer_agent.rb', line 308 def ts_source_paths(default: nil) # return cache if set return @transfer_paths unless @transfer_paths.nil? # start with lower priority : get paths from transfer spec on command line @transfer_paths = @user_transfer_spec['paths'] if @user_transfer_spec.key?('paths') # is there a source list option ? sources = @context..get_option(:sources) @transfer_paths = case sources when FILE_LIST_FROM_ARGS Log.log.debug('getting file list as parameters') Aspera.assert_type(default, Array, NilClass) # get remaining arguments list = @context..get_next_argument('source file list', multiple: true, default: default) raise Cli::BadArgument, 'specify at least one file on command line or use ' \ "--sources=#{FILE_LIST_FROM_TRANSFER_SPEC} to use transfer spec" if !list.is_a?(Array) || list.empty? list_to_paths(list) when FILE_LIST_FROM_TRANSFER_SPEC Log.log.debug('assume list provided in transfer spec') special_case_direct_with_list = (['agent'] || :direct).to_sym.eql?(:direct) && Aspera::Transfer::Parameters.ascp_args_file_list?(['ascp_args']) Aspera.assert(!@transfer_paths.nil? || special_case_direct_with_list, type: Cli::BadArgument) { 'transfer spec on command line must have sources' } # can be nil @transfer_paths when Array Log.log.debug('getting file list as extended value') Aspera.assert_array_all(sources, String, type: Cli::BadArgument) { 'sources must be a Array of String' } list_to_paths(sources) else Aspera.error_unexpected_value(sources) { 'sources' } end Log.dump(:paths, @transfer_paths) return @transfer_paths end |