Class: Hiiro::ServiceManager

Inherits:
Object
  • Object
show all
Defined in:
lib/hiiro/service_manager.rb

Constant Summary collapse

CONFIG_FILE =
File.join(Dir.home, '.config', 'hiiro', 'services.yml')
STATE_DIR =
File.join(Dir.home, '.config', 'hiiro', 'services')
STATE_FILE =
File.join(STATE_DIR, 'running.yml')
ENV_TEMPLATES_DIR =
File.join(Dir.home, '.config', 'hiiro', 'env_templates')

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_file: CONFIG_FILE, state_file: STATE_FILE) ⇒ ServiceManager

Returns a new instance of ServiceManager.



22
23
24
25
# File 'lib/hiiro/service_manager.rb', line 22

def initialize(config_file: CONFIG_FILE, state_file: STATE_FILE)
  @config_file = config_file
  @state_file = state_file
end

Instance Attribute Details

#config_fileObject (readonly)

Returns the value of attribute config_file.



13
14
15
# File 'lib/hiiro/service_manager.rb', line 13

def config_file
  @config_file
end

#state_fileObject (readonly)

Returns the value of attribute state_file.



13
14
15
# File 'lib/hiiro/service_manager.rb', line 13

def state_file
  @state_file
end

Class Method Details

.add_resolvers(hiiro) ⇒ Object



15
16
17
18
19
20
# File 'lib/hiiro/service_manager.rb', line 15

def self.add_resolvers(hiiro)
  sm = new
  hiiro.add_resolver(:service, -> { hiiro.fuzzyfind(sm.services.keys) }) do |name|
    sm.find_service(name)&.[](:name)
  end
end

.build_hiiro(parent_hiiro, sm, task_manager: nil) ⇒ Object



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
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
593
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
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/hiiro/service_manager.rb', line 439

def self.build_hiiro(parent_hiiro, sm, task_manager: nil)
  parent_hiiro.make_child(:service) do |h|
    h.add_subcmd(:ls) do
      configs = sm.services
      if configs.empty?
        puts "No services configured."
        puts "Use 'service add' to add one, or edit #{sm.config_file}"
        next
      end

      running = sm.running_services
      puts "Services:"
      puts
      configs
        .sort_by{ |name,_| running.key?(name) ? :running : :stopped }
        .each do |name, cfg|
          is_running = running.key?(name)
          status_emoji = is_running ? "🟢" : "🔴"
          host = cfg['host'] || 'localhost'
          url_str = cfg['port'] ? " #{host}:#{cfg['port']}" : ""
          extra = ""
          if is_running
            info = running[name]
            task = task_manager&.task_by_service_info(info)
            branch = task&.branch
            parts = [info['task'], branch].compact.reject(&:empty?)
            extra = "  (#{parts.join(' • ')})" unless parts.empty?
          end
          puts format("  %-20s  %s%s%s", name, status_emoji, url_str, extra)
      end
    end

    h.add_subcmd(:list) do
      h.run_subcmd(:ls)
    end

    h.add_subcmd(:start) do |svc_name=nil, *extra_args|
      unless svc_name
        all = sm.services.keys
        if all.empty?
          puts "No services configured"
          next
        end
        svc_name = h.fuzzyfind(all)
        next unless svc_name
      end

      # Parse --use flags from extra_args
      variation_overrides = {}
      extra_args.each_with_index do |arg, i|
        if arg == '--use' && extra_args[i + 1]
          key, val = extra_args[i + 1].split('=', 2)
          variation_overrides[key] = val if key && val
        elsif arg.start_with?('--use=')
          key, val = arg.sub('--use=', '').split('=', 2)
          variation_overrides[key] = val if key && val
        end
      end

      tmux_info = {
        session: h.tmux_client.current_session&.name,
      }

      task_info = {}
      if task_manager
        task = task_manager.current_task
        if task
          task_info = {
            task_name: task.name,
            tree: task.tree_name,
            branch: task.branch,
            session: task.session_name,
          }
        end
      end

      # Check if it's a group or individual service
      group = sm.find_group(svc_name)
      if group
        sm.start_group(svc_name, tmux_info: tmux_info, task_info: task_info)
      else
        sm.start(svc_name, tmux_info: tmux_info, task_info: task_info, variation_overrides: variation_overrides)
      end
    end

    h.add_subcmd(:stop) do |svc_name=nil|
      unless svc_name
        running = sm.running_services.keys
        if running.empty?
          puts "No running services"
          next
        end
        svc_name = h.fuzzyfind(running)
        next unless svc_name
      end

      # Check if it's a group or individual service
      group = sm.find_group(svc_name)
      if group
        sm.stop_group(svc_name)
      else
        sm.stop(svc_name)
      end
    end

    h.add_subcmd(:reset) do |svc_name=nil|
      unless svc_name
        running = sm.running_services.keys
        if running.empty?
          puts "No running services"
          next
        end
        svc_name = h.fuzzyfind(running)
        next unless svc_name
      end

      # Check if it's a group or individual service
      group = sm.find_group(svc_name)
      if group
        sm.reset_group(svc_name)
      else
        sm.reset(svc_name)
      end
    end

    h.add_subcmd(:clean) do
      sm.clean
    end

    h.add_subcmd(:attach) do |svc_name=nil|
      unless svc_name
        running = sm.running_services.keys
        if running.empty?
          puts "No running services"
          next
        end
        svc_name = h.fuzzyfind(running)
        next unless svc_name
      end

      sm.attach(svc_name)
    end

    h.add_subcmd(:open) do |svc_name=nil|
      unless svc_name
        puts "Usage: service open <name>"
        next
      end

      svc_url = sm.url(svc_name)
      if svc_url
        system('open', svc_url)
      else
        puts "No URL configured for '#{svc_name}'"
      end
    end

    h.add_subcmd(:url) do |svc_name=nil|
      unless svc_name
        puts "Usage: service url <name>"
        next
      end

      svc_url = sm.url(svc_name)
      if svc_url
        puts svc_url
      else
        puts "No URL configured for '#{svc_name}'"
      end
    end

    h.add_subcmd(:port) do |svc_name=nil|
      unless svc_name
        puts "Usage: service port <name>"
        next
      end

      p = sm.port(svc_name)
      if p
        puts p
      else
        puts "No port configured for '#{svc_name}'"
      end
    end

    h.add_subcmd(:status) do |svc_name=nil|
      unless svc_name
        running = sm.running_services.keys
        if running.empty?
          puts "No running services"
          next
        end
        svc_name = h.fuzzyfind(running)
        next unless svc_name
      end

      sm.status(svc_name)
    end

    h.add_subcmd(:add) do |*add_args|
      template = {
        'base_dir' => '',
        'host' => 'localhost',
        'port' => '',
        'init' => [],
        'start' => [''],
        'cleanup' => [],
        'env_files' => [
          { 'env_file' => '.env', 'base_env' => '', 'env_vars' => {} },
        ],
      }

      input = InputFile.yaml_file(hiiro: h, content: YAML.dump({ 'new_service' => template }), prefix: 'service')
      input.edit

      begin
        data = input.parsed_file(permitted_classes: [Symbol]) || {}
        data.each do |name, cfg|
          sm.add_service({ 'name' => name }.merge(cfg || {}))
        end
      rescue => e
        puts "Error parsing config: #{e.message}"
      ensure
        input.cleanup
      end
    end

    h.add_subcmd(:rm) do |svc_name=nil|
      unless svc_name
        puts "Usage: service rm <name>"
        next
      end

      sm.remove_service(svc_name)
    end

    h.add_subcmd(:remove) do |svc_name=nil|
      unless svc_name
        puts "Usage: service remove <name>"
        next
      end

      sm.remove_service(svc_name)
    end

    h.add_subcmd(:config) do
      h.edit_files(sm.config_file)
    end

    h.add_subcmd(:groups) do
      configs = sm.services
      groups = configs.select { |_, v| v.is_a?(Hash) && v.key?('services') }

      if groups.empty?
        puts "No service groups configured."
        next
      end

      puts "Service groups:"
      puts
      groups.each do |name, cfg|
        members = (cfg['services'] || []).map { |m| m['name'] || m[:name] }.compact
        puts format("  %-20s  %s", name, members.join(', '))
      end
    end

    h.add_subcmd(:env) do |svc_name=nil|
      unless svc_name
        puts "Usage: service env <name>"
        next
      end

      svc = sm.find_service(svc_name)
      unless svc
        puts "Service '#{svc_name}' not found"
        next
      end

      configs = sm.send(:build_env_file_configs, svc)
      if configs.empty?
        puts "No env files configured for '#{svc[:name]}'"
        next
      end

      puts "Env files for '#{svc[:name]}':"
      configs.each do |efc|
        puts
        puts "  #{efc[:env_file] || '(no dest)'}"
        puts "    template: #{efc[:base_env]}" if efc[:base_env]

        env_vars = efc[:env_vars]
        next unless env_vars

        env_vars.each do |var_name, var_config|
          variations = var_config.is_a?(Hash) && (var_config['variations'] || var_config[:variations])
          next unless variations

          puts "    #{var_name}:"
          variations.each do |variation, value|
            puts "      #{variation}: #{value}"
          end
        end
      end
    end
  end
end

Instance Method Details

#add_service(config_hash) ⇒ Object



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/hiiro/service_manager.rb', line 407

def add_service(config_hash)
  name = config_hash.delete('name') || config_hash.delete(:name)
  unless name
    puts "Service name required"
    return false
  end

  configs = load_config
  if configs.key?(name)
    puts "Service '#{name}' already exists"
    return false
  end

  configs[name] = config_hash.transform_keys(&:to_s)
  save_config(configs)
  puts "Added service '#{name}'"
  true
end

#attach(name) ⇒ Object



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
# File 'lib/hiiro/service_manager.rb', line 324

def attach(name)
  svc = find_service(name)
  unless svc
    puts "Service '#{name}' not found"
    return false
  end

  svc_name = svc[:name]
  unless running?(svc_name)
    puts "Service '#{svc_name}' is not running"
    return false
  end

  info = running_services[svc_name]
  pane_id = info['tmux_pane']
  session = info['tmux_session']
  window = info['tmux_window']

  if session
    system('tmux', 'switch-client', '-t', session)
  end

  if window
    system('tmux', 'select-window', '-t', window)
  end

  if pane_id
    system('tmux', 'select-pane', '-t', pane_id)
  end

  true
end

#cleanObject



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/hiiro/service_manager.rb', line 194

def clean
  state = load_state
  return puts("No running services to clean") if state.empty?

  stale = state.select { |_, info| stale_pane?(info['tmux_pane']) }
  if stale.empty?
    puts "All running services have live panes"
    return false
  end

  stale.each do |svc_name, _|
    state.delete(svc_name)
    puts "Cleaned stale service '#{svc_name}'"
  end
  save_state(state)
  true
end

#find_group(name) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/hiiro/service_manager.rb', line 42

def find_group(name)
  configs = services
  names = configs.keys.select { |k| configs[k].is_a?(Hash) && configs[k].key?('services') }
  return nil if names.empty?

  structs = names.map { |k| OpenStruct.new(name: k) }
  result = Hiiro::Matcher.new(structs, :name).by_prefix(name)
  match = result.resolved || result.first
  return nil unless match

  group_name = match.item.name
  { name: group_name, **symbolize_keys(configs[group_name]) }
end

#find_service(name) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/hiiro/service_manager.rb', line 31

def find_service(name)
  configs = services
  names = configs.keys.map { |k| OpenStruct.new(name: k) }
  result = Hiiro::Matcher.new(names, :name).by_prefix(name)
  match = result.resolved || result.first
  return nil unless match

  svc_name = match.item.name
  { name: svc_name, **symbolize_keys(configs[svc_name]) }
end

#host(name) ⇒ Object



373
374
375
376
# File 'lib/hiiro/service_manager.rb', line 373

def host(name)
  svc = find_service(name)
  svc&.[](:host) || 'localhost'
end

#port(name) ⇒ Object



368
369
370
371
# File 'lib/hiiro/service_manager.rb', line 368

def port(name)
  svc = find_service(name)
  svc&.[](:port)
end

#prepare_env(svc_name, variation_overrides: {}) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hiiro/service_manager.rb', line 56

def prepare_env(svc_name, variation_overrides: {})
  svc = find_service(svc_name)
  return unless svc

  base_dir = resolve_base_dir(svc[:base_dir])

  env_file_configs = build_env_file_configs(svc)
  return if env_file_configs.empty?

  env_file_configs.each do |efc|
    prepare_single_env(base_dir, efc, variation_overrides)
  end
end

#remove_service(name) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/hiiro/service_manager.rb', line 426

def remove_service(name)
  configs = load_config
  unless configs.key?(name)
    puts "Service '#{name}' not found"
    return false
  end

  configs.delete(name)
  save_config(configs)
  puts "Removed service '#{name}'"
  true
end

#reset(name) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/hiiro/service_manager.rb', line 174

def reset(name)
  svc = find_service(name)
  unless svc
    puts "Service '#{name}' not found"
    return false
  end

  svc_name = svc[:name]
  state = load_state
  unless state.key?(svc_name)
    puts "Service '#{svc_name}' is not in running state"
    return false
  end

  state.delete(svc_name)
  save_state(state)
  puts "Reset service '#{svc_name}' (cleared from running state)"
  true
end

#reset_group(name) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/hiiro/service_manager.rb', line 143

def reset_group(name)
  group = find_group(name)
  unless group
    puts "Group '#{name}' not found"
    return false
  end

  members = group[:services]
  unless members && !members.empty?
    puts "Group '#{group[:name]}' has no services"
    return false
  end

  puts "Resetting group '#{group[:name]}'..."

  members.each do |member|
    member_name = member['name'] || member[:name]
    reset(member_name)
  end
  true
end

#running?(name) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
168
# File 'lib/hiiro/service_manager.rb', line 165

def running?(name)
  state = load_state
  state.key?(name)
end

#running_servicesObject



170
171
172
# File 'lib/hiiro/service_manager.rb', line 170

def running_services
  load_state
end

#servicesObject



27
28
29
# File 'lib/hiiro/service_manager.rb', line 27

def services
  load_config
end

#services_for_dir(base_dir) ⇒ Object



402
403
404
405
# File 'lib/hiiro/service_manager.rb', line 402

def services_for_dir(base_dir)
  configs = services
  configs.select { |_, v| v['base_dir'] == base_dir }
end

#start(name, tmux_info: {}, task_info: {}, variation_overrides: {}, skip_env: false, skip_window_creation: false) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
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
# File 'lib/hiiro/service_manager.rb', line 212

def start(name, tmux_info: {}, task_info: {}, variation_overrides: {}, skip_env: false, skip_window_creation: false)
  svc = find_service(name)
  unless svc
    puts "Service '#{name}' not found"
    return false
  end

  svc_name = svc[:name]

  if running?(svc_name)
    info = running_services[svc_name]
    puts "Service '#{svc_name}' is already running (pid: #{info['pid']}, pane: #{info['tmux_pane']})"
    return false
  end

  start_cmd = svc[:start]
  unless start_cmd
    puts "No start command configured for '#{svc_name}'"
    return false
  end

  # Build separate init/env/start scripts + a launcher that runs them in order
  init_cmds = Array(svc[:init] || [])
  start_cmds = Array(start_cmd)
  script = write_launcher_script(
    svc_name,
    init_cmds: init_cmds,
    start_cmds: start_cmds,
    env_prep: !skip_env,
    variation_overrides: variation_overrides,
  )

  base_dir = resolve_base_dir(svc[:base_dir])
  session = tmux_info[:session] || current_tmux_session

  if session && !skip_window_creation
    # Create a new tmux window for this service
    window_target, pane_id = create_tmux_window(session, svc_name)
  elsif session && skip_window_creation
    # Pane already created by start_group
    pane_id = tmux_info[:pane]
    window_target = tmux_info[:window]
  else
    pane_id = nil
    window_target = nil
  end

  if pane_id
    send_to_pane(pane_id, base_dir, script)
  else
    system("cd #{base_dir} && #{script} &")
  end

  # Record state
  state = load_state
  state[svc_name] = {
    'pid' => nil,
    'tmux_session' => session || tmux_info[:session],
    'tmux_window' => window_target || tmux_info[:window],
    'tmux_pane' => pane_id,
    'task' => task_info[:task_name],
    'tree' => task_info[:tree],
    'branch' => task_info[:branch],
    'started_at' => Time.now.iso8601,
  }
  save_state(state)

  puts "Started service '#{svc_name}'"
  true
end

#start_group(name, tmux_info: {}, task_info: {}) ⇒ Object



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
# File 'lib/hiiro/service_manager.rb', line 70

def start_group(name, tmux_info: {}, task_info: {})
  group = find_group(name)
  unless group
    puts "Group '#{name}' not found"
    return false
  end

  members = group[:services]
  unless members && !members.empty?
    puts "Group '#{group[:name]}' has no services"
    return false
  end

  session = tmux_info[:session] || current_tmux_session
  unless session
    puts "tmux is required to start a service group"
    return false
  end

  puts "Starting group '#{group[:name]}'..."

  # Create one window for the group, split panes for each service
  window_target, first_pane_id = create_tmux_window(session, group[:name])
  last_pane_id = first_pane_id

  members.each_with_index do |member, idx|
    member_name = member['name'] || member[:name]
    use_overrides = member['use'] || member[:use] || {}

    svc = find_service(member_name)
    next unless svc

    if idx == 0
      pane_id = first_pane_id
    else
      # Split from the last pane so each new pane is distinct
      pane_id = split_tmux_pane(window_target, last_pane_id)
      last_pane_id = pane_id
    end

    member_tmux_info = tmux_info.merge(
      session: session,
      window: window_target,
      pane: pane_id,
    )

    start(member_name, tmux_info: member_tmux_info, task_info: task_info, variation_overrides: use_overrides, skip_window_creation: true)
  end
  true
end

#status(name) ⇒ Object



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/hiiro/service_manager.rb', line 378

def status(name)
  svc = find_service(name)
  unless svc
    puts "Service '#{name}' not found"
    return
  end

  svc_name = svc[:name]
  puts "Service: #{svc_name}"
  puts "Base dir: #{svc[:base_dir] || '(none)'}"
  puts "URL: #{url(svc_name) || '(none)'}"

  if running?(svc_name)
    info = running_services[svc_name]
    puts "Status: running"
    puts "PID: #{info['pid'] || '(unknown)'}"
    puts "Pane: #{info['tmux_pane'] || '(unknown)'}"
    puts "Task: #{info['task'] || '(none)'}"
    puts "Started: #{info['started_at']}"
  else
    puts "Status: stopped"
  end
end

#stop(name) ⇒ Object



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
# File 'lib/hiiro/service_manager.rb', line 283

def stop(name)
  svc = find_service(name)
  unless svc
    puts "Service '#{name}' not found"
    return false
  end

  svc_name = svc[:name]

  unless running?(svc_name)
    puts "Service '#{svc_name}' is not running"
    return false
  end

  info = running_services[svc_name]
  pane_id = info['tmux_pane']

  if svc[:stop] && !svc[:stop].to_s.strip.empty?
    stop_cmd = svc[:stop]
    if info['pid']
      stop_cmd = stop_cmd.gsub('$PID', info['pid'].to_s)
    end
    system(stop_cmd)
  elsif pane_id
    system('tmux', 'send-keys', '-t', pane_id, 'C-c')
  end

  # Run cleanup commands
  if svc[:cleanup]
    svc[:cleanup].each { |cmd| system(cmd) }
  end

  # Remove from state
  state = load_state
  state.delete(svc_name)
  save_state(state)

  puts "Stopped service '#{svc_name}'"
  true
end

#stop_group(name) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/hiiro/service_manager.rb', line 121

def stop_group(name)
  group = find_group(name)
  unless group
    puts "Group '#{name}' not found"
    return false
  end

  members = group[:services]
  unless members && !members.empty?
    puts "Group '#{group[:name]}' has no services"
    return false
  end

  puts "Stopping group '#{group[:name]}'..."

  members.each do |member|
    member_name = member['name'] || member[:name]
    stop(member_name)
  end
  true
end

#url(name) ⇒ Object



357
358
359
360
361
362
363
364
365
366
# File 'lib/hiiro/service_manager.rb', line 357

def url(name)
  svc = find_service(name)
  return nil unless svc

  host = svc[:host] || 'localhost'
  port = svc[:port]
  return nil unless port

  "http://#{host}:#{port}"
end