summaryrefslogtreecommitdiff
path: root/lib/byteback/util.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/byteback/util.rb')
-rwxr-xr-xlib/byteback/util.rb68
1 files changed, 68 insertions, 0 deletions
diff --git a/lib/byteback/util.rb b/lib/byteback/util.rb
new file mode 100755
index 0000000..f9f6c62
--- /dev/null
+++ b/lib/byteback/util.rb
@@ -0,0 +1,68 @@
+require 'tempfile'
+
+module Byteback
+ module Util
+ @@lockfile = "/var/run/byteback/byteback.lock"
+
+ def remove_lockfile!
+ begin
+ File.unlink(@@lockfile)
+ rescue Errno::ENOENT
+ end
+ end
+
+ def claim_lockfile!
+ # Check the lockfile first
+ if File.directory?(File.dirname(@@lockfile))
+ if File.exists? @@lockfile
+ # check the lockfile is sane
+ exist_pid = File.read(@@lockfile).to_i
+ if exist_pid > 1 and exist_pid < (File.read("/proc/sys/kernel/pid_max").to_i)
+ begin
+ Process.getpgid(exist_pid)
+ # if no exception, process is running, abort
+ fatal("Process is running (#{exist_pid} from #{@@lockfile})")
+ rescue Errno::ESRCH
+ # no process running with that pid, pidfile is stale
+ remove_lockfile!
+ end
+ else
+ # lockfile isn't sane, remove it and continue
+ remove_lockfile!
+ end
+ end
+ else
+ Dir.mkdir(File.dirname(@@lockfile))
+ # lockfile didn't exist so just carry on
+ end
+
+ # Own the pidfile ourselves
+ File.open(@@lockfile, "w") do |lockfile|
+ lockfile.puts Process::pid
+ end
+ end
+
+ def lock_out_other_processes(name)
+ @@lockfile = "/var/run/byteback/#{name}.lock"
+ claim_lockfile!
+ at_exit { remove_lockfile! }
+ end
+
+ def log_system(*args)
+ debug("system: " + args.map { |a| / /.match(a) ? "\"#{a}\"" : a }.join(" "))
+ rd, wr = IO.pipe
+ pid = fork
+ if pid.nil? # child
+ rd.close
+ STDOUT.reopen(wr)
+ STDERR.reopen(wr)
+ # any cleanup actually necessary here?
+ exec(*args)
+ end
+ wr.close
+ rd.each_line { |line| debug(line.chomp) }
+ pid2, status = Process.waitpid2(pid, 0)
+ status.exitstatus
+ end
+ end
+end