Class: Aspera::Ascp::LogAnalyzer

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/ascp/log_analyzer.rb,
lib/aspera/ascp/log_analyzer/lines.rb,
lib/aspera/ascp/log_analyzer/rules.rb,
lib/aspera/ascp/log_analyzer/advice.rb,
lib/aspera/ascp/log_analyzer/records.rb,
lib/aspera/ascp/log_analyzer/session.rb,
lib/aspera/ascp/log_analyzer/log_file.rb,
lib/aspera/ascp/log_analyzer/diagnostics.rb

Overview

Analysis of ascp transfer logs: sessions, statistics and diagnostics. Results are tables: Hash (one object) or Array of Hash (list of objects).

Defined Under Namespace

Modules: Lines Classes: Diagnostics, LogFile, Records, Session

Constant Summary collapse

MIN_VERSION =

Oldest ascp version for which the analysis is designed

'4.0'
GZIP_MAGIC =

First two bytes of a gzip file

"\x1F\x8B".b.freeze
INCLUDED_FILES =

Files analyzed when scanning a folder

/transfer|messages|log/i
EXCLUDED_FILES =

Files not analyzed when scanning a folder (path relative to folder)

%r{async|ssl_|\.dat|\.xml|\.html|graph|winuser|manager|asperascp\.20|background|asws|node|plugin|opt/aspera/var|\.exe|trapd|rtf|lsass|lastlog|wtmp|
process|stats|production|mongrel|console|ntp\.|prepost|aspx|aspshell|tokengen|userdata|http|asconfigurator|ascmd|\.jpg|\.png|ui\.|connect|ssh|
stderr|stdout|central|sync|\.zip|\.msi|\.tgz|\.tbz|\.tar|\.rar|\.bz2?|\.pcap|analysis\.txt|\.7z}ix
EXCLUDED_FOLDERS =

Folders not scanned

/\$|recycle/i
SUMMED_STATS =

Statistics summed over log files

%i[total_sessions success failed cancelled http_fallback smart_reset win_clock retries] + LogFile::FINDINGS.keys
SEVERITIES =

Severities of diagnostics, most severe first

%w[error warning info].freeze
MAXIMA =

Maximum values of log files

{max_total: 'max_throughput', max_out: 'max_send', max_in: 'max_receive', max_sess: 'max_sessions'}.freeze
DEFAULT_THRESHOLDS =

Default diagnostic thresholds

{
  efficiency:                90.0,
  control_loss_percent:      5.0,
  control_loss_sent:         10,
  retry_window:              3600,
  last_error_window:         60,
  rate_decline_ratio:        0.7,
  rate_decline_min_samples:  10,
  rate_decline_delay:        20,
  rate_decline_end_fraction: 0.1,
  license_expiry_days:       30,
  small_files_min_count:     100,
  small_files_max_mean:      1_000_000,
  small_mtu_max:             1400
}.freeze
LINE_TIME =

Timestamp at beginning of log line: May 29 06:53:47 (syslog) or 2017-05-24 02:33:56 (log file)

/^((?:\w+\s+\d+|\d+-\d+-\d+)\s+\d\d:\d\d:\d\d)/
STAMP =

Timestamp of sessions and samples

/^(.*?(?:\s+\d+[^:])?\s+\d\d:\d\d:\d\d)/
PID =

Process identifier: ascp[1234] (syslog) or [4c58-140234] (log file: process-thread)

/^.*?\[(\w+)(?:-\w+)?\]/
LOG_ERROR =

Error message: ascp[1234]: ERR <message> or [4c58-140234] ERR <message>

/\]:?\s+ERR\s+(.+)/
PROCESS =

Process name in syslog line: host ascp[1234]: (none in ascp log files)

/\s([\w.-]+)\[\d+\]:/
ASCP_PROCESS =

Processes whose lines are analyzed (other processes: only time is used)

/\Aascp\d*\z/
IGNORED_TEXTS =

Lines that are never relevant: containing one of these texts, or matching

[
  'async[', 'LOG Queue:', 'snmpd', 'asconfigurator', 'asuserdata', 'message repeated', 'asperacentral', 'ERR Unrecognized FASP TLV',
  'LOG fdlimit set', 'astokengen', 'varation_index', 'LOG brtt', 'Action command:', 'meta_cmp_attrs:'
].freeze
IGNORED_LINES =
Regexp.union(/pulseaudio\[\d+\]/, /\s+DBG\s+/, /10061$/, /kernel:(?!\s*ascp)/, /sshd.*?Failed password/)
OTHER_PROCESSES =

Lines of other Aspera processes, when they contain the PID

/prepost|aspmover|aspsimplesync/
SESSION_START_STOP =
/#{STAMP.source}.*?Session\s+(Start|Stop)/
ERRSTR =
/errstr="([^"]*)"(?:.*?errstr="([^"]*)")?/
ERRCODE =

Error code and message of Session Stop: local, then peer

/errcode=(\d+) errstr="([^"]*)"/
CIPHERS =

Transport ciphers (FASP_TRANSPORT_CIPHER_* of ascp), by identifier

%w[none aes-128 aes-192 aes-256 aes-128-cfb aes-192-cfb aes-256-cfb aes-128-gcm aes-192-gcm aes-256-gcm].freeze
SESSION_PARAMS =

Session Params field => session data

{
  'user' => :user, 'targetrate' => :target_rate, 'minrate' => :min_rate, 'rate_policy' => :policy, 'cipher' => :secure,
  'resume' => :resume, 'ovr' => :overwrite, 'rd_sz' => :read_block_size, 'wr_sz' => :write_block_size,
  'xfer_id' => :xfer_id, 'cluster_num_nodes' => :cluster_nodes, 'cluster_node_id' => :cluster_node
}.freeze
LICENSE_RATE =

License in Initializing FASP version line: maximum rate in Mbps (none if unlimited), expiry date (none if no expiry)

/\bmax rate=(\d+) Mbps/
LICENSE_EXPIRES =
/\blicense expires on (\w{3} \w{3} +\d+ [\d:]+ \d{4})/
AS_BUF_IO =
/ERR as_buf_io:\s+IO/
SERVER_MGMT_RESET =
{set: %i[server_management_connection_reset], clear: %i[peer_abort]}.freeze
DATA_TIMEOUT =
%i[data_transfer_timeout].freeze
LINE_RULES =

Log line conditions, and their effect on the session. Only the first matching rule applies. match: Regexp, or Array of Regexp that must all match set: flags to set, clear: flags to clear, error: session error, status: session status unless: flags that cancel the effect, call: method of LogFile called with (session, MatchData) No effect: line is recognized, so that a later rule does not match it

[
  [/\sLOG (?:IBM )?(Aspera [\w -]+?) version \d/,                              {call: :product_name}],
  [/\sLOG ASPERA_AUTH_TOKEN is set to TOKEN/,                                  {call: :token_auth}],
  [/\sLOG Node storage access_key=/,                                           {call: :node_auth}],
  [/end File Transfer statistics/,                                            {call: :end_of_statistics}],
  [/(?:Receiver|Sender)\s+bl\b/,                                              {call: :add_sample}],
  [/LOG Falling back to HTTP/,                                                {set: %i[http_fallback]}],
  [/Transfer\s+Stop\s+(.*)/,                                                  {call: :transfer_stop}],
  [/base\s+RTT\s+reset/,                                                      {call: :brtt_reset}],
  [/(Peer requested|Negotiated) rate params.*?target_rate\s+(\d+)\s+min_rate\s+(\d+)\s+(?:transfer_)?policy\s+(\w+)/, {call: :rate_params}],
  [/pMTU:\s+(\d+).*?start_brtt:\s(\d+)/, {call: :path_mtu}],
  [/server configuration specifies transit encryption cipher (\d+), user requests (\d+)/, {call: :cipher_override}],
  [/Downgrading resume policy to (\S+)/, {call: :resume_downgrade}],
  [/changing session job size from (\d+) to (\d+) to match server configuration/, {call: :job_size_change}],
  [/vlink init: id=(\d+), type=(\w+), capacity=(\d+)/,                        {call: :vlink_init}],
  [/datagram size\s+(\d+)B, block size (\d+)B(?:, path MTU (\d+)B)?/,         {call: :datagram_size}],
  [/User aborted session/,                                                    {set: %i[user_abort]}],
  [/FASP session cancelled/,                                                  {set: %i[user_abort]}],
  [/ERR Server unable to hear from client/i,                                  {set: %i[server_nohear_client]}],
  [/ERR Client unable to connect to server/i,                                 {set: %i[client_nohear_server]}],
  [/ERR.*?Token expired\s+\d+\s+seconds ago/i,                                {set: %i[token_expired]}],
  [/ERR\s+Invalid argument/i,                                                 {set: %i[invalid_argument]}],
  [/ERR\sInvalid configuration file/i,                                        {set: %i[invalid_conf_file]}],
  [/ERR Disk read failed/i,                                                   {set: %i[read]}],
  [/ERR Disk write failed/i,                                                  {set: %i[write]}],
  [/Timeout receiving data \(60 sec\)/,                                       {set: %i[receiver_data_transfer_timeout] + DATA_TIMEOUT, error: 'Receiver data transfer timeout'}],
  [/Timeout establishing UDP connection/,                                     {set: %i[timeout_establishing_udp_connection]}],
  [/ERR failed to find a valid pair of \(pMTU, brtt\)/,                       {set: %i[timeout_establishing_udp_connection]}],
  [/bind udp socket failed/,                                                  {set: %i[bind_udp_socket_failed]}],
  [/ERR Sender network failure \(UDP recv got "No route to host"\)/,          {set: %i[send_no_route]}],
  [/Transmitter inactivity timer fired/,                                      {set: %i[inactivity_timer_fired] + DATA_TIMEOUT, error: 'Data transfer timeout - inactivity timer fired'}],
  [/fc_filewrite_sz:.*errno=11672/,                                           {set: %i[device_not_connected]}],
  [/fc_filewrite_sz:.*errno=(?:28|39|112)/,                                   {set: %i[out_of_disk]}],
  [/fc_filewrite_sz:.*errno=59/,                                              {set: %i[net_error]}],
  [/ReadFile failed.*error=53/,                                               {set: %i[net_path_not_found]}],
  [/fc_filewrite_sz:.*errno=64/,                                              {set: %i[net_name_gone]}],
  [/errno=1450/,                                                              {set: %i[out_of_resources]}],
  [/errcode\s+-2009/,                                                         {set: %i[decryption_error]}],
  [/Insufficient system resources/,                                           {set: %i[out_of_resources]}],
  [/ERR Could not open.*?errno 32/,                                           {set: %i[sharing_violation], error: 'Sharing violation'}],
  [/Insufficient permissions/,                                                {set: %i[insufficient_permissions], unless: %i[sharing_violation]}],
  [/ERR fc_create: failed to alloc cache/,                                    {set: %i[out_of_memory]}],
  [/ERR fc_filewrite_sz: Could not write cache bytes/,                        {set: %i[disk_write_failed]}],
  [/ERR Server requires content protection/,                                  {set: %i[content_protection]}],
  [/ERR required management connection to localhost:\d+/,                     {set: %i[cannot_connect_to_management_socket]}],
  [/ERR Failed to connect to management socket, exiting/,                     {set: %i[cannot_connect_to_management_socket], status: 'failed', error: 'Cannot connect to management socket'}],
  [/ERR aspera.conf parsing error\)?(.*)/,                                    {call: :conf_parse_error}],
  [/ERR\s+Mandatory management socket localhost:\d+, Connection reset by peer\s+\(server\)/, SERVER_MGMT_RESET],
  [/ERR.*?Mandatory management socket localhost:\d+, An existing connection was forcibly closed by the remote host.\s+\(server\)/, SERVER_MGMT_RESET],
  [/ERR Cannot read from management socket localhost.*?server/,               SERVER_MGMT_RESET],
  [/ERR\s+Server aborted session: Failed to connect to management socket/,    SERVER_MGMT_RESET],
  [/ERR\s+Cannot write to management socket\s+localhost:\d+.*?Broken pipe.*?server/, SERVER_MGMT_RESET],
  [/ERR\s+Cannot write to management socket\s+localhost:\d+.*?Broken pipe/, {}],
  [/ERR cannot write to management socket localhost:\d+, Unknown error \(server\)/, {set: %i[server_management_connection_reset]}],
  [/ERR\s+Cannot write to management socket localhost:\d+.*\(client\)/, {set: %i[client_management_connection_reset]}],
  [/ERR PEER ABORT: Received sesserr notification from peer, reason FASP_ABORT_LOCAL/, {set: %i[peer_abort]}],
  [/ERR Peer aborted session/,                                                {set: %i[peer_abort]}],
  [/ERR Mandatory management socket localhost:\d+, Connection reset by peer/, {}],
  [/ERR Cannot read from management socket localhost:\d+, Connection reset by peer/, {}],
  [/ERR Cannot read from management socket localhost.*?client/,               {set: %i[client_management_connection_lost]}],
  [/ERR Server aborted session: Cannot connect to management port localhost/, {set: %i[server_management_connection_reset]}],
  [[AS_BUF_IO, /errno=10054/],                                                {set: %i[remote_reset]}],
  [[AS_BUF_IO, /errno=10053/],                                                {set: %i[local_reset]}],
  [[AS_BUF_IO, /errno=10055/],                                                {set: %i[no_buffer_mem], error: 'Out of buffer memory'}],
  [AS_BUF_IO,                                                                 {set: %i[as_buf_io]}],
  [/ERR Connection lost in midst of data session/,                            {set: %i[ssh_timeout]}],
  [/\[asssh\] SSH connection startup failed/,                                 {set: %i[ssh_startup_failed]}],
  [/\[asssh\] failure during public-key authentication/,                      {set: %i[ssh_key_authentication]}],
  [/\[asssh\] SSH session open failed/,                                       {set: %i[ssh_session_failed]}],
  [/Failed to start remote command, libssh2 result/,                          {set: %i[ssh_command_failed]}],
  [%r{\[asssh\] Remote failed to forward TCP/IP},                             {set: %i[ssh_forward_failed]}],
  [/\[asssh\] (?:channel|session) [a-z ]+ rc=-?\d+/,                          {call: :ssh_disconnect_error}],
  [/speed exceeded/,                                                          {set: %i[exceeded]}],
  [/segfault/,                                                                {call: :segfault}],
  [/(Receiver|Sender) has not received a packet for (\d+) seconds/,           {call: :no_data}],
  [/ERR \S*ossl-modules not found/,                                           {set: %i[ossl_modules_missing]}],
  [/ERR Warning: unable to submit change event/,                              {set: %i[change_event_failed]}],
  [/Warning: rex timer overflow auto-adjusted/,                               {call: :rex_timer_overflow}],
  [/\bFASP Session Statistics \[\w+\] (.*)/,                                  {call: :session_statistics}]
].freeze
UNDEFINED_ERROR_RULES =

When the session stop error is Undefined: first matching flag sets the error

[
  [%i[invalid_conf_file], {}],
  [%i[send_no_route],     {error: 'No route to host'}],
  [%i[peer_abort],        {error: 'Peer aborted session'}]
].freeze
ERROR_REFINEMENTS =

Session stop errors of failed sessions, refined with flags: first matching rule applies

{
  'No error' => [
    [%i[write],                              {error: 'Disk write failed'}],
    [%i[client_management_connection_reset], {error: 'Client connection to management socket reset'}],
    [%i[client_management_connection_lost],  {error: 'Client management connection lost'}],
    [%i[user_abort],                         {error: 'User aborted session'}],
    [%i[peer_abort],                         {error: 'Peer aborted session'}]
  ]
}.freeze
SAMPLE =

Sample lines: Receiver bl t/o/r/d/ts/c/h=1/2/3/4/5/6/7 rex_rtt l/h/s/o=...: group, field names, values

/#{STAMP.source}.*?\[(\w+)(?:-\w+)?\].*?(Receiver|Sender)\s+(bl\b.*)/
SAMPLE_COMMON =

Sample value => path in sample records

{
  blocks: %w[bl t], orig: %w[bl o], rex: %w[bl r], target_rate: %w[rate t], min_rate: %w[rate m], calc_rate: %w[rate c],
  tx_bytes: %w[prog t], written: %w[prog f], elapsed_us: %w[prog e]
}.freeze
RECEIVER_SAMPLE =
SAMPLE_COMMON.merge(
  rex_srtt: %w[rex_rtt s], brtt: %w[rate_rtt b], rtt_high: %w[rate_rtt h], srtt: %w[rate_rtt s], brtt_resets: %w[rate_rtt r],
  rex_count: %w[rex n], lost: %w[bl2 l], ooo: %w[bl2 o], ring_high: %w[disk h], ring_full: %w[disk b],
  net_rate: %w[rate n], vlink_local: %w[rate vl], vlink_remote: %w[rate vr], disk_rate: %w[rate r]
).freeze
SENDER_SAMPLE =

Sender: rates of the receiver (ascp 4): network, virtual links, disk

SAMPLE_COMMON.merge(
  rex_received: %w[rex b], rex_count: %w[rex n],
  peer_net_rate: %w[rate n], peer_vlink_local: %w[rate vl], peer_vlink_remote: %w[rate vr], peer_disk_rate: %w[rate r]
).freeze
RECOMMENDATIONS =

Diagnostic identifier => action to take (English text, like messages of diagnostics). Only for diagnostics on which the user can act. See also NO_RECOMMENDATION. Not for error_<category> (the message of the diagnostic is already the hint for the category of the error: SessionErrors::CATEGORIES).

{
  client_nohear_server:                udp_port,
  server_nohear_client:                udp_port,
  timeout_establishing_udp_connection: udp_port,
  http_fallback:                       "The transfer used HTTP instead of UDP, which is slower (unless forced with option `-yF` of `ascp`). #{udp_port}",
  receiver_data_transfer_timeout:      udp_flow,
  inactivity_timer_fired:              udp_flow,
  reception_interruption:              udp_flow,
  udp_flood_protection:                "Check the UDP flood protection of firewalls, and the rate limits of the path. #{lower_rate}",
  low_efficiency:                      "Retransmissions come from packet loss. #{lower_rate}",
  network_overdriven:                  "#{lower_rate} Check the path for a device that limits or polices the rate.",
  network_overdrive:                   "#{lower_rate} Check the path for shallow queues, or a device that limits the rate of UDP.",
  retransmission_buffer_full:          "#{lower_rate} Check the path for a device that limits or polices the rate.",
  control_message_loss:                "Control messages travel over UDP: their loss shows packet loss on the path. #{lower_rate}",
  feedback_interruption:               udp_flow,
  rex_timer_overflow:                  "The retransmission RTT was excessive: check the path for deep queues, congestion or a clock problem. #{lower_rate}",
  license_rate_limit:                  'Use a license with a higher maximum rate on this system (contact your IBM Aspera representative), or set the target rate to the limit of the license ' \
    '(option `-l` of `ascp`, or `target_rate` in `bandwidth/flow` of `aspera.conf`).',
  license_expiry:                      'Renew the license of this system before its expiry date (contact your IBM Aspera representative).',
  stuck_nack:                          "Packet loss prevents the retransmission requests from being served. #{lower_rate}",
  min_rate_high:                       lower_min,
  min_rate_overdrive:                  lower_min,
  slow_storage_loss:                   storage_write,
  slow_disk_write:                     storage_write,
  disk_buffers:                        storage_write,
  disk_write_speed_exceeded:           storage_write,
  storage_overdrive:                   storage_write,
  slow_storage_read:                   'Check the read speed of the storage of the sender. Read parameters can be tuned: `read_threads` and `read_block_size` in `file_system` of `aspera.conf`, option `-g` of `ascp`.',
  rate_decline:                        "Check for other traffic on the link, and for slow storage on the receiver. #{lower_rate}",
  small_files:                         'Aggregate small files into archives before transfer (`-A zip` of `ascp`), or use a protocol that amortizes the per-file overhead (e.g., HTTP/2 multipart). ' \
    'For many small files, enable concurrent file opens: `write_threads` in `file_system` of `aspera.conf`.',
  small_mtu:                           'Small packets raise the packet rate and the CPU load of ascp. Check whether the path goes through a VPN or tunnel, and raise its MTU; ' \
    'or check that no device drops the large UDP probes (`ascp` probes 1492 bytes first). To force the datagram size: option `-Z` of `ascp`, or `datagram_size` in `transfer/protocol_options` of `aspera.conf`.',
  reverse_path_skew:                   'If the network is not congested, set `rtt_reverse_infer` to `false` in `transfer/protocol_options` of `aspera.conf`: each peer reads its own `aspera.conf`.',
  clock_problem:                       'Set `rtt_autocorrect` to `true` in `transfer/protocol_options` of `aspera.conf` (auto-correction of the base RTT, for virtual machines), and check the clock of the virtual machine.',
  peer_clock_problem:                  'Ask the administrator of the peer to set `rtt_autocorrect` to `true` in `transfer/protocol_options` of `aspera.conf` (auto-correction of the base RTT, for virtual machines).',
  token_expired:                       'Generate a new token (option `-W` of `ascp`) just before the transfer, and check that the clocks of the system that generates tokens and of the server are synchronized.',
  content_protection:                  'Encrypt files at rest: option `--file-crypt=encrypt` of `ascp`, with the passphrase in environment variable `ASPERA_SCP_FILEPASS`. ' \
    'The server requires it with `content_protection_required` in `transfer/encryption` of `aspera.conf`.',
  insufficient_permissions:            'Check the permissions of the transfer user on the file (operating system), and the access rules of the server: `read_allowed` and `write_allowed` in `file_system/access/paths/path` of `aspera.conf`.',
  out_of_disk:                         'Free space on the destination storage, or check its quota, then retry the transfer with resume (option `-k` of `ascp`).',
  read:                                storage_access,
  write:                               storage_access,
  disk_write_failed:                   storage_access,
  device_not_connected:                network_storage,
  net_error:                           network_storage,
  net_path_not_found:                  network_storage,
  net_name_gone:                       network_storage,
  sharing_violation:                   'Another process (e.g. antivirus, indexer or application) uses the file: close it or exclude the folder from its scan, then retry.',
  out_of_resources:                    'Check the resources of the Windows system (memory, handles) and reduce the number of concurrent transfers.',
  out_of_memory:                       'Check the free memory of the system and reduce the number of concurrent transfers.',
  no_buffer_mem:                       'Reduce the number of concurrent transfers, or the size of UDP socket buffers (`max_sock_buffer` in `transfer/protocol_options` of `aspera.conf`).',
  bind_udp_socket_failed:              'Check that the UDP port (`bind_udp_port`) and the address (`bind_ip_address`) in `transfer/protocol_options` of `aspera.conf` are valid for this system, ' \
    'and that the process is allowed to use them. The error number is in the log line.',
  configuration_error:                 'Correct `aspera.conf` on the system that logged the error (XML syntax and values), or use another file with option `-f` of `ascp`.',
  filename_too_long:                   'Shorten the destination path or the file names, so that the Windows path is not longer than 260 characters.',
  remote_reset:                        tcp_connection,
  ssh_timeout:                         tcp_connection,
  ssh_session_died:                    tcp_connection,
  local_reset:                         'Check the firewall, antivirus and network drivers of this system: they may reset TCP connections.',
  ssh_startup_failed:                  'Check the host name, the TCP port of SSH (option `-P` of `ascp`, `ssh_port` of the server) and the firewalls. ' \
    'Test with option `--mode=test-login` of `ascp`. On a slow network, `ssh_startup_timeout_sec` in `aspera.conf` sets the connection timeout.',
  ssh_key_authentication:              'Check the private key (option `-i` of `ascp`) or the password (environment variable `ASPERA_SCP_PASS`), and that the user is allowed to connect to the server.',
  ssh_session_failed:                  'Check that the SSH server accepts new sessions (load, limits), then retry. Test with option `--mode=test-login` of `ascp`.',
  ssh_command_failed:                  'Check that the user is configured for Aspera on the server (`aspshell`), and the name of the remote command (option `-S` of `ascp`).',
  ssh_forward_failed:                  'Check that the SSH server allows TCP forwarding for the user (e.g. `AllowTcpForwarding` in `sshd_config`).'
}.freeze
NO_RECOMMENDATION =

Identifiers of Session::FLAG_DIAGNOSTICS without recommendation: nothing to do

%w[user_abort table_died].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(period: 60, zero_bytes: false, mtu: nil, resolve: false, thresholds: {}, timezone: nil) ⇒ LogAnalyzer

Returns a new instance of LogAnalyzer.

Parameters:

  • period (Integer) (defaults to: 60) —

    Snapshot period in seconds

  • zero_bytes (Boolean) (defaults to: false) —

    Include sessions without transferred bytes

  • mtu (Integer, nil) (defaults to: nil) —

    MTU to use when not found in logs

  • resolve (Boolean) (defaults to: false) —

    Resolve peer addresses to host names

  • thresholds (Hash) (defaults to: {}) —

    Diagnostic thresholds

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

    Time zone of the log lines: UTC or +HH:MM. Time zone of the analyst if nil.



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/aspera/ascp/log_analyzer.rb', line 68

def initialize(period: 60, zero_bytes: false, mtu: nil, resolve: false, thresholds: {}, timezone: nil)
  self.class.check_timezone(timezone)
  @timezone = timezone
  thresholds = thresholds.transform_keys(&:to_sym)
  unknown = thresholds.keys - DEFAULT_THRESHOLDS.keys
  Aspera.assert(unknown.empty?, type: ArgumentError) { "Unknown threshold: #{unknown.join(', ')}" }
  @thresholds = DEFAULT_THRESHOLDS.merge(thresholds)
  @options = {period: period, zero_bytes: zero_bytes, mtu: mtu, thresholds: @thresholds, timezone: timezone}
  @resolve = resolve
  @log_files = []
end

Instance Attribute Details

#log_files ⇒ Array<LogFile> (readonly)

Returns analyzed log files.

Returns:

  • (Array<LogFile>) —

    analyzed log files



60
61
62
# File 'lib/aspera/ascp/log_analyzer.rb', line 60

def log_files
  @log_files
end

#thresholds ⇒ Array<LogFile> (readonly)

Returns analyzed log files.

Returns:

  • (Array<LogFile>) —

    analyzed log files



60
61
62
# File 'lib/aspera/ascp/log_analyzer.rb', line 60

def thresholds
  @thresholds
end

Class Method Details

.ascp_log?(path) ⇒ Boolean

Reads the file up to its first ascp line only

Parameters:

  • path (String) —

    log file, plain or compressed with gzip

Returns:

  • (Boolean) —

    true if the file contains ascp log lines



149
150
151
152
153
154
# File 'lib/aspera/ascp/log_analyzer.rb', line 149

def ascp_log?(path)
  read_lines(path, Encoding::BINARY) { |line| return true if line.match?(Lines::ASCP_LINE) }
  false
rescue Zlib::Error, Errno::EPIPE
  false
end

.check_timezone(timezone) ⇒ Object

Parameters:

  • timezone (String, nil) —

    Time zone of the log lines: UTC or +HH:MM

Raises:



83
84
85
86
87
88
# File 'lib/aspera/ascp/log_analyzer.rb', line 83

def check_timezone(timezone)
  return if timezone.nil?
  Time.at(0, in: timezone)
rescue ArgumentError
  raise ParameterError, "Invalid time zone: #{timezone.inspect}, expected `UTC` or `+HH:MM`"
end

.folder?(path) ⇒ Boolean

Returns true if it is a folder.

Parameters:

Returns:

  • (Boolean) —

    true if it is a folder



92
# File 'lib/aspera/ascp/log_analyzer.rb', line 92

def folder?(path) = path.is_a?(String) && File.directory?(path)

.load_logs(path, readable: nil) {|file| ... } ⇒ Array

Load the log files of a path In a folder, a file that is not an ascp log is ignored. A file given explicitly must be an ascp log.

Parameters:

  • path (String, StandardInput) —

    log file, standard input, or folder

  • readable (#call, nil) (defaults to: nil) —

    see log_paths

Yield Parameters:

Yield Returns:

  • (#ascp?) —

    the loaded log

Returns:

  • (Array) —

    the loaded logs that are ascp logs



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/aspera/ascp/log_analyzer.rb', line 130

def load_logs(path, readable: nil)
  explicit = !folder?(path)
  log_paths(path, readable: readable).filter_map do |file|
    log = yield(file)
    next log if log.ascp?
    Aspera.assert(!explicit, type: ParameterError) { "Not an ascp log: #{file}" }
    Log.log.debug { "Ignored, not an ascp log: #{file}" }
    nil
  rescue Zlib::Error, Errno::EPIPE => e
    # JRuby raises Errno::EPIPE (instead of Zlib::Error) on truncated gzip input
    raise ParameterError, "Cannot read #{file}: #{e.message}" if explicit
    Log.log.warn("Ignored, cannot read #{file}: #{e.message}")
    nil
  end
end

.log_paths(path, readable: nil) ⇒ Array<String, StandardInput>

Returns the log file (or standard input), or the log files in the folder (recursively).

Parameters:

  • path (String, StandardInput) —

    log file, standard input, or folder

  • readable (#call, nil) (defaults to: nil) —

    For a folder: tells if a file or folder found in it can be read (e.g. it is in the allowed paths of the caller, also through a symbolic link), else it is skipped. nil: all are read.

Returns:

  • (Array<String, StandardInput>) —

    the log file (or standard input), or the log files in the folder (recursively)



98
99
100
101
# File 'lib/aspera/ascp/log_analyzer.rb', line 98

def log_paths(path, readable: nil)
  return [path] unless folder?(path)
  without_links(scan_folder(path, path, [], readable))
end

.read_lines(path, encoding) {|line| ... } ⇒ Object

Read the lines of a log file: plain, or compressed with gzip (detected with its first bytes)

Parameters:

  • path (String, StandardInput) —

    Log file, or the standard input

  • encoding (Encoding) —

    Encoding of lines

Yield Parameters:



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/aspera/ascp/log_analyzer.rb', line 107

def read_lines(path, encoding, &block)
  io =
    case path
    when StandardInput then StringIO.new(path.read)
    when String then File.open(path, 'rb')
    else Aspera.error_unexpected_value(path.class) { 'log file' }
    end
  gzip = io.read(2) == GZIP_MAGIC
  io.rewind
  io = Zlib::GzipReader.new(io, external_encoding: encoding) if gzip
  io.set_encoding(encoding) unless gzip
  io.each_line(&block)
ensure
  io&.close
end

Instance Method Details

#add(path, readable: nil) ⇒ self

Analyze a log file, or the log files in a folder (recursively)

Parameters:

  • path (String, StandardInput) —

    file, standard input or folder

  • readable (#call, nil) (defaults to: nil) —

    see log_paths

Returns:

  • (self)


207
208
209
210
# File 'lib/aspera/ascp/log_analyzer.rb', line 207

def add(path, readable: nil)
  @log_files.concat(self.class.load_logs(path, readable: readable) { |file| LogFile.new(file, **@options).analyze })
  self
end

#diagnostics ⇒ Array<Hash>

Returns one row per diagnostic of sessions: id, severity, message, recommendation (if the diagnostic has one).

Returns:

  • (Array<Hash>) —

    one row per diagnostic of sessions: id, severity, message, recommendation (if the diagnostic has one)



267
268
269
# File 'lib/aspera/ascp/log_analyzer.rb', line 267

def diagnostics
  single_file(@log_files.flat_map(&:diagnostics))
end

#licenses ⇒ Array<Hash>

Returns licenses of local and peer systems.

Returns:

  • (Array<Hash>) —

    licenses of local and peer systems



332
333
334
335
336
337
338
# File 'lib/aspera/ascp/log_analyzer.rb', line 332

def licenses
  @log_files.each_with_object({}) do |log, all|
    log.licenses.each { |key, license| all[key] = license.merge(file: log.path) }
  end.map do |(number, address), license|
    {'license' => number, 'address' => address, 'product' => license[:product], 'account' => license[:account], 'os' => license[:os], 'file' => license[:file]}.compact
  end
end

#multi_sessions ⇒ Array<Hash>

Returns one row per multi-session transfer.

Returns:

  • (Array<Hash>) —

    one row per multi-session transfer



272
273
274
# File 'lib/aspera/ascp/log_analyzer.rb', line 272

def multi_sessions
  single_file(@log_files.flat_map(&:multi_sessions))
end

#overdrives ⇒ Array<Hash>

Returns by peer: number of sessions with loss due to overdriving of network (shallow queues) or storage.

Returns:

  • (Array<Hash>) —

    by peer: number of sessions with loss due to overdriving of network (shallow queues) or storage



341
342
343
344
345
346
347
348
349
350
# File 'lib/aspera/ascp/log_analyzer.rb', line 341

def overdrives
  counts = Hash.new(0)
  each_session do |_, s|
    cause = s.overdrive
    counts[[s[:peer], cause]] += 1 if cause
  end
  counts.sort_by { |_, count| -count }.map do |(peer, cause), count|
    {'peer' => peer, 'cause' => cause.to_s, 'occurrences' => count}.merge(hostname(peer))
  end
end

#peers ⇒ Array<Hash>

Returns sessions and errors by peer address, most failures first.

Returns:

  • (Array<Hash>) —

    sessions and errors by peer address, most failures first



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/aspera/ascp/log_analyzer.rb', line 287

def peers
  rows = {}
  each_session do |_, s|
    peer = s[:peer] or next
    row = (rows[peer] ||= {'peer' => peer, 'users' => Set.new, 'sessions' => 0, 'success' => 0, 'failed' => 0, 'cancelled' => 0, 'errors' => Hash.new(0)})
    row['users'].add(s[:user]) if s[:user]
    row['sessions'] += 1
    case s[:status]
    when 'success' then row['success'] += 1
    when 'failed'
      row[s[:error].to_s.match?(/cancelled/i) ? 'cancelled' : 'failed'] += 1
      row['errors'][s[:error]] += 1 if s[:error]
    end
  end
  rows.values.sort_by { |row| -row['failed'] }.map do |row|
    row.merge('users' => row['users'].to_a, 'errors' => row['errors'].to_h).merge(hostname(row['peer']))
  end
end

#sessions ⇒ Array<Hash>

Returns one row per session, with the other side if its log is also analyzed.

Returns:

  • (Array<Hash>) —

    one row per session, with the other side if its log is also analyzed



260
261
262
263
264
# File 'lib/aspera/ascp/log_analyzer.rb', line 260

def sessions
  rows = @log_files.flat_map(&:session_reports)
  join_sides(rows)
  single_file(rows)
end

#snapshot_sessions ⇒ Array<Hash>

Returns one row per session in each snapshot period.

Returns:

  • (Array<Hash>) —

    one row per session in each snapshot period



282
283
284
# File 'lib/aspera/ascp/log_analyzer.rb', line 282

def snapshot_sessions
  single_file(@log_files.flat_map(&:snapshot_sessions))
end

#snapshots ⇒ Array<Hash>

Returns one row per snapshot period: aggregate rates.

Returns:

  • (Array<Hash>) —

    one row per snapshot period: aggregate rates



277
278
279
# File 'lib/aspera/ascp/log_analyzer.rb', line 277

def snapshots
  single_file(@log_files.flat_map(&:snapshots))
end

#summary ⇒ Hash

Returns statistics over all log files.

Returns:

  • (Hash) —

    statistics over all log files



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
245
246
247
248
249
250
# File 'lib/aspera/ascp/log_analyzer.rb', line 213

def summary
  stats = Hash.new(0)
  errors = Hash.new(0)
  categories = Hash.new(0)
  result = {}
  @log_files.each do |log|
    SUMMED_STATS.each { |key| stats[key] += log.stats[key] }
    stats[:stuck_nack_loss] = [stats[:stuck_nack_loss], log.stats[:stuck_nack_loss]].max
    log.stats[:errors].each { |error, count| errors[error] += count }
    log.stats[:error_categories].each { |category, count| categories[category] += count }
    MAXIMA.each do |key, name|
      next if log.stats[key] <= result.fetch(name, 0)
      result[name] = log.stats[key]
      result["#{name}_time"] = iso(log.stats[:"#{key}_time"])
    end
  end
  first = @log_files.filter_map(&:first_time).min
  last = @log_files.filter_map(&:last_time).max
  {
    'files'            => @log_files.size,
    'first_log'        => iso(first),
    'last_log'         => iso(last),
    'sessions'         => stats[:total_sessions],
    'success'          => stats[:success],
    'failed'           => stats[:failed],
    'cancelled'        => stats[:cancelled],
    'success_rate'     => ((100.0 * (stats[:total_sessions] - stats[:failed]) / stats[:total_sessions]).round(2) if stats[:total_sessions].positive?),
    'http_fallback'    => stats[:http_fallback],
    'retries'          => stats[:retries],
    'multi_session'    => @log_files.sum { |log| log.multi_sessions.size },
    'errors'           => errors.sort_by { |_, count| -count }.to_h,
    'error_categories' => categories.sort_by { |_, count| -count }.to_h,
    'diagnostics'      => SEVERITIES.to_h { |severity| [severity, 0] }.merge(diagnostics.map { |row| row['severity'] }.tally).reject { |_, count| count.zero? }
  }.merge(result).merge(
    'findings' => LogFile.findings(stats),
    'warnings' => warnings
  ).compact
end

#transfers ⇒ Array<Hash>

Returns one row per transferred file.

Returns:

  • (Array<Hash>) —

    one row per transferred file



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/aspera/ascp/log_analyzer.rb', line 307

def transfers
  result = []
  each_session do |log, s|
    s.files.each do |name, file|
      result.push({
        'file'        => log.path,
        'session'     => s[:uuid],
        'pid'         => s.pid,
        'user'        => s[:user],
        'peer'        => s[:peer],
        'destination' => s[:dest],
        'start'       => iso(s[:start]),
        'stop'        => iso(s[:stop]),
        'path'        => name,
        'direction'   => file[:op] == 'recv' ? 'receive' : file[:op],
        'size'        => file[:size],
        'status'      => file[:status],
        'error'       => file[:error]
      }.compact)
    end
  end
  single_file(result)
end

#warnings ⇒ Array<String>

Returns warnings about log files.

Returns:

  • (Array<String>) —

    warnings about log files



253
254
255
256
257
# File 'lib/aspera/ascp/log_analyzer.rb', line 253

def warnings
  @log_files.flat_map do |log|
    log.old_versions.map { |version| "#{log.path}: ascp #{version} is older than #{MIN_VERSION}, analysis may be inaccurate" }
  end
end