Class: OsCtl::Cli::Top::Tui::Main

Inherits:
Screen
  • Object
show all
Includes:
Lib::Utils::Humanize
Defined in:
lib/osctl/cli/top/tui/main.rb

Defined Under Namespace

Classes: Module

Constant Summary collapse

MIN_COLS =
75
MIN_LINES =
12
MIN_STATS_LINES =
MIN_LINES + 6

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, rate, enable_procs: true) ⇒ Main

Returns a new instance of Main.



30
31
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
# File 'lib/osctl/cli/top/tui/main.rb', line 30

def initialize(model, rate, enable_procs: true)
  super()

  if Curses.cols < MIN_COLS || Curses.lines < MIN_LINES
    raise "Terminal #{Curses.cols}x#{Curses.lines} is too small, " \
          "minimum required size is #{MIN_COLS}x#{MIN_LINES}"
  end

  @rate = rate
  @last_cols = Curses.cols
  @containers = []
  @last_count = nil
  @sort_index = 0
  @sort_desc = true
  @current_row = nil
  @view_page = 0
  @search_string = ''
  @highlighted_cts = []
  @status_bar_cols = 0
  @model_thread = Tui::ModelThread.new(model, rate)
  @model_thread.start
  @enable_procs = enable_procs
  if enable_procs
    @procs_thread = Tui::ProcessThread.new(rate)
    @procs_thread.start
  end
  @last_measurement = nil
  @last_generation = -1
  @last_procs_check = nil
  @last_mode = model_thread.mode
end

Instance Attribute Details

#current_rowObject (protected)

Returns the value of attribute current_row.



221
222
223
# File 'lib/osctl/cli/top/tui/main.rb', line 221

def current_row
  @current_row
end

#enable_procsObject (readonly, protected)

Returns the value of attribute enable_procs.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def enable_procs
  @enable_procs
end

#highlighted_ctsObject (readonly, protected)

Returns the value of attribute highlighted_cts.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def highlighted_cts
  @highlighted_cts
end

#last_countObject (protected)

Returns the value of attribute last_count.



221
222
223
# File 'lib/osctl/cli/top/tui/main.rb', line 221

def last_count
  @last_count
end

#last_dataObject (protected)

Returns the value of attribute last_data.



221
222
223
# File 'lib/osctl/cli/top/tui/main.rb', line 221

def last_data
  @last_data
end

#last_generationObject (readonly, protected)

Returns the value of attribute last_generation.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def last_generation
  @last_generation
end

#last_measurementObject (readonly, protected)

Returns the value of attribute last_measurement.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def last_measurement
  @last_measurement
end

#last_modeObject (readonly, protected)

Returns the value of attribute last_mode.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def last_mode
  @last_mode
end

#last_procs_checkObject (readonly, protected)

Returns the value of attribute last_procs_check.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def last_procs_check
  @last_procs_check
end

#model_threadObject (readonly, protected)

Returns the value of attribute model_thread.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def model_thread
  @model_thread
end

#procs_threadObject (readonly, protected)

Returns the value of attribute procs_thread.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def procs_thread
  @procs_thread
end

#rateObject (readonly, protected)

Returns the value of attribute rate.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def rate
  @rate
end

#search_stringObject (readonly, protected)

Returns the value of attribute search_string.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def search_string
  @search_string
end

#view_pageObject (readonly, protected)

Returns the value of attribute view_page.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def view_page
  @view_page
end

#view_page_maxObject (readonly, protected)

Returns the value of attribute view_page_max.



220
221
222
# File 'lib/osctl/cli/top/tui/main.rb', line 220

def view_page_max
  @view_page_max
end

Instance Method Details

#boldObject (protected)



1141
1142
1143
1144
1145
# File 'lib/osctl/cli/top/tui/main.rb', line 1141

def bold
  Curses.attron(Curses::A_BOLD)
  yield
  Curses.attroff(Curses::A_BOLD)
end

#compact?Boolean (protected)

Returns:

  • (Boolean)


1173
1174
1175
# File 'lib/osctl/cli/top/tui/main.rb', line 1173

def compact?
  Curses.cols < 91
end

#cursorObject (protected)



1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
# File 'lib/osctl/cli/top/tui/main.rb', line 1153

def cursor
  res = ''

  $stdin.raw do |stdin|
    $stdout << "\e[6n"
    $stdout.flush
    while (c = stdin.getc) != 'R'
      res << c if c
    end
  end

  m = res.match(/(?<row>\d+);(?<column>\d+)/)
  [m[:column].to_i, m[:row].to_i]
end

#fill_rowObject (protected)



1147
1148
1149
1150
1151
# File 'lib/osctl/cli/top/tui/main.rb', line 1147

def fill_row
  yield
  x, y = cursor
  Curses.addstr(' ' * (Curses.cols - y))
end

#format_ctid(ctid) ⇒ Object (protected)



1116
1117
1118
1119
1120
1121
1122
# File 'lib/osctl/cli/top/tui/main.rb', line 1116

def format_ctid(ctid)
  if ctid.length > 12
    "#{ctid[0..11]}.."
  else
    ctid
  end
end

#format_loadavg(lavg) ⇒ Object (protected)



1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
# File 'lib/osctl/cli/top/tui/main.rb', line 1128

def format_loadavg(lavg)
  fmt =
    if lavg < 100
      '%5.2f'
    elsif lavg < 1000
      '%5.1f'
    else
      '%4.0f'
    end

  format(fmt, lavg)
end

#format_loadavgs(lavgs) ⇒ Object (protected)



1124
1125
1126
# File 'lib/osctl/cli/top/tui/main.rb', line 1124

def format_loadavgs(lavgs)
  lavgs.map { |lavg| format_loadavg(lavg) }.join(', ')
end

#get_dataObject (protected)



869
870
871
872
873
874
875
876
877
878
879
# File 'lib/osctl/cli/top/tui/main.rb', line 869

def get_data
  ret, measured_at, generation = model_thread.get_data

  @last_data = ret
  @last_measurement = measured_at
  @last_generation = generation

  setup_modules
  run_sort
  ret
end

#header(pos) ⇒ Object (protected)



733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File 'lib/osctl/cli/top/tui/main.rb', line 733

def header(pos)
  unless @header
    ret = []

    3.times do |i|
      next if i == 1 && compact?

      ret << format(
        @modules.map { |m| m.header_fmts[i] }.join(' '),
        *@modules.map do |m|
          labels = m.header_labels
          labels.is_a?(Proc) ? labels.call[i] : labels[i]
        end.flatten
      )
    end

    # Fill to the edge of the screen
    @header = ret.map do |line|
      padding = Curses.cols - line.size

      line << (' ' * padding) if padding > 0
      line << "\n"
    end
  end

  @header.each do |line|
    Curses.setpos(pos, 0)
    Curses.addstr(line)
    pos += 1
  end

  pos
end

#lookup_field(ct, field) ⇒ Object (protected)



1099
1100
1101
1102
1103
1104
1105
1106
# File 'lib/osctl/cli/top/tui/main.rb', line 1099

def lookup_field(ct, field)
  if field.is_a?(Array)
    field.reduce(ct) { |acc, v| acc[v] }

  else
    ct[field]
  end
end

#max_rowsObject (protected)

Screen without header and footer



1169
1170
1171
# File 'lib/osctl/cli/top/tui/main.rb', line 1169

def max_rows
  Curses.lines - @status_bar_cols - 1 - @header.size - stats_rows - 1
end

#modeObject (protected)



1108
1109
1110
# File 'lib/osctl/cli/top/tui/main.rb', line 1108

def mode
  model_thread.mode
end

#openObject



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
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
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
# File 'lib/osctl/cli/top/tui/main.rb', line 62

def open
  empty_data = { containers: [] }
  data = { containers: [] }
  procs_stats, @last_procs_check = enable_procs && procs_thread.get_stats

  # Initial render
  render(Time.now, procs_stats, empty_data) if last_generation == -1

  # At each loop pass, model is queried for data, unless `hold_data` is
  # greater than zero. In that case, `hold_data` is decremented by 1
  # on each pass.
  hold_data = 0

  loop do
    now = Time.now

    if last_generation != model_thread.generation \
       && (!last_data || hold_data == 0) \
       && !paused?
      data = get_data

    elsif hold_data > 0
      hold_data -= 1
      data = last_data
    end

    @containers =
      if search_active?
        data[:containers].select { |ct| ct[:id].include?(search_string) }
      else
        data[:containers]
      end

    if last_mode != model_thread.mode
      @header = nil
      Curses.clear
      @last_mode = model_thread.mode
    elsif last_count != @containers.count
      Curses.clear
    end

    self.last_count = @containers.count

    if enable_procs && !paused?
      procs_stats, @last_procs_check = procs_thread.get_stats
    end

    if @last_cols != Curses.cols
      @header = nil
      @modules = nil
      @last_cols = Curses.cols
    end

    render(now, procs_stats, data)
    Curses.timeout = rate * 1000
    input = Curses.getch

    if search_in_focus?
      case input
      when Curses::Key::ENTER, Tui::Key::ENTER
        search_end_focus
      when Tui::Key::ESCAPE
        search_cancel
      when Curses::Key::BACKSPACE, Tui::Key::BACKSPACE
        search_chop
      else
        if input && input.is_a?(String)
          search_add(input)
          Curses.clear
        end
      end

      next
    end

    case input
    when 'q'
      procs_thread.stop if enable_procs
      model_thread.stop
      return

    when Curses::Key::LEFT, '<'
      Curses.clear
      sort_next(-1)
      run_sort

    when Curses::Key::RIGHT, '>'
      Curses.clear
      sort_next(+1)
      run_sort

    when Curses::Key::UP
      selection_up
      hold_data = 1

    when Curses::Key::DOWN
      selection_down
      hold_data = 1

    when ' '
      selection_highlight

    when Curses::Key::ENTER, Tui::Key::ENTER, 't'
      selection_open_top

    when Curses::Key::NPAGE # Page Down
      Curses.clear
      view_page_down

    when Curses::Key::PPAGE # Page Up
      Curses.clear
      view_page_up

    when Curses::Key::HOME
      Curses.clear
      view_page_reset

    when Curses::Key::END
      Curses.clear
      view_page_end

    when 'h'
      selection_open_htop

    when 'r', 'R'
      Curses.clear
      sort_inverse
      run_sort

    when 'm'
      modes = Model::MODES
      i = modes.index(mode)

      model_thread.mode = if i + 1 >= modes.count
                            modes[0]

                          else
                            modes[i + 1]
                          end

    when 'p'
      paused? ? unpause : pause

    when '/'
      search_start_focus

    when '?'
      return Tui::Help.new(self)

    when Curses::Key::RESIZE
      @modules = nil
      Curses.clear
    end
  end
end

#pauseObject (protected)



1177
1178
1179
# File 'lib/osctl/cli/top/tui/main.rb', line 1177

def pause
  @paused = true
end

#paused?Boolean (protected)

Returns:

  • (Boolean)


1185
1186
1187
# File 'lib/osctl/cli/top/tui/main.rb', line 1185

def paused?
  @paused
end


767
768
769
770
771
772
# File 'lib/osctl/cli/top/tui/main.rb', line 767

def print_row(ct)
  # Special case for container ID as that is always visible
  Curses.addstr(format("#{@modules[0].row_fmt.join(' ')} ", *@modules[0].row_values.call(ct)))

  print_row_data(@modules[1..].map { |m| m.row_values.call(ct) }.flatten)
end


774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'lib/osctl/cli/top/tui/main.rb', line 774

def print_row_data(values)
  fmts = @modules[1..].map(&:row_fmt).flatten
  w = 15 # container ID is printed in {#print_row}

  fmts.zip(values).each_with_index do |pair, i|
    f, v = pair
    s = format("#{f} ", v)
    w += s.length

    Curses.attron(Curses::A_BOLD) if i == @sort_index
    Curses.addstr(s)
    Curses.attroff(Curses::A_BOLD) if i == @sort_index
  end

  # Fill space to the edge of the screen, needed for selected rows
  Curses.addstr(' ' * (Curses.cols - w)) if Curses.cols > w
end

#render(t, procs_stats, data) ⇒ Object (protected)



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/osctl/cli/top/tui/main.rb', line 527

def render(t, procs_stats, data)
  setup_modules

  Curses.setpos(0, 0)
  Curses.addstr("#{File.basename($0)} ct top - #{t.strftime('%H:%M:%S')}")
  Curses.addstr(format(' [%.1fs]', last_measurement - t)) if last_measurement

  lavg = data[:loadavg] ? format_loadavgs(data[:loadavg]) : '?'

  if compact?
    Curses.addstr(" #{model_thread.mode}, loadavg #{lavg}")
  else
    Curses.addstr(" #{model_thread.mode} mode, load average #{lavg}")
  end

  i = status_bar(1, t, procs_stats, data)

  Curses.attron(Curses.color_pair(1))
  i = header(i + 1)
  j = 0
  Curses.attroff(Curses.color_pair(1))

  ct_count = @containers.length
  offset = 0
  view_ct_count = Curses.lines - stats_rows - i

  @view_page_max = ((ct_count - view_ct_count) / (view_ct_count / 2).to_f).ceil

  if view_page > 0
    @view_offset = (view_ct_count / 2) * view_page

    if offset >= ct_count - view_ct_count
      @view_offset = ct_count - view_ct_count
    end
  else
    @view_offset = 0
  end

  @containers[@view_offset..].each do |ct|
    Curses.setpos(i, 0)

    attr = if current_row == j && highlighted_cts.include?(ct[:id])
             Curses.color_pair(Tui::SELECTED_HIGHLIGHTED)

           elsif current_row == j
             Curses.color_pair(Tui::SELECTED)

           elsif highlighted_cts.include?(ct[:id])
             Curses.color_pair(Tui::HIGHLIGHTED)

           end

    Curses.attron(attr) if attr
    print_row(ct)
    Curses.attroff(attr) if attr

    i += 1
    j += 1

    break if i >= (Curses.lines - stats_rows)
  end

  stats(data, [offset, view_ct_count, ct_count]) if Curses.lines >= MIN_STATS_LINES

  Curses.refresh
end

#rt?Boolean (protected)

Returns:

  • (Boolean)


1112
1113
1114
# File 'lib/osctl/cli/top/tui/main.rb', line 1112

def rt?
  model_thread.mode == :realtime
end

#run_sortObject (protected)



913
914
915
916
917
918
919
# File 'lib/osctl/cli/top/tui/main.rb', line 913

def run_sort
  last_data[:containers].sort! do |a, b|
    sortable_value(a) <=> sortable_value(b)
  end

  last_data[:containers].reverse! if @sort_desc
end

#search_active?Boolean (protected)

Returns:

  • (Boolean)


1076
1077
1078
# File 'lib/osctl/cli/top/tui/main.rb', line 1076

def search_active?
  !@search_string.empty?
end

#search_add(input) ⇒ Object (protected)



1080
1081
1082
# File 'lib/osctl/cli/top/tui/main.rb', line 1080

def search_add(input)
  @search_string << input
end

#search_cancelObject (protected)



1071
1072
1073
1074
# File 'lib/osctl/cli/top/tui/main.rb', line 1071

def search_cancel
  search_end_focus
  @search_string = ''
end

#search_chopObject (protected)



1084
1085
1086
# File 'lib/osctl/cli/top/tui/main.rb', line 1084

def search_chop
  @search_string.chop!
end

#search_end_focusObject (protected)



1066
1067
1068
1069
# File 'lib/osctl/cli/top/tui/main.rb', line 1066

def search_end_focus
  Curses.curs_set(0)  # hide cursor
  @search_input = false
end

#search_in_focus?Boolean (protected)

Returns:

  • (Boolean)


1062
1063
1064
# File 'lib/osctl/cli/top/tui/main.rb', line 1062

def search_in_focus?
  @search_input
end

#search_start_focusObject (protected)



1055
1056
1057
1058
1059
1060
# File 'lib/osctl/cli/top/tui/main.rb', line 1055

def search_start_focus
  @search_input = true

  Curses.curs_set(1)  # show cursor
  Curses.clear
end

#selection_downObject (protected)



943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
# File 'lib/osctl/cli/top/tui/main.rb', line 943

def selection_down
  if @current_row
    new_row = @current_row + 1

    @current_row = if new_row < @containers.size && new_row < max_rows
                     new_row

                   elsif @containers.any?
                     0

                   end

  elsif @containers.any?
    @current_row = 0
  end
end

#selection_highlightObject (protected)



960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
# File 'lib/osctl/cli/top/tui/main.rb', line 960

def selection_highlight
  return unless @current_row

  ct = @containers[@view_offset + @current_row]
  return unless ct

  ctid = ct[:id]

  if highlighted_cts.include?(ctid)
    highlighted_cts.delete(ctid)

  else
    highlighted_cts << ctid
  end
end

#selection_open_htopObject (protected)



980
981
982
# File 'lib/osctl/cli/top/tui/main.rb', line 980

def selection_open_htop
  selection_open_program { %w[htop] }
end

#selection_open_program(&block) ⇒ Object (protected)



984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# File 'lib/osctl/cli/top/tui/main.rb', line 984

def selection_open_program(&block)
  return unless @current_row

  ct = @containers[@view_offset + @current_row]
  return unless ct

  if ct[:id] == '[host]'
    pid = Process.fork do
      Curses.close_screen
      Process.exec(*block.call)
    end
  elsif ct[:init_pid]
    pid = Process.fork do
      sys = OsCtl::Lib::Sys.new

      sys.setns_path(
        File.join('/proc', ct[:init_pid].to_s, 'ns/pid'),
        OsCtl::Lib::Sys::CLONE_NEWPID
      )
      sys.unshare_ns(OsCtl::Lib::Sys::CLONE_NEWNS)

      # Enter the PID namespace in a child process
      child = Process.fork do
        sys.mount_proc('/proc')

        Curses.close_screen
        Process.exec(*block.call)
      end

      Process.wait(child)
      exit($?.exitstatus)
    end
  else
    return
  end

  Process.wait(pid)

  # The screen needs to be reinitialized after top
  Curses.init_screen
  Curses.start_color
  Curses.crmode
  Curses.stdscr.keypad = true
  Curses.curs_set(0)  # hide cursor
  Curses.clear
end

#selection_open_topObject (protected)



976
977
978
# File 'lib/osctl/cli/top/tui/main.rb', line 976

def selection_open_top
  selection_open_program { %w[top] }
end

#selection_upObject (protected)



921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# File 'lib/osctl/cli/top/tui/main.rb', line 921

def selection_up
  last_row = [max_rows - 1, @containers.size - 1].min

  if @current_row
    new_row = @current_row - 1

    @current_row = if new_row >= 0
                     new_row

                   elsif new_row == -1
                     nil

                   elsif @containers.any?
                     last_row

                   end

  elsif @containers.any?
    @current_row = last_row
  end
end

#setup_modulesObject (protected)



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
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/osctl/cli/top/tui/main.rb', line 223

def setup_modules
  return if @modules

  @modules = []

  @modules << Module.new(
    name: 'ctid',
    header_fmts: ['%-14s'] * 3,
    header_labels: [
      ['Container'],
      [''],
      ['ID']
    ],
    row_fmt: ['%-14s'],
    row_values: proc do |ct|
      [format_ctid(ct[:id])]
    end,
    stats_cts_values: [],
    stats_all_values: []
  )

  @modules << Module.new(
    name: 'cpu',
    header_fmts: ['%9s'] * 3,
    header_labels: [
      ['CPU'],
      [''],
      ['']
    ],
    row_fmt: ['%9s'],
    row_values: proc do |ct|
      cpu = (rt? ? format_percent(ct[:cpu_usage]) : humanize_time_us(ct[:cpu_us])).to_s
      cpu << "/#{ct[:cpu_package_inuse]}" if ct[:cpu_package_inuse]
      [cpu]
    end,
    sortable_fields: proc do
      rt? ? :cpu_usage : :cpu_us
    end,
    stats_cts_values: proc do |cts|
      if rt?
        [format_percent(sum(cts, :cpu_usage, false))]
      else
        [humanize_time_us(sum(cts, :cpu_us, false))]
      end
    end,
    stats_all_values: proc do |cts|
      if rt?
        [format_percent(sum(cts, :cpu_usage, true))]
      else
        [humanize_time_us(sum(cts, :cpu_us, true))]
      end
    end
  )

  @modules << Module.new(
    name: 'memory',
    header_fmts: ['%8s'] * 3,
    header_labels: [
      ['Memory'],
      [''],
      ['']
    ],
    row_fmt: ['%8s'],
    row_values: proc do |ct|
      [humanize_data(ct[:memory])]
    end,
    sortable_fields: :memory,
    stats_cts_values: proc do |cts|
      [humanize_data(sum(cts, :memory, false))]
    end,
    stats_all_values: proc do |cts|
      [humanize_data(sum(cts, :memory, true))]
    end
  )

  @modules << Module.new(
    name: 'proc',
    header_fmts: ['%6s'] * 3,
    header_labels: [
      ['Proc'],
      [''],
      ['']
    ],
    row_fmt: ['%6s'],
    row_values: proc do |ct|
      [ct[:nproc]]
    end,
    sortable_fields: :nproc,
    stats_cts_values: proc do |cts|
      [sum(cts, :nproc, false)]
    end,
    stats_all_values: proc do |cts|
      [sum(cts, :nproc, true)]
    end
  )

  if Curses.cols >= 114
    @modules << Module.new(
      name: 'zfsio',
      header_fmts: ['%27s', '%13s %13s', '%6s %6s %6s %6s'],
      header_labels: proc do
        [
          ['ZFSIO          '],
          ['Read   ', 'Write   '],
          ['Bytes', rt? ? 'IOPS' : 'IO', 'Bytes', rt? ? 'IOPS' : 'IO']
        ]
      end,
      row_fmt: ['%6s'] * 4,
      row_values: proc do |ct|
        [
          humanize_data(ct[:zfsio][:bytes][:r]),
          humanize_number(ct[:zfsio][:ios][:r]),
          humanize_data(ct[:zfsio][:bytes][:w]),
          humanize_number(ct[:zfsio][:ios][:w])
        ]
      end,
      sortable_fields: [
        %i[zfsio bytes r],
        %i[zfsio ios r],
        %i[zfsio bytes w],
        %i[zfsio ios w]
      ],
      stats_cts_values: proc do |cts|
        [
          humanize_data(sum(cts, %i[zfsio bytes r], false)),
          humanize_number(sum(cts, %i[zfsio ios r], false)),
          humanize_data(sum(cts, %i[zfsio bytes w], false)),
          humanize_number(sum(cts, %i[zfsio ios w], false))
        ]
      end,
      stats_all_values: proc do |cts|
        [
          humanize_data(sum(cts, %i[zfsio bytes r], true)),
          humanize_number(sum(cts, %i[zfsio ios r], true)),
          humanize_data(sum(cts, %i[zfsio bytes w], true)),
          humanize_number(sum(cts, %i[zfsio ios w], true))
        ]
      end,
      stats_iostat_values: proc do |iostat|
        [
          humanize_data(iostat[:bytes_read]),
          humanize_data(iostat[:io_read]),
          humanize_data(iostat[:bytes_written]),
          humanize_data(iostat[:io_written])
        ]
      end
    )
  end

  @modules <<
    if compact?
      Module.new(
        name: 'network',
        header_fmts: ['%18s', '', '%8s %8s'],
        header_labels: proc do
          [
            ['Network     '],
            [],
            rt? ? ['TX bps', 'RX bps'] : ['TX bytes', 'RX bytes']
          ]
        end,
        row_fmt: ['%8s'] * 2,
        row_values: proc do |ct|
          [
            humanize_data(rt? ? ct[:tx][:bytes] * 8 : ct[:tx][:bytes]),
            humanize_data(rt? ? ct[:rx][:bytes] * 8 : ct[:rx][:bytes])
          ]
        end,
        sortable_fields: [
          %i[tx bytes],
          %i[rx bytes]
        ],
        stats_cts_values: proc do |cts|
          [
            humanize_data(sum(cts, %i[tx bytes], false) * (rt? ? 8 : 1)),
            humanize_data(sum(cts, %i[rx bytes], false) * (rt? ? 8 : 1))
          ]
        end,
        stats_all_values: proc do |cts|
          [
            humanize_data(sum(cts, %i[tx bytes], true) * (rt? ? 8 : 1)),
            humanize_data(sum(cts, %i[rx bytes], true) * (rt? ? 8 : 1))
          ]
        end
      )
    else
      Module.new(
        name: 'network',
        header_fmts: ['%27s', '%13s %13s', '%6s %6s %6s %6s'],
        header_labels: proc do
          [
            ['Network        '],
            ['TX    ', 'RX    '],
            rt? ? %w[bps pps bps pps] : %w[Bytes Packet Bytes Packet]
          ]
        end,
        row_fmt: ['%6s'] * 4,
        row_values: proc do |ct|
          [
            humanize_data(rt? ? ct[:tx][:bytes] * 8 : ct[:tx][:bytes]),
            humanize_data(ct[:tx][:packets]),
            humanize_data(rt? ? ct[:rx][:bytes] * 8 : ct[:rx][:bytes]),
            humanize_data(ct[:rx][:packets])
          ]
        end,
        sortable_fields: [
          %i[tx bytes],
          %i[tx packets],
          %i[rx bytes],
          %i[rx packets]
        ],
        stats_cts_values: proc do |cts|
          [
            humanize_data(sum(cts, %i[tx bytes], false) * (rt? ? 8 : 1)),
            humanize_data(sum(cts, %i[tx packets], false)),
            humanize_data(sum(cts, %i[rx bytes], false) * (rt? ? 8 : 1)),
            humanize_data(sum(cts, %i[rx packets], false))
          ]
        end,
        stats_all_values: proc do |cts|
          [
            humanize_data(sum(cts, %i[tx bytes], true) * (rt? ? 8 : 1)),
            humanize_data(sum(cts, %i[tx packets], true)),
            humanize_data(sum(cts, %i[rx bytes], true) * (rt? ? 8 : 1)),
            humanize_data(sum(cts, %i[rx packets], true))
          ]
        end
      )
    end

  @modules <<
    if compact?
      Module.new(
        name: 'loadavg',
        header_fmts: ['%12s', '', '%5s %5s'],
        header_labels: [
          ['LoadAvg  '],
          [''],
          ['1m', '5m']
        ],
        row_fmt: ['%5s'] * 2,
        row_values: proc do |ct|
          [
            format_loadavg(ct[:loadavg][0]),
            format_loadavg(ct[:loadavg][1])
          ]
        end,
        sortable_fields: [
          [:loadavg, 0],
          [:loadavg, 1]
        ],
        stats_cts_values: proc do |cts|
          [
            format_loadavg(sum(cts, [:loadavg, 0], false)),
            format_loadavg(sum(cts, [:loadavg, 1], false))
          ]
        end,
        stats_all_values: proc do |_cts, data|
          [
            data[:loadavg] ? format_loadavg(data[:loadavg][0]) : '-',
            data[:loadavg] ? format_loadavg(data[:loadavg][1]) : '-'
          ]
        end
      )
    else
      Module.new(
        name: 'loadavg',
        header_fmts: ['%17s', '%17s', '%5s %5s %5s'],
        header_labels: [
          ['LoadAvg    '],
          [''],
          ['1m', '5m', '15m']
        ],
        row_fmt: ['%5s'] * 3,
        row_values: proc do |ct|
          [
            format_loadavg(ct[:loadavg][0]),
            format_loadavg(ct[:loadavg][1]),
            format_loadavg(ct[:loadavg][2])
          ]
        end,
        sortable_fields: [
          [:loadavg, 0],
          [:loadavg, 1],
          [:loadavg, 2]
        ],
        stats_cts_values: proc do |cts|
          [
            format_loadavg(sum(cts, [:loadavg, 0], false)),
            format_loadavg(sum(cts, [:loadavg, 1], false)),
            format_loadavg(sum(cts, [:loadavg, 2], false))
          ]
        end,
        stats_all_values: proc do |_cts, data|
          [
            data[:loadavg] ? format_loadavg(data[:loadavg][0]) : '-',
            data[:loadavg] ? format_loadavg(data[:loadavg][1]) : '-',
            data[:loadavg] ? format_loadavg(data[:loadavg][2]) : '-'
          ]
        end
      )
    end
end

#sort_inverseObject (protected)



899
900
901
# File 'lib/osctl/cli/top/tui/main.rb', line 899

def sort_inverse
  @sort_desc = !@sort_desc
end

#sort_next(n) ⇒ Object (protected)



885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/osctl/cli/top/tui/main.rb', line 885

def sort_next(n)
  next_i = @sort_index + n
  fields = sortable_fields

  if next_i < 0
    next_i = fields.count - 1

  elsif next_i >= fields.count
    next_i = 0
  end

  @sort_index = next_i
end

#sortable_fieldsObject (protected)



903
904
905
906
907
908
909
910
911
# File 'lib/osctl/cli/top/tui/main.rb', line 903

def sortable_fields
  @modules[1..].map do |m|
    if m.sortable_fields.is_a?(Proc)
      m.sortable_fields.call
    else
      m.sortable_fields
    end
  end.flatten(1)
end

#sortable_value(ct) ⇒ Object (protected)



881
882
883
# File 'lib/osctl/cli/top/tui/main.rb', line 881

def sortable_value(ct)
  lookup_field(ct, sortable_fields[@sort_index])
end

#stats(data, ct_view) ⇒ Object (protected)



800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
# File 'lib/osctl/cli/top/tui/main.rb', line 800

def stats(data, ct_view)
  cts = data[:containers]
  pos = stats_rows

  Curses.setpos(Curses.lines - pos, 0)
  pos -= 1
  Curses.addstr('─' * Curses.cols)
  # Curses.addstr('-' * Curses.cols)

  Curses.setpos(Curses.lines - pos, 0)
  pos -= 1
  Curses.addstr(format('%-14s ', 'Containers:'))
  print_row_data(@modules[1..].map { |m| m.stats_cts_values.call(cts, data) }.flatten)

  Curses.setpos(Curses.lines - pos, 0)
  pos -= 1
  Curses.addstr(format('%-14s ', 'All:'))
  print_row_data(@modules[1..].map { |m| m.stats_all_values.call(cts, data) }.flatten)

  if model_thread.iostat_enabled? && @modules.detect { |m| m.name == 'zfsio' }
    iostat = data[:zfs] && data[:zfs][:iostat]

    Curses.setpos(Curses.lines - pos, 0)
    pos -= 1
    Curses.addstr(format('%-14s ', 'iostat:'))

    if iostat
      print_row_data(@modules[1..].map { |m| m.stats_iostat_values.call(iostat) }.flatten)
    end
  end

  Curses.setpos(Curses.lines - pos, 0)
  pos -= 1
  Curses.addstr('─' * Curses.cols)
  Curses.setpos(Curses.lines - pos, 0)

  search_msg = nil

  fill_row do
    if search_in_focus? || search_active?
      search_msg = "Search: #{search_string}"
      Curses.addstr(search_msg)
      next
    end

    Curses.addstr('Selected container: ')

    if @current_row && (ct = @containers[@view_offset + @current_row])
      if ct[:id] == '[host]'
        Curses.addstr('host system')
      else
        Curses.addstr("#{ct[:pool]}:#{ct[:id]}")
      end
    else
      Curses.addstr('none')
    end
  end

  offset, view_count, ct_count = ct_view
  page = format('[%d-%d/%d]', offset + 1, offset + view_count, ct_count)

  Curses.setpos(Curses.lines - pos, Curses.cols - page.length)
  Curses.addstr(page)

  return unless search_in_focus?

  Curses.setpos(Curses.lines - pos, search_msg.length)
end

#stats_rowsObject (protected)



792
793
794
795
796
797
798
# File 'lib/osctl/cli/top/tui/main.rb', line 792

def stats_rows
  return 0 if Curses.lines < MIN_STATS_LINES

  i = 5
  i += 1 if model_thread.iostat_enabled? && @modules.detect { |m| m.name == 'zfsio' }
  i
end

#status_bar(orig_pos, t, procs_stats, data) ⇒ Object (protected)



594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/osctl/cli/top/tui/main.rb', line 594

def status_bar(orig_pos, t, procs_stats, data)
  pos = orig_pos
  @status_bar_cols = 0

  # Processes
  if enable_procs
    Curses.setpos(pos, 0)
    Curses.addstr('Tasks')
    Curses.addstr(format(' [%.1fs]', @last_procs_check - t)) if @last_procs_check
    Curses.addstr(': ')
    bold { Curses.addstr(format('%5d', procs_stats['TOTAL'])) }
    Curses.addstr(compact? ? ' tot, ' : ' total, ')
    bold { Curses.addstr(format('%3d', procs_stats['R'])) }
    Curses.addstr(compact? ? ' run, ' : ' running, ')
    bold { Curses.addstr(format('%3d', procs_stats['D'])) }
    Curses.addstr(compact? ? ' block, ' : ' blocked, ')
    bold { Curses.addstr(format('%5d', procs_stats['S'])) }
    Curses.addstr(compact? ? ' sleep, ' : ' sleeping, ')
    bold { Curses.addstr(format('%2d', procs_stats['T'])) }
    Curses.addstr(compact? ? ' stop, ' : ' stopped, ')
    bold { Curses.addstr(format('%2d', procs_stats['Z'])) }
    Curses.addstr(compact? ? ' zom' : ' zombie ')
    pos += 1
  end

  # CPU
  cpu = data[:cpu]

  Curses.setpos(pos, 0)
  Curses.addstr('%CPU: ')

  if cpu
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:user]))) }
    Curses.addstr(' us, ')
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:system]))) }
    Curses.addstr(' sy, ')
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:nice]))) }
    Curses.addstr(' ni, ')
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:idle]))) }
    Curses.addstr(' id, ')
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:iowait]))) }
    Curses.addstr(' wa, ')
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:irq]))) }
    Curses.addstr(' hi, ')
    bold { Curses.addstr(format('%5.1f', format_percent(cpu[:softirq]))) }
    Curses.addstr(' si')

  else
    Curses.addstr('calculating')
  end

  # Memory
  mem = data[:memory]

  Curses.setpos(pos += 1, 0)
  Curses.addstr('Memory: ')

  if mem
    bold { Curses.addstr(format('%8s', humanize_data(mem[:total]))) }
    Curses.addstr(' total, ')
    bold { Curses.addstr(format('%8s', humanize_data(mem[:free]))) }
    Curses.addstr(' free, ')
    bold { Curses.addstr(format('%8s', humanize_data(mem[:used]))) }
    Curses.addstr(' used, ')
    bold { Curses.addstr(format('%8s', humanize_data(mem[:buffers] + mem[:cached]))) }
    Curses.addstr(' buff/cache')

    if mem[:swap_total] > 0
      Curses.setpos(pos += 1, 0)
      Curses.addstr('Swap:   ')

      bold { Curses.addstr(format('%8s', humanize_data(mem[:swap_total]))) }
      Curses.addstr(' total, ')
      bold { Curses.addstr(format('%8s', humanize_data(mem[:swap_free]))) }
      Curses.addstr(' free, ')
      bold { Curses.addstr(format('%8s', humanize_data(mem[:swap_used]))) }
      Curses.addstr(' used')
    end

  else
    Curses.addstr('calculating')
  end

  # ZFS ARC
  arc = data[:zfs] && data[:zfs][:arcstats][:arc]

  Curses.setpos(pos += 1, 0)
  Curses.addstr('ARC:    ')

  if arc
    bold { Curses.addstr(format('%8s', humanize_data(arc[:c_max]))) }
    Curses.addstr(' c_max, ')
    bold { Curses.addstr(format('%8s', humanize_data(arc[:c]))) }
    Curses.addstr(' c,    ')
    bold { Curses.addstr(format('%8s', humanize_data(arc[:size]))) }
    Curses.addstr(compact? ? ' s, ' : ' size, ')
    bold { Curses.addstr(format('%8.2f', format_percent(arc[:hit_rate]))) }
    Curses.addstr(compact? ? ' hit, ' : ' hitrate, ')
    bold { Curses.addstr(format('%6d', arc[:misses])) }
    Curses.addstr(compact? ? ' mis' : ' missed ')

  else
    Curses.addstr('calculating')
  end

  l2arc = data[:zfs] && data[:zfs][:arcstats][:l2arc]

  if l2arc && l2arc[:size] > 0
    Curses.setpos(pos += 1, 0)
    Curses.addstr("L2ARC:  #{' ' * 16}")

    bold { Curses.addstr(format('%8s', humanize_data(l2arc[:size]))) }
    Curses.addstr(' size, ')
    bold { Curses.addstr(format('%8s', humanize_data(l2arc[:asize]))) }
    Curses.addstr(' asize,')
    bold { Curses.addstr(format('%8.2f', humanize_data(l2arc[:hit_rate]))) }
    Curses.addstr(' hitrate, ')
    bold { Curses.addstr(format('%6d', l2arc[:misses])) }
    Curses.addstr(' missed ')
  end

  # Containers
  Curses.setpos(pos += 1, 0)
  Curses.addstr('Containers: ')
  bold { Curses.addstr(format('%3d', model_thread.containers.count)) }
  Curses.addstr(' total, ')
  bold { Curses.addstr(format('%3d', model_thread.containers.count { |ct| ct.state == :starting })) }
  Curses.addstr(' starting, ')
  bold { Curses.addstr(format('%3d', data[:containers].count - 1)) } # -1 for [host]
  Curses.addstr(' running, ')
  bold { Curses.addstr(format('%3d', model_thread.containers.count { |ct| ct.state == :stopping })) }
  Curses.addstr(' stopping, ')
  bold { Curses.addstr(format('%3d', model_thread.containers.count { |ct| ct.state == :stopped })) }
  Curses.addstr(' stopped')

  @status_bar_cols += pos - orig_pos + 1
  pos + 1
end

#sum(cts, field, host) ⇒ Object (protected)



1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# File 'lib/osctl/cli/top/tui/main.rb', line 1088

def sum(cts, field, host)
  cts.inject(0) do |acc, ct|
    if ct[:id] == '[host]' && !host
      acc

    else
      acc + lookup_field(ct, field)
    end
  end
end

#unpauseObject (protected)



1181
1182
1183
# File 'lib/osctl/cli/top/tui/main.rb', line 1181

def unpause
  @paused = false
end

#view_page_downObject (protected)



1031
1032
1033
1034
1035
1036
1037
# File 'lib/osctl/cli/top/tui/main.rb', line 1031

def view_page_down
  @view_page += 1

  return unless @view_page_max && @view_page > @view_page_max

  @view_page = @view_page_max
end

#view_page_endObject (protected)



1047
1048
1049
1050
1051
1052
1053
# File 'lib/osctl/cli/top/tui/main.rb', line 1047

def view_page_end
  if view_page_max
    @view_page = view_page_max
  else
    view_page_down
  end
end

#view_page_resetObject (protected)



1043
1044
1045
# File 'lib/osctl/cli/top/tui/main.rb', line 1043

def view_page_reset
  @view_page = 0
end

#view_page_upObject (protected)



1039
1040
1041
# File 'lib/osctl/cli/top/tui/main.rb', line 1039

def view_page_up
  @view_page -= 1 if @view_page > 0
end