backend: remove pointless connect_to method
[ruby-mogilefs-client.git] / lib / mogilefs / backend.rb
blobc4f4395e53daa870f28fa144d76f7985ed393a74
1 require 'mogilefs'
2 require 'mogilefs/util'
3 require 'thread'
5 ##
6 # MogileFS::Backend communicates with the MogileFS trackers.
8 class MogileFS::Backend
10   ##
11   # Adds MogileFS commands +names+.
13   def self.add_command(*names)
14     names.each do |name|
15       define_method name do |*args|
16         do_request name, args.first || {}
17       end
18     end
19   end
21   BACKEND_ERRORS = {}
23   # this converts an error code from a mogilefsd tracker to an exception:
24   #
25   # Examples of some exceptions that get created:
26   #   class AfterMismatchError < MogileFS::Error; end
27   #   class DomainNotFoundError < MogileFS::Error; end
28   #   class InvalidCharsError < MogileFS::Error; end
29   def self.add_error(err_snake)
30     err_camel = err_snake.gsub(/(?:^|_)([a-z])/) { $1.upcase } << 'Error'
31     unless self.const_defined?(err_camel)
32       self.class_eval("class #{err_camel} < MogileFS::Error; end")
33     end
34     BACKEND_ERRORS[err_snake] = self.const_get(err_camel)
35   end
37   ##
38   # The last error
40   attr_reader :lasterr
42   ##
43   # The string attached to the last error
45   attr_reader :lasterrstr
47   ##
48   # Creates a new MogileFS::Backend.
49   #
50   # :hosts is a required argument and must be an Array containing one or more
51   # 'hostname:port' pairs as Strings.
52   #
53   # :timeout adjusts the request timeout before an error is returned.
55   def initialize(args)
56     @hosts = args[:hosts]
57     raise ArgumentError, "must specify at least one host" unless @hosts
58     raise ArgumentError, "must specify at least one host" if @hosts.empty?
59     unless @hosts == @hosts.select { |h| h =~ /:\d+$/ } then
60       raise ArgumentError, ":hosts must be in 'host:port' form"
61     end
63     @mutex = Mutex.new
64     @timeout = args[:timeout] || 3
65     @socket = nil
66     @lasterr = nil
67     @lasterrstr = nil
69     @dead = {}
70   end
72   ##
73   # Closes this backend's socket.
75   def shutdown
76     if @socket
77       @socket.close rescue nil # ignore errors
78       @socket = nil
79     end
80   end
82   # MogileFS::MogileFS commands
84   add_command :create_open
85   add_command :create_close
86   add_command :get_paths
87   add_command :delete
88   add_command :sleep
89   add_command :rename
90   add_command :list_keys
92   # MogileFS::Backend commands
93   
94   add_command :get_hosts
95   add_command :get_devices
96   add_command :list_fids
97   add_command :stats
98   add_command :get_domains
99   add_command :create_domain
100   add_command :delete_domain
101   add_command :create_class
102   add_command :update_class
103   add_command :delete_class
104   add_command :create_host
105   add_command :update_host
106   add_command :delete_host
107   add_command :set_state
109   # Errors copied from MogileFS/Worker/Query.pm
110   add_error 'dup'
111   add_error 'after_mismatch'
112   add_error 'bad_params'
113   add_error 'class_exists'
114   add_error 'class_has_files'
115   add_error 'class_not_found'
116   add_error 'db'
117   add_error 'domain_has_files'
118   add_error 'domain_exists'
119   add_error 'domain_not_empty'
120   add_error 'domain_not_found'
121   add_error 'failure'
122   add_error 'host_exists'
123   add_error 'host_mismatch'
124   add_error 'host_not_empty'
125   add_error 'host_not_found'
126   add_error 'invalid_chars'
127   add_error 'invalid_checker_level'
128   add_error 'invalid_mindevcount'
129   add_error 'key_exists'
130   add_error 'no_class'
131   add_error 'no_devices'
132   add_error 'no_domain'
133   add_error 'no_host'
134   add_error 'no_ip'
135   add_error 'no_key'
136   add_error 'no_port'
137   add_error 'none_match'
138   add_error 'plugin_aborted'
139   add_error 'state_too_high'
140   add_error 'unknown_command'
141   add_error 'unknown_host'
142   add_error 'unknown_key'
143   add_error 'unknown_state'
144   add_error 'unreg_domain'
146   private unless defined? $TESTING
148   ##
149   # Performs the +cmd+ request with +args+.
151   def do_request(cmd, args)
152     @mutex.synchronize do
153       request = make_request cmd, args
155       begin
156         bytes_sent = socket.send request, 0
157       rescue SystemCallError
158         shutdown
159         raise MogileFS::UnreachableBackendError
160       end
162       unless bytes_sent == request.length then
163         raise MogileFS::RequestTruncatedError,
164           "request truncated (sent #{bytes_sent} expected #{request.length})"
165       end
167       readable?
169       return parse_response(socket.gets)
170     end
171   end
173   ##
174   # Makes a new request string for +cmd+ and +args+.
176   def make_request(cmd, args)
177     return "#{cmd} #{url_encode args}\r\n"
178   end
180   # this converts an error code from a mogilefsd tracker to an exception
181   # Most of these exceptions should already be defined, but since the
182   # MogileFS server code is liable to change and we may not always be
183   # able to keep up with the changes
184   def error(err_snake)
185     BACKEND_ERRORS[err_snake] || self.class.add_error(err_snake)
186   end
188   ##
189   # Turns the +line+ response from the server into a Hash of options, an
190   # error, or raises, as appropriate.
192   def parse_response(line)
193     if line =~ /^ERR\s+(\w+)\s*(.*)/ then
194       @lasterr = $1
195       @lasterrstr = $2 ? url_unescape($2) : nil
196       raise error(@lasterr)
197       return nil
198     end
200     return url_decode($1) if line =~ /^OK\s+\d*\s*(\S*)/
202     raise MogileFS::InvalidResponseError,
203           "Invalid response from server: #{line.inspect}"
204   end
206   ##
207   # Raises if the socket does not become readable in +@timeout+ seconds.
209   def readable?
210     timeleft = @timeout
211     peer = nil
212     loop do
213       t0 = Time.now
214       found = IO.select([socket], nil, nil, timeleft)
215       return true if found && found[0]
216       timeleft -= (Time.now - t0)
218       if timeleft < 0
219         peer = @socket ? "#{@socket.mogilefs_peername} " : nil
221         # we DO NOT want the response we timed out waiting for, to crop up later
222         # on, on the same socket, intersperesed with a subsequent request! so,
223         # we close the socket if it times out like this
224         shutdown
225         raise MogileFS::UnreadableSocketError, "#{peer}never became readable"
226         break
227       end
228       shutdown
229     end
230     false
231   end
233   ##
234   # Returns a socket connected to a MogileFS tracker.
236   def socket
237     return @socket if @socket and not @socket.closed?
239     now = Time.now
241     @hosts.sort_by { rand(3) - 1 }.each do |host|
242       next if @dead.include? host and @dead[host] > now - 5
244       begin
245         @socket = Socket.mogilefs_new(*(host.split(/:/) << @timeout))
246       rescue SystemCallError, MogileFS::Timeout
247         @dead[host] = now
248         next
249       end
251       return @socket
252     end
254     raise MogileFS::UnreachableBackendError
255   end
257   ##
258   # Turns a url params string into a Hash.
260   def url_decode(str)
261     pairs = str.split('&').map do |pair|
262       pair.split('=', 2).map { |v| url_unescape v }
263     end
265     return Hash[*pairs.flatten]
266   end
268   ##
269   # Turns a Hash (or Array of pairs) into a url params string.
271   def url_encode(params)
272     return params.map do |k,v|
273       "#{url_escape k.to_s}=#{url_escape v.to_s}"
274     end.join("&")
275   end
277   ##
278   # Escapes naughty URL characters.
280   def url_escape(str)
281     return str.gsub(/([^\w\,\-.\/\\\: ])/) { "%%%02x" % $1[0] }.tr(' ', '+')
282   end
284   ##
285   # Unescapes naughty URL characters.
287   def url_unescape(str)
288     return str.gsub(/%([a-f0-9][a-f0-9])/i) { [$1.to_i(16)].pack 'C' }.tr('+', ' ')
289   end