Method: Jkr::DataUtils#parse_block

Defined in:
lib/jkr/userutils.rb

#parse_block(block, opt) ⇒ Object



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
# File 'lib/jkr/userutils.rb', line 368

def parse_block(block, opt)
  y = opt[:start_time].year
  m = opt[:start_time].month
  d = opt[:start_time].day

  lines = block.lines.map(&:strip)
  head_line = lines.shift

  unless head_line =~ /(\d{2}):(\d{2}):(\d{2})/
    raise ArgumentError.new("Invalid top(3) data")
  end
  time = Time.local(y, m, d, $~[1].to_i, $~[2].to_i, $~[3].to_i)

  while ! (lines[0] =~ /\APID/)
    line = lines.shift
  end
  labels = lines.shift.split.map do |key|
    {"PID" => :pid, "USER" => :user, "PR" => :pr, "NI" => :ni,
      "VIRT" => :virt, "RES" => :res, "SHR" => :shr, "S" => :s,
      "%CPU" => :cpu, "%MEM" => :mem, "TIME+" => :time_plus,
      "COMMAND" => :command}[key] || key
  end

  lines = lines.select{|line| ! line.empty?}
  records = lines.map do |line|
    record = Hash.new
    record[:time] = time
    line.split.each_with_index do |val, idx|
      key = labels[idx]
      if val =~ /\A(\d+)([mg]?)\Z/
        record[key] = Integer($~[1])
        if ! $~[2].empty?
          record[key] *= {'g' => 2**20, 'm' => 2**10}[$~[2]]
        end
      elsif val =~ /\A(\d+\.\d+)([mg]?)\Z/
        record[key] = Float($~[1])
        if ! $~[2].empty?
          record[key] *= {'g' => 2**20, 'm' => 2**10}[$~[2]]
        end
      elsif val =~ /\A(\d+):(\d+\.\d+)\Z/
        record[key] = Integer($~[1])*60 + Float($~[2])
      else
        record[key] = val
      end
    end

    record
  end

  if opt[:filter]
    records = block_filter(opt[:filter], records)
  end

  if opt[:top_k]
    records = records.first(opt[:top_k])
  end

  records
end