Class: Aspera::Ascp::LogAnalyzer::Records

Inherits:
Object
  • Object
show all
Includes:
Lines
Defined in:
lib/aspera/ascp/log_analyzer/records.rb

Overview

Lines of an ascp log file parsed into records, with the field names of the log lines:

  • samples: Receiver bl or Sender bl line, merged with the DS Qs line that follows it
  • sessions: Session Start, Session Params, Session Stop and Session Statistics lines of a session, and the lines of the process about the session: license (Initializing FASP version), MTU and rate parameters of the peer
  • transfers: Transfer Start and Transfer Stop lines of a file Fields are described in schema ascp_log.

Constant Summary collapse

SCHEMAS =

Kind of record => schema

{
  samples:   "#{Schema::Registry::ASCP_LOG}:components.schemas.Sample",
  sessions:  "#{Schema::Registry::ASCP_LOG}:components.schemas.Session",
  transfers: "#{Schema::Registry::ASCP_LOG}:components.schemas.Transfer"
}.freeze
MESSAGE =

Message of a line of ascp: ascp[1234]: LOG <message> or [4c58-140234] LOG <message>

/\]:?\s+LOG\s+(.*?)\s*\z/
MESSAGES =

Line message => method called with (pid, time, MatchData)

{
  /\A(Receiver|Sender) (bl .*)/                                                                    => :sample_line,
  /\A(Receiver|Sender) DS (.*)/                                                                    => :queues_line,
  /\AFASP Session (Start|Stop) (.*)/                                                               => :session_line,
  /\AFASP Session Params (.*)/                                                                     => :params_line,
  /\AFASP Session Statistics \[\w+\] (.*)/                                                         => :statistics_line,
  /\AInitializing FASP version (.+?), license\b/                                                   => :initializing_line,
  /\AMeasured pMTU: (\d+) Bytes, start_brtt: (\d+) ms/                                             => :measured_mtu_line,
  /\Adatagram size (\d+)B, block size (\d+)B(?:, path MTU (\d+)B)?/                                => :datagram_line,
  /\APeer requested rate params adopted,\s+target_rate (\d+) min_rate (\d+) transfer_policy (\w+)/ => :peer_rate_params_line,
  /\AFASP Transfer (Start|Stop) (.*)/                                                              => :transfer_line
}.freeze
GROUP_FIELDS =

Group of a sample line: name k1/k2=v1/v2, or key=value alone

%r{(?<![A-Za-z_/])(?:([A-Za-z_]++)\s++)?([A-Za-z_]++(?:/[A-Za-z_]++)*+)=(-?\d++(?:/-?\d++)*+)}
MGMT_BACKLOG =

mgmt backlog i/s/n = 0/3/0 1/4/0 of DS Qs lines: one triplet per management socket

%r{mgmt backlog ([a-z/]++) =((?:\s++-?\d++(?:/-?\d++)*+)*+)}
PREFIXED =

[peer errcode=27 errstr="..."]: fields of the peer

/\[(\w+)\s+([^\]]*)\]/
KEY =
%r{([A-Za-z_][\w/]*)=}
QUOTED =

Value of key=value: quoted, in brackets, or up to the next key (it may contain spaces, e.g. ver=4.4.8.2596 b12cd13)

/"(.*?)"(?=\s|\z)/
BRACKETS =
/\[([^\]]*)\](?=\s|\z)/
UNQUOTED =
%r{.*?(?=\s+(?:\[\w+\s|[A-Za-z_][\w/]*=)|\s*\z)}
STATISTICS_GROUP =

Group of Session Statistics: (name: key value key value), or (name: value unit)

/\(([a-z ]+):\s*([^()]*)\)/
HIDDEN_FIELDS =

Never output: contains user names and emails

%w[cookie].freeze
SPLIT_KEYS =

Keys with a slash: name of each value

{'exclude_older/newer_than' => %w[exclude_older_than exclude_newer_than]}.freeze
NUMBER =

Number, with optional unit

/\A(-?\d+(?:\.\d+)?)\s*([KMG]?bps|ms|s|%)?\z/
RATE_UNITS =
{'Kbps' => 1e3, 'Mbps' => 1e6, 'Gbps' => 1e9}.freeze

Constants included from Lines

Lines::ASCP_LINE, Lines::HALF_YEAR, Lines::MONTHS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Lines

#ascp?

Constructor Details

#initialize(path, timezone: nil) ⇒ Records

Returns a new instance of Records.

Parameters:

  • path (String, StandardInput) —

    Log file, or standard input

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

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



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 231

def initialize(path, timezone: nil)
  @source = path
  # Name in results: `-` for the standard input
  @path = path.to_s
  @timezone = timezone
  @samples = []
  # uuid => session record
  @sessions = {}
  @transfers = []
  # PID => uuid of current session of process
  @uuids = {}
  # PID => last sample, until its `DS Qs` line
  @last_sample = {}
  # [uuid, file] => transfer record, until its `Transfer Stop` line
  @open_transfers = {}
  # PID => fields of lines logged before the `Session Start` line of the process
  @pending = {}
end

Instance Attribute Details

#path ⇒ String (readonly)

Returns Log file.

Returns:



225
226
227
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 225

def path
  @path
end

#samples ⇒ Array<Hash> (readonly)

Returns one record per sample of a session.

Returns:

  • (Array<Hash>) —

    one record per sample of a session



227
228
229
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 227

def samples
  @samples
end

Class Method Details

.add_field(fields, key, value) ⇒ Object

A key with a slash has one value per name: exclude_older/newer_than=0/0



169
170
171
172
173
174
175
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 169

def add_field(fields, key, value)
  if key.include?('/') && value.is_a?(String)
    SPLIT_KEYS.fetch(key) { key.split('/') }.zip(value.split('/')) { |name, part| fields[name] = part }
  else
    fields[key] = value
  end
end

.field_types(kind) ⇒ Hash{String => String}

Returns dot path of field => JSON type.

Parameters:

  • kind (Symbol) —

    One of the keys of SCHEMAS

Returns:



88
89
90
91
92
93
94
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 88

def field_types(kind)
  (@field_types ||= {})[kind] ||= {}.tap do |types|
    Schema::Registry.instance.reader(SCHEMAS[kind]).each_property do |schema, _name, full_name, _required|
      types[full_name] = schema.current['type']
    end
  end
end

.group_fields(text) ⇒ Hash

Returns name => => value, and key => value. A repeated group gets a number: bl, bl2.

Parameters:

  • text (String) —

    groups of a sample line: name k1/k2=v1/v2, or key=value

Returns:

  • (Hash) —

    name => => value, and key => value. A repeated group gets a number: bl, bl2



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 113

def group_fields(text)
  seen = Hash.new(0)
  text.scan(GROUP_FIELDS).each_with_object({}) do |(group, keys, numbers), result|
    values = keys.split('/').zip(numbers.split('/').map(&:to_i)).to_h
    if group.nil?
      result.merge!(values)
    else
      seen[group] += 1
      result[seen[group] > 1 ? "#{group}#{seen[group]}" : group] = values
    end
  end
end

.key_values(text) ⇒ Hash

Returns key => value (String), or Hash for brackets.

Parameters:

  • text (String) —

    key=value key="value" key=[k=v,k=v] [prefix key=value]

Returns:

  • (Hash) —

    key => value (String), or Hash for brackets



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
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 141

def key_values(text)
  fields = {}
  scanner = StringScanner.new(text)
  loop do
    scanner.skip(/\s+/)
    break if scanner.eos?
    if scanner.scan(PREFIXED)
      prefix = scanner[1]
      key_values(scanner[2]).each { |key, value| fields["#{prefix}_#{key}"] = value }
    elsif scanner.scan(KEY)
      key = scanner[1]
      value =
        if scanner.scan(QUOTED)
          scanner[1]
        elsif scanner.scan(BRACKETS)
          scanner[1].include?('=') ? scanner[1].split(',').to_h { |pair| pair.split('=', 2) } : scanner[1]
        else
          scanner.scan(UNQUOTED)
        end
      add_field(fields, key, value)
    else
      scanner.skip(/\S+/)
    end
  end
  fields.except(*HIDDEN_FIELDS)
end

.list(kind, paths, timezone: nil, readable: nil) ⇒ Array<Hash>

Returns records of all log files, with field log_file when there are several log files.

Parameters:

  • kind (Symbol) —

    One of the keys of SCHEMAS

  • paths (Array<String, StandardInput>) —

    Log files, standard input or folders

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

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

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

    For a folder: tells if a file or folder found in it can be read, see LogAnalyzer.log_paths

Returns:

  • (Array<Hash>) —

    records of all log files, with field log_file when there are several log files



76
77
78
79
80
81
82
83
84
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 76

def list(kind, paths, timezone: nil, readable: nil)
  Aspera.assert_values(kind, SCHEMAS.keys)
  LogAnalyzer.check_timezone(timezone)
  logs = paths.flat_map { |path| LogAnalyzer.load_logs(path, readable: readable) { |file| new(file, timezone: timezone).parse } }
  logs.flat_map do |log|
    rows = log.public_send(kind)
    logs.size > 1 ? rows.map { |row| {'log_file' => log.path}.merge(row) } : rows
  end
end

.pairs(tokens) ⇒ Hash

Returns key => value. A repeated key with a percentage: <key>_pct, e.g. lost 1 lost 1.47%.

Parameters:

  • tokens (Array<String>) —

    key value key value

Returns:

  • (Hash) —

    key => value. A repeated key with a percentage: <key>_pct, e.g. lost 1 lost 1.47%



199
200
201
202
203
204
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 199

def pairs(tokens)
  tokens.each_slice(2).with_object({}) do |(key, value), result|
    key = "#{key}_pct" if result.key?(key) && value.to_s.end_with?('%')
    result[key] = value
  end
end

.queues_fields(text) ⇒ Hash

Returns queue groups and mgmt_backlog array.

Parameters:

  • text (String) —

    Qs ... mgmt backlog ... of a DS Qs line

Returns:

  • (Hash) —

    queue groups and mgmt_backlog array



128
129
130
131
132
133
134
135
136
137
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 128

def queues_fields(text)
  backlog = text.match(MGMT_BACKLOG)
  text = backlog.pre_match + backlog.post_match if backlog
  queues = group_fields(text)
  if backlog
    keys = backlog[1].split('/')
    queues['mgmt_backlog'] = backlog[2].split.map { |values| keys.zip(values.split('/').map(&:to_i)).to_h }
  end
  queues
end

.statistics_fields(text) ⇒ Hash

Returns key => value, group => => value. Key of a->b.key: key.

Parameters:

  • text (String) —

    key=value, key value and (group: key value key value) of Session Statistics

Returns:

  • (Hash) —

    key => value, group => => value. Key of a->b.key: key



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 179

def statistics_fields(text)
  fields = {}
  scanner = StringScanner.new(text)
  loop do
    scanner.skip(/\s+/)
    break if scanner.eos?
    if scanner.scan(STATISTICS_GROUP)
      tokens = scanner[2].split
      fields[scanner[1].split.join('_')] = tokens.first&.match?(/\A-?\d/) ? tokens.first : pairs(tokens)
    elsif scanner.scan(/([^\s=]+)=(\S*)/) || scanner.scan(/(\S+)\s+(-?\d\S*)/)
      fields[scanner[1].split(/->|\./).last] = scanner[2]
    else
      scanner.skip(/\S+/)
    end
  end
  fields
end

.typed(fields, kind, prefix = '') ⇒ Hash

Returns values with the type of the field in the schema.

Parameters:

  • fields (Hash) —

    Values from log line (String)

  • kind (Symbol) —

    Kind of record

Returns:

  • (Hash) —

    values with the type of the field in the schema



209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 209

def typed(fields, kind, prefix = '')
  types = field_types(kind)
  fields.to_h do |key, value|
    path = "#{prefix}#{key}"
    value =
      case value
      when Hash then typed(value, kind, "#{path}.")
      when String then self.value(value, types[path])
      else value
      end
    [key, value]
  end
end

.value(text, type) ⇒ String, ...

Returns value: numbers in bps, ms, s or %, without unit.

Parameters:

  • text (String) —

    Value in log line

  • type (String, nil) —

    JSON type of field, nil if not in schema

Returns:

  • (String, Integer, Float) —

    value: numbers in bps, ms, s or %, without unit



99
100
101
102
103
104
105
106
107
108
109
# File 'lib/aspera/ascp/log_analyzer/records.rb', line 99

def value(text, type)
  return text if type.eql?('string')
  if type.nil?
    return text.to_i if text.match?(/\A-?\d+\z/)
    return text.to_f if text.match?(/\A-?\d+\.\d+\z/)
    return text
  end
  m = text.match(NUMBER) or return text
  number = m[1].to_f * RATE_UNITS.fetch(m[2], 1)
  type.eql?('integer') ? number.round : number
end

Instance Method Details

#parse ⇒ self

Read and parse the log file

Returns:

  • (self)


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

def parse
  LogAnalyzer.read_lines(@source, Encoding::UTF_8) do |line|
    line = line.scrub unless line.valid_encoding?
    parse_line(normalize(line))
  end
  self
end

#sessions ⇒ Array<Hash>

Returns one record per session.

Returns:

  • (Array<Hash>) —

    one record per session



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

def sessions
  @sessions.values.map(&:compact)
end

#transfers ⇒ Array<Hash>

Returns one record per transferred file.

Returns:

  • (Array<Hash>) —

    one record per transferred file



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

def transfers
  @transfers.map(&:compact)
end