Module: Jkr::PlanUtils

Included in:
Jkr::Plan::PlanLoader
Defined in:
lib/jkr/utils.rb

Instance Method Summary collapse

Instance Method Details

#cmd(*args) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
257
258
259
# File 'lib/jkr/utils.rb', line 100

def cmd(*args)
  @procdb_mutex ||= Mutex.new
  options = (if args.last.is_a? Hash
               args.pop
             else
               {}
             end)
  options = {
    :wait   => true,
    :timeout => 0,
    :raise_failure => true,
    :stdin  => nil,
    :stdout => [$stdout],
    :stderr => [$stderr]
  }.merge(options)

  if options[:timeout] > 0 && ! options[:wait]
    raise ArgumentError.new("cmd: 'wait' must be true if 'timeout' specified.")
  end

  start_time = Time.now
  pid = nil
  status = nil
  args.flatten!
  args.map!(&:to_s)
  command = args.join(" ")
  barrier = Barrier.new(2)
  process_exited = false

  t = Thread.new {
    pipers = []
    status = POpen4::popen4(command){|p_stdout, p_stderr, p_stdin, p_id|
      pid = p_id
      barrier.wait
      stdouts = if options[:stdout].is_a? Array
                  options[:stdout]
                else
                  [options[:stdout]]
                end
      stderrs = if options[:stderr].is_a? Array
                  options[:stderr]
                else
                  [options[:stderr]]
                end
      pipers << Thread.new{
        target = p_stdout
        timeout_count = 0
        while true
          begin
            if (ready = IO.select([target], [], [], 1))
              ready.first.each do |fd|
                buf = fd.read_nonblock(4096)
                stdouts.each{|out| out.print buf}
              end
              Thread.exit if target.eof?
            else
              if process_exited
                timeout_count += 1
                if timeout_count > 5
                  target.close_read
                  Thread.exit
                end
              end
            end
          rescue IOError => err
            if target.closed?
              Thread.exit
            end
          end
        end
      }
      pipers << Thread.new{
        target = p_stderr
        timeout_count = 0
        while true
          begin
            if (ready = IO.select([target], [], [], 1))
              ready.first.each do |fd|
                buf = fd.read_nonblock(4096)
                stderrs.each{|out| out.print buf}
              end
              Thread.exit if target.eof?
            else
              if process_exited
                timeout_count += 1
                if timeout_count > 5
                  target.close_read
                  Thread.exit
                end
              end
            end
          rescue IOError => err
            if target.closed?
              Thread.exit
            end
          end
        end
      }
      if options[:stdin]
        pipers << Thread.new{
        target = options[:stdin]
        timeout_count = 0
        while true
          begin
            if (ready = IO.select([target], [], [], 1))
              ready.first.each do |fd|
                  buf = fd.read_nonblock(4096)
                  p_stdin.print buf
                end
            else
              if process_exited
                timeout_count += 1
                if timeout_count > 5
                  p_stdin.close_write
                  Thread.exit
                end
              end
            end
          rescue IOError => err
            if target.closed?
              Thread.exit
            end
          end
        end
      }
      end
    }
    pipers.each{|t| t.join}
    raise ArgumentError.new("Invalid command: #{command}") unless status
    procdb_update_status(pid, status)
  }
  barrier.wait
  procdb_spawn(pid, command, t)
  timekeeper = nil

  killed = false
  timekeeper = nil
  if options[:timeout] > 0
    timekeeper = Thread.new do
      sleep(options[:timeout])
      begin
        Process.kill(:INT, pid)
        killed = true
      rescue Errno::ESRCH # No such process
      end
    end
  end
  if options[:wait]
    timekeeper.join if timekeeper
    t.join
    if (! killed) && options[:raise_failure] && status.exitstatus != 0
      raise RuntimeError.new("'#{command}' failed.")
    end
  end
  while ! pid
    sleep 0.001 # do nothing
  end

  pid
end

#procdbObject

info about processes spawned by me



50
51
52
# File 'lib/jkr/utils.rb', line 50

def procdb
  @procdb ||= Hash.new
end

#procdb_get(pid) ⇒ Object



86
87
88
89
90
# File 'lib/jkr/utils.rb', line 86

def procdb_get(pid)
  @procdb_mutex.synchronize do
    self.procdb[pid]
  end
end

#procdb_get_command(pid) ⇒ Object



95
96
97
98
# File 'lib/jkr/utils.rb', line 95

def procdb_get_command(pid)
  proc = self.procdb_get(pid)
  proc && proc[:command]
end

#procdb_get_status(pid) ⇒ Object



91
92
93
94
# File 'lib/jkr/utils.rb', line 91

def procdb_get_status(pid)
  proc = self.procdb_get(pid)
  proc && proc[:status]
end

#procdb_resetpid(pid) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/jkr/utils.rb', line 72

def procdb_resetpid(pid)
  @procdb_mutex.synchronize do
    if self.procdb[pid]
      self.procdb.delete(pid)
    end
  end
end

#procdb_spawn(pid, command, owner_thread) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/jkr/utils.rb', line 53

def procdb_spawn(pid, command, owner_thread)
  @procdb_mutex.synchronize do
    self.procdb[pid] = {
      :pid => pid,
      :command => command,
      :thread => owner_thread,
      :status => nil
    }
  end
end

#procdb_update_status(pid, status) ⇒ Object



79
80
81
82
83
84
85
# File 'lib/jkr/utils.rb', line 79

def procdb_update_status(pid, status)
  @procdb_mutex.synchronize do
    if self.procdb[pid]
      self.procdb[pid][:status] = status
    end
  end
end

#procdb_waitpid(pid) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'lib/jkr/utils.rb', line 63

def procdb_waitpid(pid)
  t = nil
  @procdb_mutex.synchronize do
    if self.procdb[pid]
      t = self.procdb[pid][:thread]
    end
  end
  t.join if t
end

#use_script(name) ⇒ Object



343
344
345
346
347
348
349
350
351
# File 'lib/jkr/utils.rb', line 343

def use_script(name)
  name = name.to_s
  name = name + ".rb" unless name =~ /\.rb$/
  dir = @plan.jkr_env.jkr_script_dir
  path = File.join(dir, name)
  script = File.open(path, "r").read
  self.instance_eval(script, path, 1)
  true
end

#with_process(*args) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/jkr/utils.rb', line 300

def with_process(*args)
  options = (if args.last.is_a? Hash
               args.pop
             else
               {}
             end )
  options = {
    :kill_on_exit => false
  }.merge(options)
  options[:wait] = false

  args.push(options)
  pid = cmd(*args)

  err = nil
  begin
    yield
  rescue Exception => e
    err = e
  end

  if options[:kill_on_exit]
    Process.kill(:INT, pid)
  else
    if err
      begin
        Process.kill(:TERM, pid)
      rescue Exception
      end
    else
      procdb_waitpid(pid)
      status = procdb_get_status(pid)
      unless status && status.exitstatus == 0
        command = procdb_get_command(pid) || "Unknown command"
        raise RuntimeError.new("'#{command}' failed.")
      end
      procdb_resetpid(pid)
    end
  end

  raise err if err
end

#with_process2(*args) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/jkr/utils.rb', line 261

def with_process2(*args)
  options = (if args.last.is_a? Hash
               args.pop
             else
               {}
             end )
  options = {
    :kill_on_exit => false
  }.merge(options)
  
  command = args.flatten.map(&:to_s).join(" ")
  pid = Process.spawn(command)

  err = nil
  begin
    yield
  rescue Exception => e
    err = e
  end

  if options[:kill_on_exit]
    Process.kill(:INT, pid)
  else
    if err
      begin
        Process.kill(:TERM, pid)
      rescue Exception
      end
    else
      begin
        status = Process.waitpid(pid)
        p status
      rescue Errno::ESRCH
      end
    end
  end
  raise err if err
end