Class: Sidekiq::TUI

Inherits:
Object
  • Object
show all
Includes:
Component
Defined in:
lib/sidekiq/tui.rb,
lib/sidekiq/tui/tabs.rb,
lib/sidekiq/tui/controls.rb,
lib/sidekiq/tui/filtering.rb,
lib/sidekiq/tui/tabs/busy.rb,
lib/sidekiq/tui/tabs/dead.rb,
lib/sidekiq/tui/tabs/home.rb,
lib/sidekiq/tui/tabs/queues.rb,
lib/sidekiq/tui/tabs/metrics.rb,
lib/sidekiq/tui/tabs/retries.rb,
lib/sidekiq/tui/tabs/set_tab.rb,
lib/sidekiq/tui/tabs/base_tab.rb,
lib/sidekiq/tui/tabs/scheduled.rb

Defined Under Namespace

Modules: Controls, Filtering, Tabs Classes: BaseTab, PageOptions

Constant Summary collapse

REFRESH_INTERVAL_SECONDS =
2
LOCALE_DIRECTORIES =
[File.expand_path("#{File.dirname(__FILE__)}/../../web/locales")]

Instance Attribute Summary collapse

Attributes included from Component

#config

Instance Method Summary collapse

Methods included from Component

#default_tag, #fire_event, #handle_exception, #hostname, #identity, #inspect, #logger, #mono_ms, #process_nonce, #real_ms, #redis, #safe_thread, #tid, #watchdog

Constructor Details

#initialize(cfg, language: ENV["LANG"] || "en") ⇒ TUI

language is meant to be a locale code, e.g. LANG=en_US.utf-8



28
29
30
31
32
33
34
35
36
# File 'lib/sidekiq/tui.rb', line 28

def initialize(cfg, language: ENV["LANG"] || "en")
  @lang = language
  @config = cfg
  @base_style = nil
  @last_refresh = Time.at(0)
  @fps = Array.new(2) { 0 }
  @previous_fps = 0
  @showing = :main
end

Instance Attribute Details

#langObject (readonly)

Returns the value of attribute lang.



24
25
26
# File 'lib/sidekiq/tui.rb', line 24

def lang
  @lang
end

Instance Method Details

#allObject



295
296
297
# File 'lib/sidekiq/tui.rb', line 295

def all
  @all ||= Tabs::All.map { |kls| kls.new(self) }
end

#available_localesObject



335
336
337
# File 'lib/sidekiq/tui.rb', line 335

def available_locales
  @@available_locales ||= Set.new(locale_files.map { |path| File.basename(path, ".yml") })
end

#current_tabObject



299
300
301
# File 'lib/sidekiq/tui.rb', line 299

def current_tab
  @current ||= @all.first
end

#debugging?Boolean

Returns:

  • (Boolean)


378
379
380
# File 'lib/sidekiq/tui.rb', line 378

def debugging?
  !!ENV["DEBUG"]
end

#find_locale_files(lang) ⇒ Object



339
340
341
# File 'lib/sidekiq/tui.rb', line 339

def find_locale_files(lang)
  locale_files.select { |file| file =~ /\/#{lang}\.yml$/ }
end

#handle_inputObject



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/sidekiq/tui.rb', line 228

def handle_input
  # We shouldn't need more than 10 FPS for a data-oriented app.
  # This throttles down our CPU usage. Default is 60 FPS.
  case @tui.poll_event(timeout: 0.1)
  in {type: :key, code: "esc"} if @showing == :help
    @showing = :main
  in {type: :key, code: code} if current_tab.filtering? && code.length == 1
    current_tab.append_to_filter(code)
    current_tab.refresh_data
  in {type: :key, code:, modifiers:}
    control = current_tab.controls.find { |ctrl|
      ctrl[:code] == code &&
        (ctrl[:modifiers] || []) == (modifiers || [])
    }
    return unless control
    control[:action].call(self, current_tab).tap {
      refresh_data if control[:refresh]
    }
  else
    # Ignore other events
  end
rescue => ex
  logger.error { [ex.message, ex.backtrace] }
end

#load_localeObject



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/sidekiq/tui.rb', line 343

def load_locale
  require "yaml"
  lang = @lang.split(".").first # "en_US"
  while lang.size > 0
    hash = load_strings(lang)
    if hash.size > 0
      # found a working language dataset
      @lang = lang
      @strings = hash
      Sidekiq.logger.debug { "using the #{lang} locale" }
      break
    end
    # Try "en_US", "en_U", "en_", "en"
    # It's ugly and bruteforce but it works
    lang = lang[..-2]
  end
end

#load_strings(lang) ⇒ Object



320
321
322
323
324
325
326
327
# File 'lib/sidekiq/tui.rb', line 320

def load_strings(lang)
  {}.tap do |all|
    find_locale_files(lang).each do |file|
      strs = YAML.safe_load_file(file)
      all.merge! strs[lang]
    end
  end
end

#locale_filesObject



329
330
331
332
333
# File 'lib/sidekiq/tui.rb', line 329

def locale_files
  @@locale_files ||= LOCALE_DIRECTORIES.flat_map { |path|
    Dir["#{path}/*.yml"]
  }
end

Navigate tabs to the left or right.

Parameters:

  • direction (Symbol)

    :left or :right



305
306
307
308
309
# File 'lib/sidekiq/tui.rb', line 305

def navigate(direction)
  index_change = (direction == :right) ? 1 : -1
  @current = @all[(@all.index(current_tab) + index_change) % @all.size]
  @current.reset_data
end

#prepare(tui) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/sidekiq/tui.rb', line 38

def prepare(tui)
  load_locale

  @tui = tui
  @highlight_style = @tui.style(fg: :light_red, modifiers: [:underlined])
  @hotkey_style = @tui.style(modifiers: [:bold, :underlined])
  # eager load tabs
  all
end

#previous_fpsObject



368
369
370
371
372
373
374
375
376
# File 'lib/sidekiq/tui.rb', line 368

def previous_fps
  curidx = Time.now.to_i % 2
  prev = (curidx == 1) ? 0 : 1
  if (val = @fps[prev]) != 0
    @previous_fps = val
    @fps[prev] = 0
  end
  @previous_fps
end

#redis_urlObject



253
254
255
256
257
258
259
# File 'lib/sidekiq/tui.rb', line 253

def redis_url
  Sidekiq.redis do |conn|
    conn.config.server_url
  end
rescue
  "N/A"
end

#refresh_dataObject



265
266
267
268
269
270
271
272
# File 'lib/sidekiq/tui.rb', line 265

def refresh_data
  # logger.info GC.stat
  current_tab.refresh_data
  @last_refresh = Time.now
rescue => e
  handle_exception(e)
  current_tab.error = e
end

#renderObject



59
60
61
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
# File 'lib/sidekiq/tui.rb', line 59

def render
  track_fps do
    if @showing == :main
      @tui.draw do |frame|
        main_area, controls_area = @tui.layout_split(
          frame.area,
          direction: :vertical,
          constraints: [
            @tui.constraint_fill(1),
            @tui.constraint_length(5)
          ]
        )

        # Split main area into tabs and content
        tabs_area, content_area = @tui.layout_split(
          main_area,
          direction: :vertical,
          constraints: [
            @tui.constraint_length(3),
            @tui.constraint_fill(1)
          ]
        )

        all_tabs = all
        tabs = @tui.tabs(
          titles: all_tabs.map { |tab| t(tab.name) },
          selected_index: all_tabs.index(current_tab),
          block: @tui.block(title: " #{Sidekiq::NAME}", borders: [:all], title_style: @tui.style(fg: :light_red, modifiers: [:bold])),
          divider: " | ",
          highlight_style: @highlight_style,
          style: @base_style
        )
        frame.render_widget(tabs, tabs_area)

        render_content_area(frame, content_area)
        render_controls(frame, controls_area)
      end
    end

    if @showing == :help
      @tui.draw do |frame|
        main_area, controls_area = @tui.layout_split(
          frame.area,
          direction: :vertical,
          constraints: [
            @tui.constraint_fill(1),
            @tui.constraint_length(4)
          ]
        )
        content = @tui.block(
          title: " #{Sidekiq::NAME} ",
          borders: [:all],
          title_style: @tui.style(fg: :light_red, modifiers: [:bold]),
          children: [
            # TODO convert to table
            @tui.paragraph(
              text: [
                @tui.text_line(spans: ["Welcome to the Sidekiq Terminal UI"], alignment: :center),
                @tui.text_line(spans: [
                  @tui.text_span(content: "Global hotkeys")
                ]),
                @tui.text_line(spans: []),
                @tui.text_line(spans: [
                  @tui.text_span(content: "Esc", style: @hotkey_style),
                  @tui.text_span(content: ": Close this window")
                ]),
                @tui.text_line(spans: [
                  @tui.text_span(content: "←/→", style: @hotkey_style),
                  @tui.text_span(content: ": Move between tabs")
                ]),
                @tui.text_line(spans: [
                  @tui.text_span(content: "h/l", style: @hotkey_style),
                  @tui.text_span(content: ": Move to prev/next page of data")
                ]),
                @tui.text_line(spans: [
                  @tui.text_span(content: "j/k", style: @hotkey_style),
                  @tui.text_span(content: ": Move to prev/next row in current page")
                ]),
                @tui.text_line(spans: [
                  @tui.text_span(content: "x", style: @hotkey_style),
                  @tui.text_span(content: ": Select/deselect current row")
                ]),
                @tui.text_line(spans: [
                  @tui.text_span(content: "A", style: @hotkey_style),
                  @tui.text_span(content: ": Select/deselect All rows in current page")
                ]),
                @tui.text_line(spans: [
                  @tui.text_span(content: "q", style: @hotkey_style),
                  @tui.text_span(content: ": Quit")
                ])
              ]
            )
          ]
        )
        frame.render_widget(content, main_area)
        controls = @tui.block(
          title: t("Controls"),
          borders: [:all],
          children: [
            @tui.paragraph(
              text: [
                @tui.text_line(spans: [
                  @tui.text_span(content: "Esc", style: @hotkey_style),
                  @tui.text_span(content: ": Close  ")
                ])
              ]
            )
          ]
        )
        frame.render_widget(controls, controls_area)
      end
    end
  end
end

#render_content_area(frame, content_area) ⇒ Object



174
175
176
177
178
# File 'lib/sidekiq/tui.rb', line 174

def render_content_area(frame, content_area)
  return render_error(frame, content_area, current_tab.error) if current_tab.error

  current_tab.render(@tui, frame, content_area)
end

#render_controls(frame, area) ⇒ Object



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
217
218
219
220
221
222
223
224
225
226
# File 'lib/sidekiq/tui.rb', line 180

def render_controls(frame, area)
  active_keys = current_tab.controls.filter { |hash| hash[:description] }

  # Split controls into two lines, 8 is arbitrary
  # TODO Dynamically split based on term width?
  first = active_keys[...8]
  lines = []
  lines << @tui.text_line(spans: first.map { |hash|
    [
      @tui.text_span(content: hash[:display] || hash[:code], style: @hotkey_style),
      @tui.text_span(content: ": #{t(hash[:description])}  ")
    ]
  }.flatten)

  last = active_keys[8...]
  lines << if last && last.size > 0
    @tui.text_line(spans: last.map { |hash|
      [
        @tui.text_span(content: hash[:display] || hash[:code], style: @hotkey_style),
        @tui.text_span(content: ": #{t(hash[:description])}  ")
      ]
    }.flatten)
  else
    @tui.text_line(spans: [])
  end

  footer = [
    @tui.text_span(content: "Redis: #{redis_url}    "),
    @tui.text_span(content: "#{t("Now")}: #{Time.now.utc}    "),
    @tui.text_span(content: "#{t("Locale")}: #{@lang}")
  ]

  if current_tab.data[:filter]
    @filter_style = @tui.style(fg: :white, bg: :dark_gray)
    footer += [
      @tui.text_span(content: "   #{t("Filter")}: ", style: @filter_style),
      @tui.text_span(content: current_tab.data[:filter], style: @filter_style),
      @tui.text_span(content: "_", style: @tui.style(fg: :white, bg: :dark_gray, modifiers: [:slow_blink]))
    ]
  end
  footer << @tui.text_span(content: "  FPS: #{previous_fps}") if debugging?
  lines << @tui.text_line(spans: footer)

  controls = @tui.block(title: t("Controls"), borders: [:all],
    children: [@tui.paragraph(text: lines)])
  frame.render_widget(controls, area)
end

#render_error(frame, area, err) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/sidekiq/tui.rb', line 274

def render_error(frame, area, err)
  header = [@tui.text_line(
    spans: [@tui.text_span(content: err.message, style: @tui.style(modifiers: [:bold]))],
    alignment: :center
  )]
  lines = Array(err.backtrace).map { |line| @tui.text_line(spans: [@tui.text_span(content: line)]) }

  frame.render_widget(
    @tui.paragraph(
      text: header + lines,
      alignment: :left,
      block: @tui.block(title: t("Error"), borders: [:all], border_style: @tui.style(fg: :light_red))
    ),
    area
  )
end

#run_loopObject



48
49
50
51
52
53
54
55
56
57
# File 'lib/sidekiq/tui.rb', line 48

def run_loop
  # Must log to a file, terminal is now controlled by Ratatui
  config.logger = Logger.new("tui.log")

  loop do
    refresh_data if should_refresh?
    render
    break if handle_input == :quit
  end
end

#should_refresh?Boolean

Returns:

  • (Boolean)


261
262
263
# File 'lib/sidekiq/tui.rb', line 261

def should_refresh?
  Time.now - @last_refresh >= REFRESH_INTERVAL_SECONDS
end

#show_helpObject



291
292
293
# File 'lib/sidekiq/tui.rb', line 291

def show_help
  @showing = :help
end

#t(msg, options = nil) ⇒ Object



311
312
313
314
315
316
317
318
# File 'lib/sidekiq/tui.rb', line 311

public def t(msg, options = nil)
  string = @strings[msg] || msg
  if options.nil?
    string
  else
    string % options
  end
end

#track_fpsObject



361
362
363
364
365
366
# File 'lib/sidekiq/tui.rb', line 361

def track_fps
  # We hold two fps buckets: one for current second, one for previous second
  idx = Time.now.to_i % 2
  @fps[idx] += 1
  yield
end