Class: ClaudeSwarm::ProcessTracker

Inherits:
Object
  • Object
show all
Defined in:
lib/claude_swarm/process_tracker.rb

Constant Summary collapse

PIDS_DIR =
"pids"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(session_path) ⇒ ProcessTracker

Returns a new instance of ProcessTracker.



7
8
9
10
11
# File 'lib/claude_swarm/process_tracker.rb', line 7

def initialize(session_path)
  @session_path = session_path
  @pids_dir = File.join(@session_path, PIDS_DIR)
  ensure_pids_directory
end

Class Method Details

.cleanup_session(session_path) ⇒ Object



64
65
66
67
68
69
# File 'lib/claude_swarm/process_tracker.rb', line 64

def cleanup_session(session_path)
  return unless Dir.exist?(File.join(session_path, PIDS_DIR))

  tracker = new(session_path)
  tracker.cleanup_all
end

Instance Method Details

#cleanup_allObject



18
19
20
21
22
23
24
25
26
27
28
29
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
61
# File 'lib/claude_swarm/process_tracker.rb', line 18

def cleanup_all
  return unless Dir.exist?(@pids_dir)

  # Get all PID files
  pid_files = Dir.glob(File.join(@pids_dir, "*"))

  pid_files.each do |pid_file|
    pid = File.basename(pid_file).to_i
    name = begin
      File.read(pid_file).strip
    rescue StandardError
      "unknown"
    end

    begin
      # Check if process is still running
      Process.kill(0, pid)
      # If we get here, process is running, so kill it
      Process.kill("TERM", pid)
      puts "✓ Terminated MCP server: #{name} (PID: #{pid})"

      # Give it a moment to terminate gracefully
      sleep(0.1)

      # Force kill if still running
      begin
        Process.kill(0, pid)
        Process.kill("KILL", pid)
        puts "  → Force killed #{name} (PID: #{pid})"
      rescue Errno::ESRCH
        # Process is gone, which is what we want
      end
    rescue Errno::ESRCH
      # Process not found, already terminated
      puts "  → MCP server #{name} (PID: #{pid}) already terminated"
    rescue Errno::EPERM
      # Permission denied
      puts "  ⚠️  No permission to terminate #{name} (PID: #{pid})"
    end
  end

  # Clean up the pids directory
  FileUtils.rm_rf(@pids_dir)
end

#track_pid(pid, name) ⇒ Object



13
14
15
16
# File 'lib/claude_swarm/process_tracker.rb', line 13

def track_pid(pid, name)
  pid_file = File.join(@pids_dir, pid.to_s)
  File.write(pid_file, name)
end