Class: Aspera::Plugins::Direct::Agent
- Inherits:
-
Agent::Base
- Object
- Agent::Base
- Aspera::Plugins::Direct::Agent
- Defined in:
- lib/aspera/plugins/direct/agent.rb
Overview
Execute a local ascp and use its management port to monitor progress
Class Method Summary collapse
-
.required_security_level(_options) ⇒ Object
Runs
ascpon the local host: refused at levelhigh(seeCli::Security). -
.transfer_status(transfer_id, agent_params) ⇒ Hash
Re-query the status of a direct transfer that was started in-process.
Instance Method Summary collapse
-
#in_process? ⇒ Boolean
true:ascpsessions are monitored by threads of this process. -
#initialize(ascp_args: nil, wss: true, quiet: true, file_list: true, client_ssh_key: nil, spawn_timeout_sec: 2, spawn_delay_sec: 2, multi_incr_udp: nil, resume: {}, monitor: true, management_cb: nil, **base_options) ⇒ Agent
constructor
Options: same as values in option
transfer(Args) : Options that influenceascparguments. -
#last_job_id ⇒ String?
Job_id of the last submitted transfer.
-
#send_command(data, id: nil) ⇒ Object
Send command to management port of command (used in `asession).
-
#sessions_by_job(id) ⇒ Array
List of sessions for a job.
-
#shutdown ⇒ Object
used by asession (to be removed ?).
-
#start_and_monitor_process(session:, exec_spec:) ⇒ nil
This is the low level method to start the transfer process.
-
#start_transfer(transfer_spec, token_regenerator: nil) ⇒ Object
Start
ascptransfer(s) (non blocking), single or multi-session Session information added to @sessions. -
#transfer_id ⇒ String?
The job id: for
transfer_status. -
#wait_for_transfers_completion ⇒ Array
wait for completion of all jobs started.
Methods inherited from Agent::Base
#async_params, #local_destination?, transfer_cancel, #wait_for_completion
Constructor Details
#initialize(ascp_args: nil, wss: true, quiet: true, file_list: true, client_ssh_key: nil, spawn_timeout_sec: 2, spawn_delay_sec: 2, multi_incr_udp: nil, resume: {}, monitor: true, management_cb: nil, **base_options) ⇒ Agent
Options: same as values in option transfer
(Args) : Options that influence ascp arguments.
Base options used: progress, progress_default, config_dir,
trusted_certs (Args) (WSS) Optional list of files with trusted certificates (stores),
check_ignore_cb (Args) (WSS) Callback with host,port to check if WSS connection shall ignore certificate validity
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/aspera/plugins/direct/agent.rb', line 84 def initialize( ascp_args: nil, wss: true, quiet: true, file_list: true, client_ssh_key: nil, spawn_timeout_sec: 2, spawn_delay_sec: 2, multi_incr_udp: nil, resume: {}, monitor: true, management_cb: nil, ** ) super(**) # Native `ascp` progress bar: no other progress bar, unless requested own_progress_display unless quiet # Options that have impact on `ascp` command line generated @tr_opts = { ascp_args: ascp_args, wss: wss, quiet: quiet, file_list: file_list, trusted_certs: trusted_certs, client_ssh_key: client_ssh_key, check_ignore_cb: check_ignore_cb } @spawn_timeout_sec = spawn_timeout_sec @spawn_delay_sec = spawn_delay_sec # default is true on Windows, false on other OSes @multi_incr_udp = multi_incr_udp.nil? ? Environment.instance.os.eql?(Environment::OS_WINDOWS) : multi_incr_udp @monitor = monitor @management_cb = management_cb Aspera.assert_type(resume, Hash) { 'resume' } @resume_policy = Aspera::Transfer::Resumer.new(**resume.symbolize_keys) # all transfer jobs, key = SecureRandom.uuid, protected by mutex, cond var on change @sessions = [] # mutex protects global data accessed by threads @mutex = Mutex.new # Check on all management messages if that file exists, and if so, read commands from it @command_file = File.join(config_dir || '.', "send_#{$PROCESS_ID}") end |
Class Method Details
.required_security_level(_options) ⇒ Object
Runs ascp on the local host: refused at level high (see Cli::Security).
32 |
# File 'lib/aspera/plugins/direct/agent.rb', line 32 def required_security_level() = :medium |
.transfer_status(transfer_id, agent_params) ⇒ Hash
Re-query the status of a direct transfer that was started in-process. Only works if the same Ruby process is still alive (e.g. MCP mode). agent_params must contain '_agent_ref' pointing to the live Direct instance.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/aspera/plugins/direct/agent.rb', line 40 def transfer_status(transfer_id, agent_params) agent = agent_params['_agent_ref'] return {'status' => 'unknown', 'note' => 'direct agent not available (different process?)'} if agent.nil? sessions = agent.sessions_by_job(transfer_id) return {'status' => 'unknown', 'note' => "no sessions found for job #{transfer_id}"} if sessions.empty? errors = sessions.filter_map { |s| s[:error] } running = sessions.any? { |s| s[:thread]&.alive? } result = {'bytes_transferred' => sessions.sum { |s| s[:last_size].to_i }} result['ended_at'] = sessions.filter_map { |s| s[:ended_at] }.max unless running if errors.any? result.merge('status' => 'failed', 'error' => errors.first.) elsif running result.merge('status' => 'running') else result.merge('status' => 'completed') end end |
Instance Method Details
#in_process? ⇒ Boolean
Returns true: ascp sessions are monitored by threads of this process.
228 229 230 |
# File 'lib/aspera/plugins/direct/agent.rb', line 228 def in_process? true end |
#last_job_id ⇒ String?
Returns job_id of the last submitted transfer.
218 219 220 |
# File 'lib/aspera/plugins/direct/agent.rb', line 218 def last_job_id @sessions.last&.dig(:job_id) end |
#send_command(data, id: nil) ⇒ Object
Send command to management port of command (used in `asession). Examples: 'type'=>'START','source'=>_path_,'destination'=>_path_ 'type'=>'DONE'
266 267 268 269 270 271 272 273 274 275 276 277 |
# File 'lib/aspera/plugins/direct/agent.rb', line 266 def send_command(data, id: nil) Log.dump(:command, data) sessions = id ? sessions_by_job(id) : @sessions if sessions.empty? Log.log.warn('No transfer session') return end = Aspera::Ascp::Management.command_to_stream(data) sessions.each do |session| session[:io].puts() end end |
#sessions_by_job(id) ⇒ Array
Returns list of sessions for a job.
256 257 258 |
# File 'lib/aspera/plugins/direct/agent.rb', line 256 def sessions_by_job(id) @sessions.select { |session| session[:job_id].eql?(id) } end |
#shutdown ⇒ Object
used by asession (to be removed ?)
250 251 252 |
# File 'lib/aspera/plugins/direct/agent.rb', line 250 def shutdown Log.log.debug('fasp local shutdown') end |
#start_and_monitor_process(session:, exec_spec:) ⇒ nil
This is the low level method to start the transfer process. Typically started in a thread. Start process with management port.
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 342 343 344 345 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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
# File 'lib/aspera/plugins/direct/agent.rb', line 312 def start_and_monitor_process( session:, exec_spec: ) exec = exec_spec.exec env = exec_spec.env args = exec_spec.args Aspera.assert_type(session, Hash) notify_progress(:sessions_init, info: 'starting') # Do not use `capture_stderr` capture_stderr = false stderr_r, stderr_w = nil spawn_args = {} command_pid = nil # `true` when `async` ended reporting on the management port, but may keep running (continuous mode) async_keeps_running = false # Get location of command executable (ascp, async) command_path = Aspera::Ascp::Installation.instance.path(exec) command_arguments = [command_path] begin if @monitor # we use Socket directly, instead of TCPServer, as it gives access to lower level options socket_class = defined?(JRUBY_VERSION) ? ServerSocket : Socket mgt_server_socket = socket_class.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) # open any available (0) local TCP port for use as management port mgt_server_socket.bind(Addrinfo.tcp(LISTEN_LOCAL_ADDRESS, SELECT_AVAILABLE_PORT)) # make port ready to accept connections, before starting ascp mgt_server_socket.listen(1) # build arguments and add mgt port command_arguments = if exec.eql?(:async) [command_path, "--exclusive-mgmt-port=#{mgt_server_socket.local_address.ip_port}"] else [command_path, '-M', mgt_server_socket.local_address.ip_port.to_s] end end command_arguments.concat(args) if capture_stderr # capture process stderr stderr_r, stderr_w = IO.pipe spawn_args[:err] = stderr_w end command_pid = Environment.secure_execute(*command_arguments, mode: :background, env: env, **spawn_args) # close here, but still used in other process (pipe) stderr_w&.close notify_progress(:sessions_init, info: "waiting for #{exec} to start") # "ensure" block will wait for process return unless @monitor # TODO: timeout does not work when Process.spawn is used... until process exits, then it works # So we use select to detect that anything happens on the socket (connection) Log.log.debug { "before select, timeout: #{@spawn_timeout_sec}" } readable, _, _ = IO.select([mgt_server_socket], nil, nil, @spawn_timeout_sec) Log.log.debug('after select, before accept') Aspera.assert(readable, 'timeout waiting mgt port connect (select not readable)', type: Aspera::Transfer::Error) # There is a connection to accept client_socket, _client_addrinfo = mgt_server_socket.accept Log.log.debug('after accept') management_port_io = client_socket.to_io # by default socket is US-ASCII # management messages include file names which may be UTF-8 # TODO: use same value as Encoding.default_external ? management_port_io.set_encoding(Encoding::UTF_8) session[:io] = management_port_io processor = Aspera::Ascp::Management.new # read management port, until socket is closed (gets returns nil) while (line = management_port_io.gets) event = processor.process_line(line.chomp) next unless event # event is ready Log.dump(:management_port, event, level: :trace1) # store session identifier session[:id] = event['SessionId'] if event['Type'].eql?('INIT') @management_cb&.call(event) process_progress(session, event) next unless File.exist?(@command_file) begin commands = JSON.parse(File.read(@command_file)) send_command(commands) rescue => e Log.log.error { e.to_s } end File.delete(@command_file) end Log.log.debug('management io closed') # check that last status was received before process exit last_event = processor.last_event Aspera.assert_type(last_event, Hash, type: Aspera::Transfer::Error) { 'management event' } case last_event['Type'] when 'DONE' Log.log.trace1 { 'Graceful shutdown, DONE message received' } # In continuous mode, `async` reports activity as "virtual sessions" (based on idleness): after the first one, # it sends DONE and closes this exclusive management port, but keeps running: wait for its end, do not stop it. async_keeps_running = exec.eql?(:async) when 'ERROR' if /bearer token/i.match?(last_event['Description']) && !session[:token_regenerator].nil? # regenerate token here, expired, or error on it # Note: in multi-session, each session will have a different one. Log.log.warn('Regenerating token for transfer') env['ASPERA_SCP_TOKEN'] = session[:token_regenerator].call end raise Aspera::Transfer::Error.new(last_event['Description'], code: last_event['Code'].to_i) else # e.g. process was killed: like a lost connection (code 16), so that transfer is resumed raise Aspera::Transfer::Error.new("#{exec} ended without final status (last event: #{last_event['Type']})", code: 16) end rescue SystemCallError => e # Process.spawn failed, or socket error raise Aspera::Transfer::Error, e. rescue Interrupt raise Aspera::Transfer::Error, 'transfer interrupted by user' ensure mgt_server_socket&.close session.delete(:io) # if command was successfully started, check its status unless command_pid.nil? ::Process.kill(:INT, command_pid) if @monitor && !async_keeps_running && !Environment.instance.os.eql?(Environment::OS_WINDOWS) # collect process exit status or wait for termination _, status = ::Process.wait2(command_pid) if capture_stderr # process stderr of ascp stderr_flag = false stderr_r.each_line do |line| Log.log.error { "BEGIN stderr #{exec}" } unless stderr_flag Log.log.error { line.chomp } stderr_flag = true end Log.log.error { "END stderr #{exec}" } if stderr_flag stderr_r.close end # status is nil if an exception occurred before starting command if !status&.success? = "#{exec} failed (#{status})" # raise error only if there was not already an exception (`$ERROR_INFO`) raise Aspera::Transfer::Error, unless $ERROR_INFO # else display this message also, as main exception is already here Log.log.error() end end end nil end |
#start_transfer(transfer_spec, token_regenerator: nil) ⇒ Object
Start ascp transfer(s) (non blocking), single or multi-session
Session information added to @sessions
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 160 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/aspera/plugins/direct/agent.rb', line 131 def start_transfer(transfer_spec, token_regenerator: nil) # clone transfer spec because we modify it (first level keys) transfer_spec = transfer_spec.clone # if there are aspera tags if transfer_spec.dig('tags', Aspera::Transfer::Spec::TAG_RESERVED).is_a?(Hash) # TODO: what is this for ? only on local ascp ? # NOTE: important: transfer id must be unique: generate random id # using a non unique id results in discard of tags in AoC, and a package is never finalized # all sessions in a multi-session transfer must have the same xfer_id (see admin manual) transfer_spec['tags'][Aspera::Transfer::Spec::TAG_RESERVED]['xfer_id'] ||= SecureRandom.uuid Log.log.debug { "xfer id=#{transfer_spec['xfer_id']}" } # TODO: useful ? node only ? seems to be a timeout for retry in node transfer_spec['tags'][Aspera::Transfer::Spec::TAG_RESERVED]['xfer_retry'] ||= 3600 end Log.dump(:ts, transfer_spec) # Compute this before using transfer spec because it potentially modifies the transfer spec # (even if the var is not used in single session) multi_session_info = nil if transfer_spec.key?('multi_session') # Managed by multi-session, so delete from transfer spec multi_session_info = { count: transfer_spec.delete('multi_session').to_i } if multi_session_info[:count].negative? Log.log.error { "multi_session(#{transfer_spec['multi_session']}) shall be integer >= 0" } multi_session_info = nil elsif multi_session_info[:count].eql?(0) Log.log.debug('multi_session count is zero: no multi session') multi_session_info = nil elsif @multi_incr_udp # multi_session_info[:count] > 0 # if option not `true`: keep default UDP port for all sessions multi_session_info[:udp_base] = transfer_spec.key?('fasp_port') ? transfer_spec['fasp_port'] : Aspera::Transfer::Spec::UDP_PORT # delete from original transfer spec, as we will increment values transfer_spec.delete('fasp_port') # override if specified, else use default value end end # generic session information session = { id: nil, # SessionId from INIT message in mgt port job_id: SecureRandom.uuid, # job id (regroup sessions) ts: transfer_spec, # global transfer spec thread: nil, # Thread object monitoring management port, not nil when pushed to :sessions error: nil, # exception if failed io: nil, # management port server socket token_regenerator: token_regenerator, # regenerate bearer token with oauth progress_id: nil, # session identifier for progress, one per `ascp` process, same on resume size_sent: false, # `true` when total size was notified (PreTransferBytes) last_size: nil, # last notified transferred size skipped: 0, # size of whole files already at destination last_skipped: nil, # last notified size not transferred (already at destination) # env vars and args for ascp (from transfer spec) exec_spec: Aspera::Transfer::Parameters.new(transfer_spec, **@tr_opts).ascp_args } # Temporary files of `ascp` (file list) are deleted when the last session ends, # also after the end of the command (asynchronous transfer): hold them once per session, before any session starts (multi_session_info.nil? ? 1 : multi_session_info[:count]).times { TempFileManager.instance.hold(session[:exec_spec].temp_files) } if multi_session_info.nil? Log.log.debug('Starting single session thread') # single session for transfer : simple session[:thread] = Thread.new { transfer_thread_entry(session) } @sessions.push(session) else Log.log.debug('Starting multi session threads') 1.upto(multi_session_info[:count]) do |i| # do not delay the first session sleep(@spawn_delay_sec) unless i.eql?(1) # do deep copy (each thread has its own copy because it is modified here below and in thread) this_session = session.clone this_session[:ts] = this_session[:ts].clone exec_spec = this_session[:exec_spec] = this_session[:exec_spec].deep_clone # set multi session part exec_spec.args.unshift("-C#{i}:#{multi_session_info[:count]}") # option: increment (default as per ascp manual) or not (cluster on other side ?) exec_spec.args.unshift('-O', (multi_session_info[:udp_base] + i - 1).to_s) if @multi_incr_udp # finally start the thread this_session[:thread] = Thread.new { transfer_thread_entry(this_session) } @sessions.push(this_session) end end return session[:job_id] end |
#transfer_id ⇒ String?
Returns the job id: for transfer_status.
223 224 225 |
# File 'lib/aspera/plugins/direct/agent.rb', line 223 def transfer_id last_job_id end |
#wait_for_transfers_completion ⇒ Array
wait for completion of all jobs started
234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/aspera/plugins/direct/agent.rb', line 234 def wait_for_transfers_completion Log.log.debug('wait_for_transfers_completion') # set to non-nil to exit loop result = [] @sessions.each do |session| Log.log.debug { "join #{session[:thread]}" } session[:thread].join result.push(session[:error] || :success) end Log.log.debug('all transfers joined') # since all are finished and we return the result, clear statuses @sessions.clear return result end |