Sha256: 851b81db23d9ccce34f4715f886f02f716e9d1becda35df58b94f6d9da7bb1d8

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

if ENV["RBBT_NO_LOCKFILE_REFRESH"] == "true"
  Lockfile.refresh = false 
  Lockfile.max_age = 60 * 60 * 5
  Lockfile.max_age = 15
  Lockfile.suspend = 10
else
  Lockfile.dont_use_lock_id = true
  Lockfile.refresh = 5 
  Lockfile.max_age = 60
  Lockfile.suspend = 15
end


module Misc

  LOCK_MUTEX = Mutex.new
  def self.lock(file, unlock = true, options = {})
    return yield if file.nil?
    FileUtils.mkdir_p File.dirname(File.expand_path(file)) unless File.exists?  File.dirname(File.expand_path(file))

    res = nil

    lock_path = File.expand_path(file + '.lock')
    lockfile = Lockfile.new(lock_path, options)

    lockfile.lock 

    begin
      res = yield lockfile
    #rescue Lockfile::StolenLockError
    rescue KeepLocked
      unlock = false
      res = $!.payload
    rescue Exception
      lockfile.unlock #if lockfile.locked?
      raise $!
    ensure
      if unlock 
        begin
          lockfile.unlock #if lockfile.locked?
        rescue Exception
        end
      end
    end

    res
  end
  

  LOCK_REPO_SERIALIZER=Marshal
  def self.lock_in_repo(repo, key, *args)
    return yield file, *args if repo.nil? or key.nil?

    lock_key = "lock-" << key

    begin
      if repo[lock_key] and
        Misc.hostname == (info = LOCK_REPO_SERIALIZER.load(repo[lock_key]))["host"] and 
        info["pid"] and not Misc.pid_exists?(info["pid"])

        Log.info("Removing lockfile: #{lock_key}. This pid #{Process.pid}. Content: #{info.inspect}")
        repo.out lock_key 
      end
    rescue
      Log.warn("Error checking lockfile #{lock_key}: #{$!.message}. Removing. Content: #{begin repo[lock_key] rescue "Could not open file" end}")
      repo.out lock_key if repo.include? lock_key
    end

    while repo[lock_key]
      sleep 1
    end
    
    repo[lock_key] = LOCK_REPO_SERIALIZER.dump({:hostname => Misc.hostname, :pid => Process.pid})

    res = yield lock_key, *args

    repo.delete lock_key

    res
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rbbt-util-5.13.31 lib/rbbt/util/misc/lock.rb