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

Inherits:
Tui::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_row ⇒ Object (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_procs ⇒ Object (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_cts ⇒ Object (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_count ⇒ Object (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_data ⇒ Object (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_generation ⇒ Object (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_measurement ⇒ Object (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_mode ⇒ Object (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_check ⇒ Object (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_thread ⇒ Object (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_thread ⇒ Object (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

#rate ⇒ Object (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_string ⇒ Object (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_page ⇒ Object (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_max ⇒ Object (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

#bold ⇒ Object (protected)



1193
1194
1195
1196
1197
# File 'lib/osctl/cli/top/tui/main.rb', line 1193

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

#compact? ⇒ Boolean (protected)

Returns:

  • (Boolean)


1225
1226
1227
# File 'lib/osctl/cli/top/tui/main.rb', line 1225

def compact?
  Curses.cols < 91
end

#cursor ⇒ Object (protected)



1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
# File 'lib/osctl/cli/top/tui/main.rb', line 1205

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_row ⇒ Object (protected)



1199
1200
1201
1202
1203
# File 'lib/osctl/cli/top/tui/main.rb', line 1199

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

#format_ctid(ctid) ⇒ Object (protected)



1164
1165
1166
1167
1168
1169
1170
# File 'lib/osctl/cli/top/tui/main.rb', line 1164

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

#format_loadavg(lavg) ⇒ Object (protected)



1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
# File 'lib/osctl/cli/top/tui/main.rb', line 1178

def format_loadavg(lavg)
  return '-' if lavg.nil?

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

  format(fmt, lavg)
end

#format_loadavgs(lavgs) ⇒ Object (protected)



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

def format_loadavgs(lavgs)
  return '?' unless lavgs

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

#get_data ⇒ Object (protected)



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

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)



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/osctl/cli/top/tui/main.rb', line 746

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)



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

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

  else
    ct[field]
  end
end

#max_rows ⇒ Object (protected)

Screen without header and footer



1221
1222
1223
# File 'lib/osctl/cli/top/tui/main.rb', line 1221

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

#mode ⇒ Object (protected)



1156
1157
1158
# File 'lib/osctl/cli/top/tui/main.rb', line 1156

def mode
  model_thread.mode
end

#module_totals(mod, cts, data, include_host) ⇒ Object (protected)



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'lib/osctl/cli/top/tui/main.rb', line 812

def module_totals(mod, cts, data, include_host)
  fields = case mod.name
           when 'network' then %i[tx rx]
           when 'zfsio' then [:zfsio]
           when 'cpu' then [rt? ? :cpu_usage : :cpu_us]
           when 'memory' then [:memory]
           when 'proc' then [:nproc]
           when 'loadavg' then [:loadavg]
           else []
           end
  unknown = cts.any? do |ct|
    next false if !include_host && ct[:id] == '[host]'

    fields.any? { |key| ct[key].nil? }
  end
  return ['-'] * mod.row_fmt.length if unknown

  (include_host ? mod.stats_all_values : mod.stats_cts_values).call(cts, data)
end

#open ⇒ Object



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

#pause ⇒ Object (protected)



1229
1230
1231
# File 'lib/osctl/cli/top/tui/main.rb', line 1229

def pause
  @paused = true
end

#paused? ⇒ Boolean (protected)

Returns:

  • (Boolean)


1237
1238
1239
# File 'lib/osctl/cli/top/tui/main.rb', line 1237

def paused?
  @paused
end


780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/osctl/cli/top/tui/main.rb', line 780

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 do |m|
    if (m.name == 'network' && (ct[:tx].nil? || ct[:rx].nil?)) ||
       (m.name == 'zfsio' && ct[:zfsio].nil?) || (m.name == 'loadavg' && ct[:loadavg].nil?)
      ['-'] * m.row_fmt.length
    else
      m.row_values.call(ct)
    end
  end.flatten)
end


794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# File 'lib/osctl/cli/top/tui/main.rb', line 794

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)



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

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
  @view_offset, view_ct_count, @view_page_max, @view_page =
    view_window(ct_count, Curses.lines - stats_rows - i, view_page)
  shown_ct_count = [view_ct_count, ct_count - @view_offset].min

  @containers[@view_offset, shown_ct_count].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, [@view_offset, shown_ct_count, ct_count]) if Curses.lines >= MIN_STATS_LINES

  Curses.refresh
end

#rt? ⇒ Boolean (protected)

Returns:

  • (Boolean)


1160
1161
1162
# File 'lib/osctl/cli/top/tui/main.rb', line 1160

def rt?
  model_thread.mode == :realtime
end

#run_sort ⇒ Object (protected)



954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/osctl/cli/top/tui/main.rb', line 954

def run_sort
  last_data[:containers].sort! do |a, b|
    av = sortable_value(a)
    bv = sortable_value(b)
    if av.nil?
      bv.nil? ? 0 : -1
    else
      (bv.nil? ? 1 : av <=> bv)
    end
  end

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

#search_active? ⇒ Boolean (protected)

Returns:

  • (Boolean)


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

def search_active?
  !@search_string.empty?
end

#search_add(input) ⇒ Object (protected)



1127
1128
1129
# File 'lib/osctl/cli/top/tui/main.rb', line 1127

def search_add(input)
  @search_string << input
end

#search_cancel ⇒ Object (protected)



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

def search_cancel
  search_end_focus
  @search_string = ''
end

#search_chop ⇒ Object (protected)



1131
1132
1133
# File 'lib/osctl/cli/top/tui/main.rb', line 1131

def search_chop
  @search_string.chop!
end

#search_end_focus ⇒ Object (protected)



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

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

#search_in_focus? ⇒ Boolean (protected)

Returns:

  • (Boolean)


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

def search_in_focus?
  @search_input
end

#search_start_focus ⇒ Object (protected)



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

def search_start_focus
  @search_input = true

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

#selection_down ⇒ Object (protected)



990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
# File 'lib/osctl/cli/top/tui/main.rb', line 990

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_highlight ⇒ Object (protected)



1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
# File 'lib/osctl/cli/top/tui/main.rb', line 1007

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_htop ⇒ Object (protected)



1027
1028
1029
# File 'lib/osctl/cli/top/tui/main.rb', line 1027

def selection_open_htop
  selection_open_program { %w[htop] }
end

#selection_open_program(&block) ⇒ Object (protected)



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
# File 'lib/osctl/cli/top/tui/main.rb', line 1031

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_top ⇒ Object (protected)



1023
1024
1025
# File 'lib/osctl/cli/top/tui/main.rb', line 1023

def selection_open_top
  selection_open_program { %w[top] }
end

#selection_up ⇒ Object (protected)



968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
# File 'lib/osctl/cli/top/tui/main.rb', line 968

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_modules ⇒ Object (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
526
527
528
529
530
531
532
533
# 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|
      value = rt? ? ct[:cpu_usage] : ct[:cpu_us]
      cpu = if value.nil?
              '-'
            else
              (rt? ? format_percent(value) : humanize_time_us(value)).to_s
            end
      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|
      [ct[:memory].nil? ? '-' : 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 model_thread.zfs_enabled? && 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

  if model_thread.netif_enabled?
    @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

  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_inverse ⇒ Object (protected)



940
941
942
# File 'lib/osctl/cli/top/tui/main.rb', line 940

def sort_inverse
  @sort_desc = !@sort_desc
end

#sort_next(n) ⇒ Object (protected)



926
927
928
929
930
931
932
933
934
935
936
937
938
# File 'lib/osctl/cli/top/tui/main.rb', line 926

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_fields ⇒ Object (protected)



944
945
946
947
948
949
950
951
952
# File 'lib/osctl/cli/top/tui/main.rb', line 944

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)



922
923
924
# File 'lib/osctl/cli/top/tui/main.rb', line 922

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

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



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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
# File 'lib/osctl/cli/top/tui/main.rb', line 840

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| module_totals(m, cts, data, false) }.flatten)

  Curses.setpos(Curses.lines - pos, 0)
  pos -= 1
  Curses.addstr(format('%-14s ', 'All:'))
  print_row_data(@modules[1..].map { |m| module_totals(m, cts, data, true) }.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
  view_from = view_count > 0 ? offset + 1 : 0
  page = format('[%d-%d/%d]', view_from, 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_rows ⇒ Object (protected)



832
833
834
835
836
837
838
# File 'lib/osctl/cli/top/tui/main.rb', line 832

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)



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
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/osctl/cli/top/tui/main.rb', line 604

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

  if model_thread.zfs_enabled?
    # 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

  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)



1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
# File 'lib/osctl/cli/top/tui/main.rb', line 1135

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

    else
      value = lookup_field(ct, field)
      value.nil? || acc.nil? ? nil : acc + value
    end
  end
end

#unpause ⇒ Object (protected)



1233
1234
1235
# File 'lib/osctl/cli/top/tui/main.rb', line 1233

def unpause
  @paused = false
end

#view_page_down ⇒ Object (protected)



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

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_end ⇒ Object (protected)



1094
1095
1096
1097
1098
1099
1100
# File 'lib/osctl/cli/top/tui/main.rb', line 1094

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

#view_page_reset ⇒ Object (protected)



1090
1091
1092
# File 'lib/osctl/cli/top/tui/main.rb', line 1090

def view_page_reset
  @view_page = 0
end

#view_page_up ⇒ Object (protected)



1086
1087
1088
# File 'lib/osctl/cli/top/tui/main.rb', line 1086

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

#view_window(ct_count, row_count, page) ⇒ Object (protected)



591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/osctl/cli/top/tui/main.rb', line 591

def view_window(ct_count, row_count, page)
  row_count = [row_count, 0].max

  return [0, row_count, 0, 0] if row_count == 0 || ct_count <= row_count

  page_step = [row_count / 2, 1].max
  page_max = (ct_count - row_count).fdiv(page_step).ceil
  page = page.clamp(0, page_max)
  offset = [page_step * page, ct_count - row_count].min

  [offset, row_count, page_max, page]
end