Class: Aspera::Agent::Direct
Overview
executes a local “ascp”, create mgt port
Instance Method Summary collapse
-
#initialize(ascp_args: nil, wss: true, quiet: true, trusted_certs: nil, client_ssh_key: nil, check_ignore_cb: nil, spawn_timeout_sec: 2, spawn_delay_sec: 2, multi_incr_udp: nil, resume: nil, monitor: true, management_cb: nil, **base_options) ⇒ Direct
constructor
options for initialize (same as values in option transfer_info).
-
#send_command(job_id, data) ⇒ Object
send command to management port of command (used in ‘asession) ’type’=>‘START’,‘source’=><em>path</em>,‘destination’=><em>path</em> ‘type’=>‘DONE’.
-
#sessions_by_job(job_id) ⇒ Array
List of sessions for a job.
-
#shutdown ⇒ Object
used by asession (to be removed ?).
-
#start_and_monitor_process(session:, env:, name:, args:) ⇒ nil
This is the low level method to start the transfer process.
-
#start_transfer(transfer_spec, token_regenerator: nil) ⇒ Object
start ascp transfer(s) (non blocking), single or multi-session session information added to @sessions.
-
#wait_for_transfers_completion ⇒ Object
wait for completion of all jobs started.
Methods inherited from Base
agent_list, factory_create, #wait_for_completion
Constructor Details
#initialize(ascp_args: nil, wss: true, quiet: true, trusted_certs: nil, client_ssh_key: nil, check_ignore_cb: nil, spawn_timeout_sec: 2, spawn_delay_sec: 2, multi_incr_udp: nil, resume: nil, monitor: true, management_cb: nil, **base_options) ⇒ Direct
options for initialize (same as values in option transfer_info)
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/aspera/agent/direct.rb', line 41 def initialize( ascp_args: nil, wss: true, quiet: true, trusted_certs: nil, client_ssh_key: nil, check_ignore_cb: nil, spawn_timeout_sec: 2, spawn_delay_sec: 2, multi_incr_udp: nil, resume: nil, monitor: true, management_cb: nil, ** ) super(**) # special transfer parameters @tr_opts = { ascp_args: ascp_args, wss: wss, quiet: quiet, 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.os.eql?(Environment::OS_WINDOWS) : multi_incr_udp @monitor = monitor @management_cb = management_cb @resume_policy = Resumer.new(resume.nil? ? {} : 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 @pre_calc_sent = false @pre_calc_last_size = nil end |
Instance Method Details
#send_command(job_id, data) ⇒ Object
send command to management port of command (used in ‘asession) ’type’=>‘START’,‘source’=><em>path</em>,‘destination’=><em>path</em> ‘type’=>‘DONE’
196 197 198 199 200 |
# File 'lib/aspera/agent/direct.rb', line 196 def send_command(job_id, data) session = @sessions.find{ |session| session[:job_id].eql?(job_id)} Log.log.debug{"command: #{data}"} session[:io].puts(Ascp::Management.command_to_stream(data)) end |
#sessions_by_job(job_id) ⇒ Array
Returns list of sessions for a job.
186 187 188 |
# File 'lib/aspera/agent/direct.rb', line 186 def sessions_by_job(job_id) @sessions.select{ |session| session[:job_id].eql?(job_id)} end |
#shutdown ⇒ Object
used by asession (to be removed ?)
181 182 183 |
# File 'lib/aspera/agent/direct.rb', line 181 def shutdown Log.log.debug('fasp local shutdown') end |
#start_and_monitor_process(session:, env:, name:, args:) ⇒ nil
This is the low level method to start the transfer process. Typically started in a thread. Start process with management port.
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 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 342 343 344 345 346 347 |
# File 'lib/aspera/agent/direct.rb', line 234 def start_and_monitor_process( session:, env:, name:, args: ) Aspera.assert_type(session, Hash) notify_progress(:pre_start, session_id: nil, info: 'starting') begin command_pid = nil command_arguments = [] 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 name.eql?(:async) ["--exclusive-mgmt-port=#{mgt_server_socket.local_address.ip_port}"] else ['-M', mgt_server_socket.local_address.ip_port.to_s] end end command_arguments.concat(args) # capture process stderr stderr_r, stderr_w = IO.pipe # get location of command executable (ascp, async) command_path = Ascp::Installation.instance.path(name) command_pid = Environment.secure_spawn(env: env, exec: command_path, args: command_arguments, err: stderr_w) stderr_w.close notify_progress(:pre_start, session_id: nil, info: "waiting for #{name} 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, exception_class: Transfer::Error){'timeout waiting mgt port connect (select not readable)'} # 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 = 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.log.trace1{Log.dump(:management_port, event)} # store session identifier session[:id] = event['SessionId'] if event['Type'].eql?('INIT') @management_cb&.call(event) process_progress(event) Log.log.error(event['Description'].to_s) if event['Type'].eql?('FILEERROR') # cspell:disable-line end Log.log.debug('management io closed') # check that last status was received before process exit last_event = processor.last_event raise Transfer::Error, "No management event (#{last_event.class})" unless last_event.is_a?(Hash) case last_event['Type'] when 'DONE' Log.log.trace1{'Graceful shutdown, DONE message received'} when 'ERROR' if /bearer token/i.match?(last_event['Description']) && session[:token_regenerator].respond_to?(:refreshed_transfer_token) # 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].refreshed_transfer_token end raise Transfer::Error.new(last_event['Description'], last_event['Code'].to_i) else Log.log.error{"unexpected last event type: #{last_event['Type']}"} # raise Transfer::Error, "unexpected last event type: #{last_event['Type']}, #{last_event['Description']}" end rescue SystemCallError => e # Process.spawn failed, or socket error raise Transfer::Error, e. rescue Interrupt raise 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 && !Environment.os.eql?(Environment::OS_WINDOWS) # collect process exit status or wait for termination _, status = Process.wait2(command_pid) # process stderr of ascp stderr_r.each_line do |line| Log.log.error(line.chomp) end stderr_r.close # status is nil if an exception occurred before starting command if !status&.success? = "#{name} failed (#{status})" # raise error only if there was not already an exception (ERROR_INFO) raise 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
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 126 127 128 129 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 160 161 |
# File 'lib/aspera/agent/direct.rb', line 85 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', 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'][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'][Transfer::Spec::TAG_RESERVED]['xfer_retry'] ||= 3600 end Log.log.debug{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'] : 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 # env vars and args for ascp (from transfer spec) env_args: Transfer::Parameters.new(transfer_spec, **@tr_opts).ascp_args } 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 env_args = this_session[:env_args] = this_session[:env_args].clone args = env_args[:args] = env_args[:args].clone # set multi session part args.unshift("-C#{i}:#{multi_session_info[:count]}") # option: increment (default as per ascp manual) or not (cluster on other side ?) 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 |
#wait_for_transfers_completion ⇒ Object
wait for completion of all jobs started
165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
# File 'lib/aspera/agent/direct.rb', line 165 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 |