Guest User

Untitled

a guest
Feb 19th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.89 KB | None | 0 0
  1. require 'debug_helper'
  2.  
  3.  
  4. class Lock
  5. include DebugHelper
  6. attr_reader :type, :range, :owner
  7. EXCLUSIVE = 1
  8. NORMAL = 2
  9.  
  10. def initialize(owner, type = EXCLUSIVE,offset = nil, size = nil)
  11. @owner = owner
  12. @type = type
  13. if !offset.nil? and !size.nil? then
  14. @range = Range.new(offset,offset+size)
  15. end
  16. end
  17.  
  18. def concurrent?(lock)
  19. if (@type == EXCLUSIVE) or (lock.type == EXCLUSIVE) then
  20. print_debug({:op => "concurrent?", :result => false, :type => "exclusive"})
  21. return false
  22. elsif @range.include?(lock.range.begin) or @range.include?(lock.range.end) then
  23. print_debug({:op => "concurrent?", :result => false, :type => "normal"})
  24. return false
  25. end
  26. print_debug({:op => "concurrent?", :result => true, :type => "normal"})
  27. true
  28. end
  29. end
  30.  
  31.  
  32. class DLM
  33. include DebugHelper
  34. attr_reader :locks, :config
  35.  
  36.  
  37.  
  38. def initialize(config)
  39. @locks = Hash.new { Array.new }
  40. @config = config
  41. @m = Mutex.new
  42. end
  43.  
  44. def lock(path,type = Lock::EXCLUSIVE, offset = nil, size = nil)
  45. @m.synchronize do
  46. # requested EXCLUSIVE
  47. if type == Lock::EXCLUSIVE then
  48. return nil if @locks.has_key?(path)
  49. l = Lock.new(@config.local_ip)
  50. @locks[path] << l
  51. print_debug({:op => "lock", :path => path, :result => true, :type => "exclusive"}) if @config.debug_dlm
  52. return l
  53. elsif (offset.nil? or size.nil?) then
  54. print_debug({:op => "lock", :error => "somebody kidding"})
  55. return nil
  56. else
  57. l = Lock.new(@config.local_ip,Lock::NORMAL,offset,size)
  58. if @locks.has_key?(path) then
  59. @locks[path].each { |x| return nil if !l.concurrent?(x) }
  60. @locks[path] << l
  61. print_debug({:op => "lock", :path => path, :result => true, :type => "normal/concurrent"}) if @config.debug_dlm
  62. return l
  63. else
  64. @locks[path] << l
  65. print_debug({:op => "lock", :path => path, :result => true, :type => "normal"}) if @config.debug_dlm
  66. return l
  67. end
  68. end
  69. end
  70. end
  71. def release(path, lock = nil)
  72. @m.synchronize do
  73. #exclusive lock
  74. if lock.nil? then
  75. print_debug({:op => "lock", :error => "exclusive and normal lock?!?!"}) if @locks[path].size > 1
  76. @locks.delete path
  77. else
  78. arr = @locks[path]
  79. if arr.nil? then
  80. print_debug({:op => "lock", :error => "trying to release a lock in a path that doesn't exists"})
  81. else
  82. l = arr.delete(lock)
  83. print_debug({:op => "lock", :error => "trying to release a lock that doesn't exists"}) if l.nil?
  84. end
  85. end
  86. end
  87. end
  88. end
Add Comment
Please, Sign In to add comment