Class: Aspera::Agent::Direct

Inherits:
Base
  • Object
show all
Defined in:
lib/aspera/agent/direct.rb

Overview

executes a local “ascp”, connects mgt port, equivalent of “Fasp Manager”

Constant Summary

Constants inherited from Base

Base::RUBY_EXT

Instance Method Summary collapse

Methods inherited from Base

agent_list, factory_create, to_move_options, #wait_for_completion

Instance Method Details

#sessions_by_job(job_id) ⇒ Array

Returns list of sessions for a job.

Returns:

  • (Array)

    list of sessions for a job



134
135
136
# File 'lib/aspera/agent/direct.rb', line 134

def sessions_by_job(job_id)
  @sessions.select{|session_info| session_info[:job_id].eql?(job_id)}
end

#shutdownObject

used by asession (to be removed ?)



129
130
131
# File 'lib/aspera/agent/direct.rb', line 129

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 Start process with management port. returns raises FaspError on error

Parameters:

  • session

    this session information, keys :io and :token_regenerator

  • env (Hash)

    environment variables

  • name (Symbol)

    name of executable: :ascp, :ascp4 or :async

  • args (Array)

    command line arguments

Returns:

  • (nil)

    when process has exited



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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/aspera/agent/direct.rb', line 147

def start_and_monitor_process(
  session:,
  env:,
  name:,
  args:
)
  Aspera.assert_type(session, Hash)
  notify_progress(session_id: nil, type: :pre_start, info: 'starting')
  begin
    command_pid = nil
    # 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))
    # 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
    command_arguments.concat(args)
    # 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)
    notify_progress(session_id: nil, type: :pre_start, info: "waiting for #{name} to start")
    mgt_server_socket.listen(1)
    # TODO: timeout does not work when Process.spawn is used... until process exits, then it works
    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
    # management messages include file names which may be utf8
    # by default socket is US-ASCII
    # 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)}
      @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')
    last_event = processor.last_event
    # check that last status was received before process exit
    if last_event.is_a?(Hash)
      case last_event['Type']
      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)
      when 'DONE'
        nil
      else
        raise "unexpected last event type: #{last_event['Type']}"
      end
    end
  rescue SystemCallError => e
    # Process.spawn failed, or socket error
    raise Transfer::Error, e.message
  rescue Interrupt
    raise Transfer::Error, 'transfer interrupted by user'
  ensure
    mgt_server_socket.close
    # if command was successfully started, check its status
    unless command_pid.nil?
      # "wait" for process to avoid zombie
      Process.wait(command_pid)
      status = $CHILD_STATUS
      # command_pid = nil
      session.delete(:io)
      # status is nil if an exception occurred before starting command
      if !status&.success?
        message = status.nil? ? "#{name} not started" : "#{name} failed (#{status})"
        # raise error only if there was not already an exception (ERROR_INFO)
        raise Transfer::Error, message unless $ERROR_INFO
        # else display this message also, as main exception is already here
        Log.log.error(message)
      end
    end
  end
  nil
end

#start_transfer(transfer_spec, token_regenerator: nil) ⇒ Object

method of Base start ascp transfer(s) (non blocking), single or multi-session session information added to @sessions

Parameters:

  • transfer_spec (Hash)

    aspera transfer specification

  • token_regenerator (Object) (defaults to: nil)

    object with method refreshed_transfer_token



32
33
34
35
36
37
38
39
40
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
80
81
82
83
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
# File 'lib/aspera/agent/direct.rb', line 32

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')
    multi_session_info = {
      count: transfer_spec['multi_session'].to_i
    }
    # Managed by multi-session, so delete from transfer spec
    transfer_spec.delete('multi_session')
    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,     # 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 to 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(session) {|session_info|transfer_thread_entry(session_info)}
    @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(this_session) {|session_info|transfer_thread_entry(session_info)}
      @sessions.push(this_session)
    end
  end
  return session[:job_id]
end

#wait_for_transfers_completionObject

wait for completion of all jobs started

Returns:

  • list of :success or error message



113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/aspera/agent/direct.rb', line 113

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