Class: KnifeCloudformation::Cache::LocalLock

Inherits:
Object
  • Object
show all
Defined in:
lib/knife-cloudformation/cache.rb

Overview

Simple lock for memory cache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, args = {}) ⇒ LocalLock

Create new instance

Parameters:

  • name (Symbol)

    name of lock

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

Options Hash (args):

  • :timeout (Numeric)


296
297
298
299
300
# File 'lib/knife-cloudformation/cache.rb', line 296

def initialize(name, args={})
  @_key = name
  @_timeout = args.fetch(:timeout, -1).to_f
  @_lock = Mutex.new
end

Instance Attribute Details

#_keySymbol (readonly)

Returns key name.

Returns:

  • (Symbol)

    key name



285
286
287
# File 'lib/knife-cloudformation/cache.rb', line 285

def _key
  @_key
end

#_lockMutex (readonly)

Returns underlying lock.

Returns:

  • (Mutex)

    underlying lock



289
290
291
# File 'lib/knife-cloudformation/cache.rb', line 289

def _lock
  @_lock
end

#_timeoutNumeric (readonly)

Returns timeout.

Returns:

  • (Numeric)

    timeout



287
288
289
# File 'lib/knife-cloudformation/cache.rb', line 287

def _timeout
  @_timeout
end

Instance Method Details

#clearObject

Note:

this is a noop

Clear the lock



326
327
328
# File 'lib/knife-cloudformation/cache.rb', line 326

def clear
  # noop
end

#lock { ... } ⇒ Object

Aquire lock and yield

Yields:

  • block to execute within lock

Returns:

  • (Object)

    result of yield



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/knife-cloudformation/cache.rb', line 306

def lock
  locked = false
  attempt_start = Time.now.to_f
  while(!locked && (_timeout < 0 || Time.now.to_f - attempt_start < _timeout))
    locked = _lock.try_lock
  end
  if(locked)
    begin
      yield
    ensure
      _lock.unlock if _lock.locked?
    end
  else
    raise Redis::Lock::LockTimeout.new "Timeout on lock #{_key} exceeded #{_timeout} sec"
  end
end