Module: DebugSocket

Defined in:
lib/debug_socket.rb,
lib/debug_socket/version.rb

Constant Summary collapse

VERSION =
"0.1.8"

Class Method Summary collapse

Class Method Details

.backtraceObject



64
65
66
67
68
69
70
71
72
73
# File 'lib/debug_socket.rb', line 64

def self.backtrace
  pid = Process.pid
  "#{Time.now.utc.iso8601} #{$PROGRAM_NAME}\n" + Thread.list.map do |thread|
    output =
      +"#{Time.now.utc.iso8601} pid=#{pid} thread.object_id=#{thread.object_id} thread.status=#{thread.status}"
    backtrace = thread.backtrace || []
    output << "\n#{backtrace.join("\n")}" if backtrace
    output
  end.join("\n\n")
end

.loggerObject



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

def self.logger
  return @logger if defined?(@logger)

  require "logger"
  @logger = Logger.new(STDERR)
end

.logger=(logger) ⇒ Object



11
12
13
# File 'lib/debug_socket.rb', line 11

def self.logger=(logger)
  @logger = logger
end

.start(path) ⇒ Object



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
# File 'lib/debug_socket.rb', line 22

def self.start(path)
  pid = Process.pid
  raise "debug socket thread already running for this process" if @thread && @pid == pid

  @pid = pid

  # make sure socket is only accessible to the process owner
  old_mask = File.umask(0o0177)

  @path = path.to_s

  server = UNIXServer.new(@path)
  @thread = Thread.new do
    loop do
      begin
        socket = server.accept
        input = socket.read
        logger&.warn("debug-socket-command=#{input.inspect}")
        socket.puts(eval(input)) # rubocop:disable Security/Eval
      rescue Exception => e # rubocop:disable Lint/RescueException
        logger&.error { "debug-socket-error=#{e.inspect} backtrace=#{e.backtrace.inspect}" }
      ensure
        socket&.close
      end
    end
  end

  logger&.unknown { "Debug socket listening on #{@path}" }

  @thread
ensure
  File.umask(old_mask) if old_mask
end

.stopObject



56
57
58
59
60
61
62
# File 'lib/debug_socket.rb', line 56

def self.stop
  @thread&.kill
  File.unlink(@path) if @path && File.exist?(@path)
  @thread = nil
  @pid = nil
  @path = nil
end