Class: SocketLock

Inherits:
Object
  • Object
show all
Defined in:
lib/socketlock.rb

Constant Summary collapse

SOCKETLOCK_ROOT =
File.dirname(File.expand_path(File.dirname(__FILE__)))
VERSION =
'0.5.9'

Instance Method Summary collapse

Constructor Details

#initialize(port, interface = '127.0.0.1', lock_timeout = 15 * 60) ⇒ SocketLock

Returns a new instance of SocketLock.



11
12
13
14
15
16
17
18
19
# File 'lib/socketlock.rb', line 11

def initialize port, interface = '127.0.0.1', lock_timeout = 15 * 60
	@port = port
	@interface = interface
	@locked = false
	@unlock_code = 'unlock'
	@lock_timeout = lock_timeout
	@monitor = Monitor.new
	@unlock_thread = nil
end

Instance Method Details

#lockObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/socketlock.rb', line 21

def lock
	@monitor.synchronize do
		return if locked? # we already have it
		Timeout::timeout(@lock_timeout) do
			while true
				begin
					@server = TCPServer.new(@interface, @port)
					@locked = true
					break
				rescue => e
					# Whoops... still not ours
					sleep(1.0)
				end
			end
		end # Timeout::timeout(@lock_timeout)
		# Watch for unlock requests
		@unlock_thread = Thread.new do
			while true
				begin
					socket = @server.accept()
					@monitor.synchronize do
						code = socket.gets.strip
						begin socket.close(); rescue; end
						if code == @unlock_code
							@locked = false
							@unlock_thread = nil
							@server.close()
							break
						end
					end
				rescue => e
					# Getting conn probs. We're just ignoring it.
					sleep(0.5)
				end
			end
		end # @unlock_thread
	end # @monitor.synchronize
end

#locked?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/socketlock.rb', line 71

def locked?
	@monitor.synchronize {return @locked}
end

#unlockObject

def lock



60
61
62
63
64
65
66
67
68
69
# File 'lib/socketlock.rb', line 60

def unlock
	@monitor.synchronize do
		if locked?
			socket = TCPSocket.new(@interface, @port)
			socket.puts @unlock_code
			socket.close()
			sleep(0.5) # Give it a chance
		end
	end
end