Class: Cuboid::Processes::Manager

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/cuboid/processes/manager.rb

Overview

Helper for managing processes.

Author:

Constant Summary collapse

RUNNER =
"#{File.dirname( __FILE__ )}/executables/base.rb"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeManager

Returns a new instance of Manager.



18
19
20
# File 'lib/cuboid/processes/manager.rb', line 18

def initialize
    reset
end

Instance Attribute Details

#pidsArray<Integer> (readonly)

Returns PIDs of all running processes.

Returns:

  • (Array<Integer>)

    PIDs of all running processes.



16
17
18
# File 'lib/cuboid/processes/manager.rb', line 16

def pids
  @pids
end

Class Method Details

.method_missing(sym, *args, &block) ⇒ Object



258
259
260
261
262
263
264
# File 'lib/cuboid/processes/manager.rb', line 258

def self.method_missing( sym, *args, &block )
    if instance.respond_to?( sym )
        instance.send( sym, *args, &block )
    else
        super( sym, *args, &block )
    end
end

.respond_to?(m) ⇒ Boolean

Returns:

  • (Boolean)


266
267
268
# File 'lib/cuboid/processes/manager.rb', line 266

def self.respond_to?( m )
    super( m ) || instance.respond_to?( m )
end

Instance Method Details

#<<(pid) ⇒ Integer

Returns ‘pid`.

Parameters:

  • pid (Integer)

    Adds a PID to the #pids and detaches the process.

Returns:

  • (Integer)

    ‘pid`



31
32
33
34
35
# File 'lib/cuboid/processes/manager.rb', line 31

def <<( pid )
    @pids << pid
    Process.detach pid
    pid
end

#alive?(pid) ⇒ Boolean

Returns ‘true` if the process is alive, `false` otherwise.

Parameters:

  • pid (Integer)

Returns:

  • (Boolean)

    ‘true` if the process is alive, `false` otherwise.



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/cuboid/processes/manager.rb', line 127

def alive?( pid )
    # Windows is not big on POSIX so try it its own way if possible.
    if Cuboid.windows?
        begin
            alive = false
            processes = wmi.ExecQuery( "select ProcessId from win32_process where ProcessID='#{pid}'" )
            processes.each do |proc|
                proc.ole_free
                alive = true
            end
            processes.ole_free

            return alive
        rescue WIN32OLERuntimeError
        end
    end

    !!(Process.kill( 0, pid ) rescue false)
end

#discard_outputObject



175
176
177
# File 'lib/cuboid/processes/manager.rb', line 175

def discard_output
    @discard_output = true
end

#discard_output?Boolean

Returns:

  • (Boolean)


179
180
181
# File 'lib/cuboid/processes/manager.rb', line 179

def discard_output?
    @discard_output
end

#find(bin) ⇒ Object



62
63
64
65
# File 'lib/cuboid/processes/manager.rb', line 62

def find( bin )
    find_in_path( bin ) || find_in_applications( bin ) ||
        find_in_program_files( bin )
end

#find_in_applications(bin) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/cuboid/processes/manager.rb', line 83

def find_in_applications( bin )
    return if !Cuboid.mac?

    @find_in_applications ||= {}
    return @find_in_applications[bin] if @find_in_applications.include?( bin )

    paths = ENV['PATH'].split( File::PATH_SEPARATOR ) | [
      '/Applications/'
    ]

    paths.each do |root|
        glob = File.join( "#{root}/*/Contents/MacOS", '**', bin )

        exe = Dir.glob( glob ).find { |f| File.executable?( f ) }
        return @find_in_applications[bin] = exe if exe
    end

    @find_in_applications[bin] = nil
end

#find_in_path(bin) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/cuboid/processes/manager.rb', line 67

def find_in_path( bin )
    @find_in_path ||= {}
    return @find_in_path[bin] if @find_in_path.include?( bin )

    if Cuboid.windows?
        bin = "#{bin}.exe"
    end

    ENV['PATH'].split( File::PATH_SEPARATOR ).each do |path|
        f = File.join( path, bin )
        return @find_in_path[bin] = f if File.exist?( f )
    end

    @find_in_path[bin] = nil
end

#find_in_program_files(bin) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/cuboid/processes/manager.rb', line 103

def find_in_program_files( bin )
    return if !Cuboid.windows?

    @find_in_program_files ||= {}
    return @find_in_program_files[bin] if @find_in_program_files.include?( bin )

    [
        ENV['PROGRAMFILES']      || '\\Program Files',
        ENV['ProgramFiles(x86)'] || '\\Program Files (x86)',
        ENV['ProgramW6432']      || '\\Program Files'
    ].each do |root|
        glob = File.join( root, '**', "#{bin}.exe" )
        glob.tr!( '\\', '/' )

        exe = Dir.glob( glob ).find { |f| File.executable?( f ) }
        return @find_in_program_files[bin] = exe if exe
    end

    @find_in_program_files[bin] = nil
end

#kill(pid) ⇒ Object

Parameters:

  • pid (Integer)

    PID of the process to kill.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/cuboid/processes/manager.rb', line 39

def kill( pid )
    fail 'Cannot kill self.' if pid == Process.pid

    Timeout.timeout 10 do
        while sleep 0.1 do
            begin
                Process.kill( Cuboid.windows? ? 'KILL' : 'TERM', pid )

            # Either kill was successful or we don't have enough perms or
            # we hit a reused PID for someone else's process, either way,
            # consider the process gone.
            rescue Errno::ESRCH, Errno::EPERM,
                # Don't kill ourselves.
                SignalException

                @pids.delete pid
                return
            end
        end
    end
rescue Timeout::Error
end

#kill_many(pids) ⇒ Object

Parameters:

  • pids (Array<Integer>)

    PIDs of the process to #kill.



149
150
151
# File 'lib/cuboid/processes/manager.rb', line 149

def kill_many( pids )
    pids.each { |pid| kill pid }
end

#kill_reactorObject

Stops the Reactor.



160
161
162
163
164
# File 'lib/cuboid/processes/manager.rb', line 160

def kill_reactor
    Raktr.stop
rescue
    nil
end

#killallObject

Kills all processes.



154
155
156
157
# File 'lib/cuboid/processes/manager.rb', line 154

def killall
    kill_many @pids.dup
    @pids.clear
end

#preserve_outputObject

Overrides the default setting of discarding process outputs.



167
168
169
# File 'lib/cuboid/processes/manager.rb', line 167

def preserve_output
    @discard_output = false
end

#preserve_output?Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/cuboid/processes/manager.rb', line 171

def preserve_output?
    !discard_output?
end

#resetObject



22
23
24
25
# File 'lib/cuboid/processes/manager.rb', line 22

def reset
    @pids           = []
    @discard_output = true
end

#spawn(executable, options = {}) ⇒ Integer

Returns PID of the process.

Parameters:

  • executable (String)

    Name of the executable Ruby script found in OptionGroups::Paths#executables without the ‘.rb’ extension.

  • options (Hash) (defaults to: {})

    Options to pass to the script – can be retrieved from ‘$options`.

Returns:

  • (Integer)

    PID of the process.



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
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
# File 'lib/cuboid/processes/manager.rb', line 191

def spawn( executable, options = {} )
    fail ArgumentError, 'Fork not supported.' if options.delete(:fork)

    stdin      = options.delete(:stdin)
    stdout     = options.delete(:stdout)
    stderr     = options.delete(:stderr)
    new_pgroup = options.delete(:new_pgroup)
    daemonize  = options.delete(:daemonize)

    spawn_options = {}

    if new_pgroup
        if Cuboid.windows?
            spawn_options[:new_pgroup] = new_pgroup
        else
            spawn_options[:pgroup] = new_pgroup
        end
    end

    spawn_options[:in]  = stdin  if stdin
    spawn_options[:out] = stdout if stdout
    spawn_options[:err] = stderr if stderr

    options[:ppid]   = Process.pid
    options[:tmpdir] = Options.paths.tmpdir

    cuboid_options = Options.dup.update( options.delete(:options) || {} ).to_h
    encoded_cuboid_options = Base64.strict_encode64( Marshal.dump( cuboid_options ) )

    if executable.is_a? Symbol
        executable = "#{Options.paths.executables}/#{executable}.rb"
    elsif !File.exist?( executable )
        raise ArgumentError, "Executable does not exist: #{executable}"
    end

    encoded_options = Base64.strict_encode64( Marshal.dump( options ) )
    argv            = [executable, encoded_options]


    # It's very, **VERY** important that we use this argument format as
    # it bypasses the OS shell and we can thus count on a 1-to-1 process
    # creation and that the PID we get will be for the actual process.
    pid = Process.spawn(
        {
            'CUBOID_SPAWN_OPTIONS' => encoded_cuboid_options
        },
        RbConfig.ruby,
        RUNNER,
        *(argv + [spawn_options])
    )

    self << pid

    if !daemonize
        begin
            Process.waitpid( pid )
        rescue Errno::ECHILD
            @pids.delete pid
            return
        rescue Interrupt
            exit 0
        end
    end

    pid
end