bluepill 0.2.9 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +111 -2
  3. data/README.md +16 -13
  4. data/bin/bluepill +21 -8
  5. data/bluepill.gemspec +7 -2
  6. data/lib/bluepill/application/lifecycle.rb +48 -35
  7. data/lib/bluepill/application/listener.rb +2 -4
  8. data/lib/bluepill/application/previous_daemon.rb +12 -14
  9. data/lib/bluepill/application.rb +36 -30
  10. data/lib/bluepill/base_directory.rb +18 -20
  11. data/lib/bluepill/check_registry.rb +104 -0
  12. data/lib/bluepill/clock.rb +1 -3
  13. data/lib/bluepill/condition_watch.rb +46 -54
  14. data/lib/bluepill/controller/directory.rb +1 -3
  15. data/lib/bluepill/controller.rb +35 -37
  16. data/lib/bluepill/daemonize.rb +52 -0
  17. data/lib/bluepill/dsl/app_proxy.rb +68 -64
  18. data/lib/bluepill/dsl/attributes.rb +135 -0
  19. data/lib/bluepill/dsl/process_factory/child_factory.rb +83 -0
  20. data/lib/bluepill/dsl/process_factory/registry.rb +4 -26
  21. data/lib/bluepill/dsl/process_factory.rb +85 -84
  22. data/lib/bluepill/dsl/process_proxy.rb +80 -160
  23. data/lib/bluepill/dsl.rb +16 -15
  24. data/lib/bluepill/errors.rb +190 -0
  25. data/lib/bluepill/group.rb +14 -37
  26. data/lib/bluepill/logger.rb +65 -99
  27. data/lib/bluepill/process/attributes.rb +66 -32
  28. data/lib/bluepill/process/children.rb +6 -7
  29. data/lib/bluepill/process/pid.rb +43 -35
  30. data/lib/bluepill/process/state_machine.rb +15 -59
  31. data/lib/bluepill/process/stop_signals.rb +123 -0
  32. data/lib/bluepill/process/transition.rb +1 -3
  33. data/lib/bluepill/process/transition_callbacks.rb +2 -16
  34. data/lib/bluepill/process/triggers.rb +90 -0
  35. data/lib/bluepill/process/user_commands.rb +1 -1
  36. data/lib/bluepill/process/watches.rb +9 -23
  37. data/lib/bluepill/process.rb +55 -52
  38. data/lib/bluepill/process_commands/execution.rb +16 -24
  39. data/lib/bluepill/process_commands/hooks.rb +1 -31
  40. data/lib/bluepill/process_commands/stop_signals.rb +12 -17
  41. data/lib/bluepill/process_commands.rb +10 -8
  42. data/lib/bluepill/process_conditions/always_true.rb +2 -6
  43. data/lib/bluepill/process_conditions/below_threshold.rb +6 -8
  44. data/lib/bluepill/process_conditions/cpu_usage.rb +1 -4
  45. data/lib/bluepill/process_conditions/file_time.rb +8 -9
  46. data/lib/bluepill/process_conditions/http.rb +29 -67
  47. data/lib/bluepill/process_conditions/mem_usage.rb +7 -45
  48. data/lib/bluepill/process_conditions/process_condition.rb +29 -47
  49. data/lib/bluepill/process_conditions/zombie_process.rb +2 -6
  50. data/lib/bluepill/process_conditions.rb +5 -14
  51. data/lib/bluepill/process_journal/cleanup.rb +5 -53
  52. data/lib/bluepill/process_journal/config.rb +73 -0
  53. data/lib/bluepill/process_journal/entries.rb +128 -0
  54. data/lib/bluepill/process_journal/journal.rb +69 -0
  55. data/lib/bluepill/process_journal/kind.rb +60 -0
  56. data/lib/bluepill/process_journal/lock.rb +9 -4
  57. data/lib/bluepill/process_journal.rb +13 -324
  58. data/lib/bluepill/process_statistics.rb +3 -7
  59. data/lib/bluepill/socket.rb +19 -17
  60. data/lib/bluepill/system/command_options.rb +136 -0
  61. data/lib/bluepill/system/command_result.rb +73 -0
  62. data/lib/bluepill/system/command_setup.rb +3 -4
  63. data/lib/bluepill/system/command_spawn.rb +244 -0
  64. data/lib/bluepill/system/commands.rb +27 -40
  65. data/lib/bluepill/system/daemon.rb +97 -15
  66. data/lib/bluepill/system/files.rb +35 -0
  67. data/lib/bluepill/system/ps.rb +20 -17
  68. data/lib/bluepill/system/ps_table.rb +7 -9
  69. data/lib/bluepill/system/usage.rb +175 -0
  70. data/lib/bluepill/system.rb +7 -192
  71. data/lib/bluepill/trigger.rb +18 -69
  72. data/lib/bluepill/triggers/flapping.rb +12 -8
  73. data/lib/bluepill/units.rb +7 -21
  74. data/lib/bluepill/version.rb +16 -26
  75. data/lib/bluepill.rb +1 -1
  76. data/sig/bluepill/application.rbs +11 -12
  77. data/sig/bluepill/attributes.rbs +48 -0
  78. data/sig/bluepill/checks.rbs +40 -40
  79. data/sig/bluepill/dsl.rbs +100 -59
  80. data/sig/bluepill/errors.rbs +48 -0
  81. data/sig/bluepill/logger.rbs +15 -31
  82. data/sig/bluepill/process.rbs +39 -305
  83. data/sig/bluepill/process_commands.rbs +235 -0
  84. data/sig/bluepill/stop_signals.rbs +21 -0
  85. data/sig/bluepill/system.rbs +191 -101
  86. data/sig/bluepill/version.rbs +17 -0
  87. data/sig/bluepill.rbs +2 -17
  88. data/sig/manifest.yaml +1 -0
  89. metadata +22 -8
  90. data/lib/bluepill/deprecation/custom_checks.rb +0 -193
  91. data/lib/bluepill/deprecation/dsl.rb +0 -141
  92. data/lib/bluepill/deprecation/options.rb +0 -140
  93. data/lib/bluepill/deprecation.rb +0 -92
  94. data/lib/bluepill/dsl/process_factory/children.rb +0 -99
  95. data/sig/bluepill/deprecation.rbs +0 -87
@@ -1,8 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "io/wait"
3
4
  require "shellwords"
4
5
  require "bluepill/daemonize"
6
+ require "bluepill/system/command_options"
7
+ require "bluepill/system/command_result"
5
8
  require "bluepill/system/command_setup"
9
+ require "bluepill/system/command_spawn"
6
10
  require "bluepill/system/daemon"
7
11
 
8
12
  module Bluepill
@@ -15,25 +19,27 @@ module Bluepill
15
19
  # @api private
16
20
  module Commands
17
21
  include CommandSetup
22
+ include CommandSpawn
18
23
 
19
24
  # Run a command until it finishes, and return what it printed
20
25
  #
21
- # With a :timeout, the command runs in a process group of its own, and
26
+ # With a timeout, the command runs in a process group of its own, and
22
27
  # if it hasn't finished in time, that whole group is killed, so a hung
23
- # command and anything it started don't keep running.
28
+ # command and anything it started don't keep running. A Ruby that
29
+ # can't fork spawns the command instead.
24
30
  #
25
31
  # @param [String] cmd the command, split into words without a shell
26
- # @param [Hash{Symbol => Object}] options :uid, :gid,
27
- # :supplementary_groups, :working_dir, :environment and :timeout (in
28
- # seconds)
32
+ # @param [CommandOptions] options its uid, gid, supplementary_groups,
33
+ # working_dir, environment and timeout
29
34
  #
30
- # @return [Hash{Symbol => Object}] its :stdout and :stderr Strings, and
31
- # its :exit_code (nil if a signal ended it)
35
+ # @return [CommandResult] what it printed, and its exit code
32
36
  #
33
- # @raise [Timeout::Error] if it ran longer than the :timeout
37
+ # @raise [Timeout::Error] if it ran longer than the timeout
34
38
  #
35
39
  # @api private
36
- def execute_blocking(cmd, options = {})
40
+ def execute_blocking(cmd, options = CommandOptions.new)
41
+ return spawn_blocking(cmd, options) unless Daemonize.can_fork?
42
+
37
43
  rd, wr = IO.pipe
38
44
 
39
45
  child = Daemonize.safefork
@@ -44,18 +50,21 @@ module Bluepill
44
50
  waiter = ::Process.detach(child)
45
51
 
46
52
  wr.close
47
- cmd_status = read_blocking_status(cmd, options[:timeout], child, rd)
53
+ cmd_status = read_blocking_status(cmd, options.timeout, child, rd)
48
54
  waiter.join
49
55
 
50
- cmd_status.empty? ? {exit_code: 0, stdout: "", stderr: ""} : Marshal.load(cmd_status)
56
+ return CommandResult.new(exit_code: 0) if cmd_status.empty?
57
+
58
+ # The child sends a Hash, so loading it needs only core classes
59
+ CommandResult.from_h(Marshal.load(cmd_status))
51
60
  end
52
61
 
53
62
  # Run the command in the child, which execute_blocking forked
54
63
  #
55
- # With a :timeout, the child gets a process group of its own first.
64
+ # With a timeout, the child gets a process group of its own first.
56
65
  #
57
66
  # @param [String] cmd the command
58
- # @param [Hash{Symbol => Object}] options as for execute_blocking
67
+ # @param [CommandOptions] options as for execute_blocking
59
68
  # @param [IO] reader the end of the pipe that only the parent uses
60
69
  # @param [IO] result_pipe where to write the result, marshaled
61
70
  #
@@ -65,7 +74,7 @@ module Bluepill
65
74
  def start_blocking_child(cmd, options, reader, result_pipe)
66
75
  reader.close
67
76
  # The command and what it starts can all be killed at once on a timeout
68
- ::Process.setpgid(0, 0) if options[:timeout]
77
+ ::Process.setpgid(0, 0) if options.timeout
69
78
  run_blocking_child(cmd, options, result_pipe)
70
79
  end
71
80
 
@@ -84,42 +93,20 @@ module Bluepill
84
93
  #
85
94
  # @api private
86
95
  def read_blocking_status(cmd, timeout, child, reader)
87
- # The signatures for IO.select leave out its timeout
88
- ready = timeout.nil? || IO.select([reader], nil, nil, timeout.to_f) # steep:ignore UnresolvedOverloading
96
+ ready = timeout.nil? || reader.wait_readable(timeout.to_f)
89
97
  kill_group_after(child, timeout, cmd) unless ready
90
98
  reader.read
91
99
  ensure
92
100
  reader.close
93
101
  end
94
102
 
95
- # Kill a command's process group, once it has run past its timeout
96
- #
97
- # @param [Integer] child the pid of the group's leader, which runs the
98
- # command
99
- # @param [Numeric, ActiveSupport::Duration] timeout the seconds it was given
100
- # @param [String] cmd the command, for the error
101
- #
102
- # @return [void] it never returns
103
- #
104
- # @raise [Timeout::Error] always
105
- #
106
- # @api private
107
- def kill_group_after(child, timeout, cmd)
108
- begin
109
- ::Process.kill("KILL", -child)
110
- rescue Errno::ESRCH
111
- nil # it finished just now
112
- end
113
- raise Timeout::Error, "#{cmd} took longer than #{timeout} seconds"
114
- end
115
-
116
103
  # Run a command in a grandchild, report its result, and exit
117
104
  #
118
105
  # Sends the grandchild's output and exit code to the parent over
119
106
  # result_pipe.
120
107
  #
121
108
  # @param [String] cmd the command
122
- # @param [Hash{Symbol => Object}] options as for execute_blocking
109
+ # @param [CommandOptions] options as for execute_blocking
123
110
  # @param [IO] result_pipe where to write the result, marshaled
124
111
  #
125
112
  # @return [void] it never returns, since it exits the child
@@ -191,7 +178,7 @@ module Bluepill
191
178
  # Replace the grandchild with the command, its output going to the pipes
192
179
  #
193
180
  # @param [String] cmd the command
194
- # @param [Hash{Symbol => Object}] options as for execute_blocking
181
+ # @param [CommandOptions] options as for execute_blocking
195
182
  # @param [Hash{Symbol => Object}] pipes the :out and :err pipes, each a
196
183
  # reader and a writer, and the :result pipe
197
184
  #
@@ -200,7 +187,7 @@ module Bluepill
200
187
  #
201
188
  # @api private
202
189
  def exec_blocking_grandchild(cmd, options, pipes)
203
- drop_privileges(options[:uid], options[:gid], options[:supplementary_groups])
190
+ drop_privileges(options.uid, options.gid, options.supplementary_groups)
204
191
  setup_command_environment(options)
205
192
 
206
193
  # close unused fds so ancestors wont hang. This line is the only reason we are not
@@ -2,10 +2,17 @@
2
2
 
3
3
  require "shellwords"
4
4
  require "bluepill/daemonize"
5
+ require "bluepill/system/command_options"
5
6
  require "bluepill/system/command_setup"
7
+ require "bluepill/system/command_spawn"
6
8
 
7
9
  module Bluepill
8
10
  module System
11
+ # The mode that a daemon's stdout and stderr files are opened in
12
+ #
13
+ # @api private
14
+ APPEND_MODE = "a"
15
+
9
16
  # Run commands in the background, as daemons
10
17
  #
11
18
  # System extends this module, so these are System's module functions.
@@ -13,22 +20,38 @@ module Bluepill
13
20
  # @api private
14
21
  module Daemon
15
22
  include CommandSetup
23
+ include CommandSpawn
16
24
 
17
25
  # Start a command as a daemon, and write its pid file
18
26
  #
19
27
  # It forks a child that drops privileges, sets up the environment and
20
28
  # standard streams, and daemonizes the command. The child tells the
21
- # parent the daemon's pid over a pipe.
29
+ # parent the daemon's pid over a pipe. A Ruby that can't fork spawns
30
+ # the command instead.
22
31
  #
23
32
  # @param [String] cmd the command, split into words without a shell
24
- # @param [Hash{Symbol => Object}] options :uid, :gid,
25
- # :supplementary_groups, :working_dir, :environment, :pid_file,
26
- # :logger, :stdin, :stdout and :stderr
33
+ # @param [CommandOptions] options its uid, gid, supplementary_groups,
34
+ # working_dir, environment, stdin, stdout and stderr
35
+ # @param [String] pid_file where to write the daemon's pid
36
+ # @param [Logger] logger where to log why the pid file can't be written
27
37
  #
28
38
  # @return [Integer, nil] the daemon's pid, or nil if it didn't start
29
39
  #
30
40
  # @api private
31
- def daemonize(cmd, options = {})
41
+ def daemonize(cmd, options = CommandOptions.new, pid_file:, logger:)
42
+ return fork_daemon(cmd, options, pid_file:, logger:) if Daemonize.can_fork?
43
+
44
+ spawn_daemon(cmd, options, pid_file:, logger:)
45
+ end
46
+
47
+ # Start a command as a daemon by forking, and write its pid file
48
+ #
49
+ # @param (see #daemonize)
50
+ #
51
+ # @return [Integer, nil] the daemon's pid, or nil if it didn't start
52
+ #
53
+ # @api private
54
+ def fork_daemon(cmd, options, pid_file:, logger:)
32
55
  rd, wr = IO.pipe
33
56
 
34
57
  child = Daemonize.safefork
@@ -41,11 +64,72 @@ module Bluepill
41
64
  # child
42
65
  rd.close
43
66
 
44
- drop_privileges(options[:uid], options[:gid], options[:supplementary_groups])
45
- start_daemon(cmd, options, wr)
67
+ drop_privileges(options.uid, options.gid, options.supplementary_groups)
68
+ start_daemon(cmd, options, wr, pid_file:, logger:)
46
69
  end
47
70
  end
48
71
 
72
+ # Start a command as a daemon without forking, and write its pid file
73
+ #
74
+ # The command runs in a process group of its own, as a forked daemon's
75
+ # new session does, so killing what's left in it never kills bluepill.
76
+ # It stays bluepill's child, and pid_alive? collects its exit status.
77
+ #
78
+ # @param [String] cmd the command, split into words without a shell
79
+ # @param [CommandOptions] options its working_dir, environment, stdin,
80
+ # stdout and stderr
81
+ # @param [String] pid_file where to write the daemon's pid
82
+ # @param [Logger] logger where to log why it didn't start
83
+ #
84
+ # @return [Integer, nil] the daemon's pid, or nil if it didn't start
85
+ #
86
+ # @api private
87
+ def spawn_daemon(cmd, options, pid_file:, logger:)
88
+ return unless can_write_pid_file(pid_file, logger)
89
+
90
+ pid = spawn_command(cmd, options, chdir: "/", pgroup: true, **daemon_streams(options))
91
+ File.write(pid_file, pid.to_s)
92
+ pid
93
+ rescue SystemCallError => e
94
+ logger.warning(format("%s - %s", e.class, e))
95
+ nil
96
+ end
97
+
98
+ # Return where a spawned daemon's standard streams go
99
+ #
100
+ # They're /dev/null unless the options name files. Output and error
101
+ # share one file when they name the same one, and are appended to.
102
+ #
103
+ # @param [CommandOptions] options its stdin, stdout and stderr
104
+ #
105
+ # @return [Hash{Symbol => Object}] Process.spawn's in, out and err
106
+ #
107
+ # @api private
108
+ def daemon_streams(options)
109
+ out = options.stdout
110
+ {
111
+ in: options.stdin || File::NULL,
112
+ out: out ? [out, APPEND_MODE] : File::NULL,
113
+ err: daemon_stderr(out, options.stderr)
114
+ }
115
+ end
116
+
117
+ # Return where a spawned daemon's standard error goes
118
+ #
119
+ # @param [String, nil] out the file for standard output
120
+ # @param [String, nil] err the file for standard error
121
+ #
122
+ # @return [Object] Process.spawn's err: standard output when they're
123
+ # the same file, the file, or /dev/null
124
+ #
125
+ # @api private
126
+ def daemon_stderr(out, err)
127
+ return File::NULL unless err
128
+ return [:child, :out] if err.eql?(out)
129
+
130
+ [err, APPEND_MODE]
131
+ end
132
+
49
133
  # Read the daemon's pid from the child that started it, in the parent
50
134
  #
51
135
  # @param [IO] reader the end of the pipe that the child writes the pid to
@@ -69,17 +153,15 @@ module Bluepill
69
153
  # It runs in the child, once it has dropped privileges.
70
154
  #
71
155
  # @param [String] cmd the command
72
- # @param [Hash{Symbol => Object}] options as for daemonize
156
+ # @param [CommandOptions] options as for daemonize
73
157
  # @param [IO] pid_pipe where to write the daemon's pid for the parent
158
+ # @param [String] pid_file where to write the daemon's pid
159
+ # @param [Logger] logger where to log why the pid file can't be written
74
160
  #
75
161
  # @return [void] it never returns, since it exits the child
76
162
  #
77
163
  # @api private
78
- def start_daemon(cmd, options, pid_pipe)
79
- # Processes that bluepill daemonizes always have a pid file and a logger
80
- pid_file = options[:pid_file] #: String
81
- logger = options[:logger] #: Logger
82
-
164
+ def start_daemon(cmd, options, pid_pipe, pid_file:, logger:)
83
165
  # if we cannot write the pid file as the provided user, err out
84
166
  exit unless can_write_pid_file(pid_file, logger)
85
167
 
@@ -97,7 +179,7 @@ module Bluepill
97
179
  # Return what the daemon runs: the command, in its environment
98
180
  #
99
181
  # @param [String] cmd the command
100
- # @param [Hash{Symbol => Object}] options as for daemonize
182
+ # @param [CommandOptions] options as for daemonize
101
183
  #
102
184
  # @return [Proc] a block that execs the command
103
185
  #
@@ -105,7 +187,7 @@ module Bluepill
105
187
  def daemon_command(cmd, options)
106
188
  lambda do
107
189
  setup_command_environment(options)
108
- redirect_io(options[:stdin], options[:stdout], options[:stderr])
190
+ redirect_io(options.stdin, options.stdout, options.stderr)
109
191
 
110
192
  Kernel.exec(*Shellwords.shellwords(cmd))
111
193
  exit
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bluepill
4
+ module System
5
+ # Delete the files that bluepill leaves behind
6
+ #
7
+ # System extends this module, so these are System's module functions.
8
+ #
9
+ # @api private
10
+ module Files
11
+ # Delete a file if it exists
12
+ #
13
+ # It tries three times when permission is denied, and then prints a
14
+ # warning instead of raising.
15
+ #
16
+ # @param [String, nil] filename the file's path
17
+ #
18
+ # @return [void]
19
+ #
20
+ # @api private
21
+ def delete_if_exists(filename)
22
+ tries = 0
23
+
24
+ begin
25
+ File.unlink(filename) if filename && File.exist?(filename)
26
+ rescue IOError, Errno::ENOENT
27
+ # Already gone, or another process removed it in between
28
+ rescue Errno::EACCES
29
+ retry if (tries += 1) < 3
30
+ $stderr.puts("Warning: permission denied trying to delete #{filename}")
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -4,6 +4,16 @@ require "bluepill/system/ps_table"
4
4
 
5
5
  module Bluepill
6
6
  module System
7
+ # Raised when ps could not be run, so there is no data for this tick
8
+ #
9
+ # @api private
10
+ class PsError < StandardError; end
11
+
12
+ # Watches run in their own threads, so only let one of them run ps per tick
13
+ #
14
+ # @api private
15
+ PS_MUTEX = Mutex.new
16
+
7
17
  # Run ps once a tick, and read its table of processes
8
18
  #
9
19
  # System extends this module, so these are System's module functions.
@@ -12,43 +22,36 @@ module Bluepill
12
22
  #
13
23
  # @api private
14
24
  module Ps
15
- # Return what this tick has memoized
16
- #
17
- # @return [Hash{Symbol => PsTable, String}] the ps table, or ps's
18
- # error, by name
19
- #
20
- # @api private
21
- def store
22
- @store ||= {}
23
- end
24
-
25
- # Forget what the last tick memoized, so ps runs again
25
+ # Forget the last tick's ps table, so ps runs again
26
26
  #
27
27
  # @return [void]
28
28
  #
29
29
  # @api private
30
30
  def reset_data
31
31
  @children_table = nil
32
- store.clear
32
+ @ps_table = nil
33
33
  end
34
34
 
35
35
  # Return this tick's ps table, running ps the first time it's asked for
36
36
  #
37
+ # When ps could not be run, the error is kept instead, and raised
38
+ # again until the next tick.
39
+ #
37
40
  # @return [PsTable] each process's ps fields
38
41
  #
39
42
  # @raise [PsError] if ps could not be run this tick
40
43
  #
41
44
  # @api private
42
45
  def ps_axu
43
- ps = PS_MUTEX.synchronize { store[:ps_axu] ||= read_ps_table }
44
- raise PsError, ps if ps.instance_of?(String)
46
+ ps = PS_MUTEX.synchronize { @ps_table ||= read_ps_table }
47
+ raise ps if ps.instance_of?(PsError)
45
48
 
46
49
  ps
47
50
  end
48
51
 
49
52
  # Run ps, and parse what it prints into a table
50
53
  #
51
- # @return [PsTable, String] each process's ps fields, or why ps could
54
+ # @return [PsTable, PsError] each process's ps fields, or why ps could
52
55
  # not be run
53
56
  #
54
57
  # @api private
@@ -58,8 +61,8 @@ module Bluepill
58
61
  PsTable.parse(`ps -Ao pid,ppid,pcpu,rss,etime,args`)
59
62
  rescue SystemCallError => e
60
63
  # Forking ps can fail, for example with ENOMEM or EAGAIN under memory pressure.
61
- # Cache the message so ps is not run again until the next tick.
62
- "Could not run ps: #{e.class}: #{e}"
64
+ # Keep the error so ps is not run again until the next tick.
65
+ PsError.new("Could not run ps: #{e.class}: #{e}")
63
66
  end
64
67
 
65
68
  # Return the pids of a process's descendants, from this tick's ps table
@@ -2,6 +2,10 @@
2
2
 
3
3
  module Bluepill
4
4
  module System
5
+ # No pids, which get_children returns for a process with no children
6
+ no_pids = [] #: Array[Integer]
7
+ NO_PIDS = no_pids.freeze
8
+
5
9
  # A tick's table of processes, as ps listed them
6
10
  #
7
11
  # Each row is a process's ps fields, Strings in the order of the column
@@ -76,9 +80,7 @@ module Bluepill
76
80
  # @return [undefined]
77
81
  #
78
82
  # @api private
79
- def initialize(rows)
80
- @rows = rows
81
- end
83
+ def initialize(rows) = @rows = rows
82
84
 
83
85
  # Return a process's ps fields
84
86
  #
@@ -87,9 +89,7 @@ module Bluepill
87
89
  # @return [Array<String>, nil] its fields, or nil if ps doesn't list it
88
90
  #
89
91
  # @api private
90
- def row(pid)
91
- @rows[pid]
92
- end
92
+ def row(pid) = @rows[pid]
93
93
 
94
94
  # Return the pids of a process's children
95
95
  #
@@ -99,9 +99,7 @@ module Bluepill
99
99
  # NO_PIDS if it has none
100
100
  #
101
101
  # @api private
102
- def children(pid)
103
- children_by_parent.fetch(pid, NO_PIDS)
104
- end
102
+ def children(pid) = children_by_parent.fetch(pid, NO_PIDS)
105
103
 
106
104
  # Return the pids of a process's descendants
107
105
  #
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bluepill
4
+ module System
5
+ # Ask the system about a process: whether it's alive, when it started,
6
+ # and what this tick's ps table says it uses
7
+ #
8
+ # System extends this module, so these are System's module functions.
9
+ #
10
+ # @api private
11
+ module Usage
12
+ # Return whether a process is running
13
+ #
14
+ # @param [Integer] pid the process's pid
15
+ #
16
+ # @return [Boolean] true if the process exists, even if bluepill may
17
+ # not signal it
18
+ #
19
+ # @api private
20
+ def pid_alive?(pid)
21
+ reap(pid)
22
+ ::Process.kill(0, pid)
23
+ true
24
+ rescue Errno::EPERM # no permission, but it is definitely alive
25
+ true
26
+ rescue
27
+ false # no such process (ESRCH), or no pid
28
+ end
29
+
30
+ # Collect the exit status of a daemon that bluepill spawned, if it exited
31
+ #
32
+ # A spawned daemon stays bluepill's child, and one that exited is a
33
+ # zombie, which kill(0) still finds, until bluepill collects its exit
34
+ # status. A thread that waits for it instead would keep JRuby from
35
+ # exiting while the daemon runs. A Ruby that forks has no daemons to
36
+ # collect, since init adopts them.
37
+ #
38
+ # @param [Integer, nil] pid the daemon's pid
39
+ #
40
+ # @return [void]
41
+ #
42
+ # @api private
43
+ def reap(pid)
44
+ ::Process.wait(pid, ::Process::WNOHANG) if pid && !Daemonize.can_fork?
45
+ rescue Errno::ECHILD
46
+ # It isn't bluepill's child, or was collected already
47
+ end
48
+
49
+ # Return when a process started, in seconds since the epoch
50
+ #
51
+ # It's read from ps's elapsed time for the process, so it's accurate to
52
+ # about a second, and works wherever ps does.
53
+ #
54
+ # @param [Integer] pid the process's pid
55
+ #
56
+ # @return [Integer, nil] when it started, or nil if there's no such
57
+ # process
58
+ #
59
+ # @api private
60
+ def started_at(pid)
61
+ # ps says why on stderr when there's no such process
62
+ elapsed = IO.popen(["ps", "-o", "etime=", "-p", Integer(pid).to_s], err: File::NULL, &:read).rstrip
63
+ Integer(Time.now) - parse_elapsed_time(elapsed) unless elapsed.empty?
64
+ rescue SystemCallError
65
+ nil
66
+ end
67
+
68
+ # Return when the machine booted, in seconds since the epoch
69
+ #
70
+ # That's when its first process, pid 1, started. In a container, it's
71
+ # when the container started, which is when its pids start over.
72
+ #
73
+ # @return [Integer, nil] when it booted, or nil if ps can't tell
74
+ #
75
+ # @api private
76
+ def boot_time = started_at(1)
77
+
78
+ # Return a process's CPU usage, from this tick's ps table
79
+ #
80
+ # @param [Integer, nil] pid the process's pid
81
+ # @param [Boolean] include_children whether to add its descendants'
82
+ #
83
+ # @return [Float, nil] the percent of a CPU it uses, or nil if ps doesn't
84
+ # list it
85
+ #
86
+ # @raise [PsError] if ps could not be run this tick
87
+ #
88
+ # @api private
89
+ def cpu_usage(pid, include_children) = usage(pid, include_children, PsTable::PCPU)
90
+
91
+ # Return a process's resident memory, from this tick's ps table
92
+ #
93
+ # @param [Integer, nil] pid the process's pid
94
+ # @param [Boolean] include_children whether to add its descendants'
95
+ #
96
+ # @return [Float, nil] its resident memory in kilobytes, or nil if ps
97
+ # doesn't list it
98
+ #
99
+ # @raise [PsError] if ps could not be run this tick
100
+ #
101
+ # @api private
102
+ def memory_usage(pid, include_children) = usage(pid, include_children, PsTable::RSS)
103
+
104
+ # Return a column of a process's row, from this tick's ps table, as a Float
105
+ #
106
+ # @param [Integer, nil] pid the process's pid
107
+ # @param [Boolean] include_children whether to add its descendants'
108
+ # @param [Integer] column the column, PsTable::PCPU or PsTable::RSS
109
+ #
110
+ # @return [Float, nil] the process's value, and its descendants' if
111
+ # asked for, or nil if ps doesn't list it
112
+ #
113
+ # @raise [PsError] if ps could not be run this tick
114
+ #
115
+ # @api private
116
+ def usage(pid, include_children, column)
117
+ ps = ps_axu
118
+ row = ps.row(pid)
119
+ return unless row
120
+
121
+ used = row.fetch(column).to_f
122
+ include_children ? ps.sum(get_children(pid), column, used) : used
123
+ end
124
+
125
+ # Return how long a process has been running, from this tick's ps table
126
+ #
127
+ # @param [Integer, nil] pid the process's pid
128
+ #
129
+ # @return [Integer, nil] its running time in seconds, or nil if ps
130
+ # doesn't list it
131
+ #
132
+ # @raise [PsError] if ps could not be run this tick
133
+ #
134
+ # @api private
135
+ def running_time(pid)
136
+ row = ps_axu.row(pid)
137
+ parse_elapsed_time(row.fetch(PsTable::ETIME)) if row
138
+ end
139
+
140
+ # Return a process's command line, from this tick's ps table
141
+ #
142
+ # @param [Integer, nil] pid the process's pid
143
+ #
144
+ # @return [String, nil] its command and arguments, or nil if ps doesn't
145
+ # list it
146
+ #
147
+ # @raise [PsError] if ps could not be run this tick
148
+ #
149
+ # @api private
150
+ def command(pid)
151
+ row = ps_axu.row(pid)
152
+ row&.fetch(PsTable::COMMAND)
153
+ end
154
+
155
+ # Convert ps's elapsed time to seconds
156
+ #
157
+ # @param [String, nil] str an elapsed time, [[dd-]hh:]mm:ss
158
+ #
159
+ # @return [Integer] the seconds, or 0 if str isn't an elapsed time
160
+ #
161
+ # @api private
162
+ def parse_elapsed_time(str)
163
+ # [[dd-]hh:]mm:ss
164
+ match = /(?:(?:(\d+)-)?(\d\d):)?(\d\d):(\d\d)/.match(str)
165
+ if match
166
+ hours = (match[1].to_i * 24) + match[2].to_i
167
+ mins = (hours * 60) + match[3].to_i
168
+ (mins * 60) + match[4].to_i
169
+ else
170
+ 0
171
+ end
172
+ end
173
+ end
174
+ end
175
+ end