url_unescape: fix ordering of "+" => " " of swap
[ruby-mogilefs-client.git] / lib / mogilefs / backend.rb
blob50272dff6517826085d46f05f70feed477ae786c
1 # -*- encoding: binary -*-
2 require 'thread'
4 # This class communicates with the MogileFS trackers.
5 # You should not have to use this directly unless you are developing
6 # support for new commands or plugins for MogileFS
7 class MogileFS::Backend
9   # Adds MogileFS commands +names+.
10   def self.add_command(*names)
11     names.each do |name|
12       define_method name do |*args|
13         do_request(name, args[0] || {}, false)
14       end
15     end
16   end
18   # adds idempotent MogileFS commands +names+, these commands may be retried
19   # transparently on a different tracker if there is a network/server error.
20   def self.add_idempotent_command(*names)
21     names.each do |name|
22       define_method name do |*args|
23         do_request(name, args[0] || {}, true)
24       end
25     end
26   end
28   BACKEND_ERRORS = {} # :nodoc:
30   # this converts an error code from a mogilefsd tracker to an exception:
31   #
32   # Examples of some exceptions that get created:
33   #   class AfterMismatchError < MogileFS::Error; end
34   #   class DomainNotFoundError < MogileFS::Error; end
35   #   class InvalidCharsError < MogileFS::Error; end
36   def self.add_error(err_snake)
37     err_camel = err_snake.gsub(/(?:^|_)([a-z])/) { $1.upcase }
38     err_camel << 'Error' unless /Error\z/ =~ err_camel
39     unless const_defined?(err_camel)
40       const_set(err_camel, Class.new(MogileFS::Error))
41     end
42     BACKEND_ERRORS[err_snake] = const_get(err_camel)
43   end
45   ##
46   # The last error
48   attr_reader :lasterr
50   ##
51   # The string attached to the last error
53   attr_reader :lasterrstr
55   ##
56   # Creates a new MogileFS::Backend.
57   #
58   # :hosts is a required argument and must be an Array containing one or more
59   # 'hostname:port' pairs as Strings.
60   #
61   # :timeout adjusts the request timeout before an error is returned.
63   def initialize(args)
64     @hosts = args[:hosts]
65     raise ArgumentError, "must specify at least one host" unless @hosts
66     raise ArgumentError, "must specify at least one host" if @hosts.empty?
67     unless @hosts == @hosts.select { |h| h =~ /:\d+$/ } then
68       raise ArgumentError, ":hosts must be in 'host:port' form"
69     end
71     @mutex = Mutex.new
72     @timeout = args[:timeout] || 3
73     @socket = nil
74     @lasterr = nil
75     @lasterrstr = nil
77     @dead = {}
78   end
80   ##
81   # Closes this backend's socket.
83   def shutdown
84     @mutex.synchronize { shutdown_unlocked }
85   end
87   # MogileFS::MogileFS commands
89   add_command :create_open
90   add_command :create_close
91   add_idempotent_command :get_paths
92   add_command :delete
93   add_idempotent_command :sleep
94   add_command :rename
95   add_idempotent_command :list_keys
96   add_idempotent_command :file_info
97   add_idempotent_command :file_debug
99   # MogileFS::Backend commands
101   add_idempotent_command :get_hosts
102   add_idempotent_command :get_devices
103   add_idempotent_command :list_fids
104   add_idempotent_command :stats
105   add_idempotent_command :get_domains
106   add_command :create_domain
107   add_command :delete_domain
108   add_command :create_class
109   add_command :update_class
110   add_command :delete_class
111   add_command :create_host
112   add_command :update_host
113   add_command :delete_host
114   add_command :set_state
116   # Errors copied from MogileFS/Worker/Query.pm
117   add_error 'dup'
118   add_error 'after_mismatch'
119   add_error 'bad_params'
120   add_error 'class_exists'
121   add_error 'class_has_files'
122   add_error 'class_not_found'
123   add_error 'db'
124   add_error 'domain_has_files'
125   add_error 'domain_exists'
126   add_error 'domain_not_empty'
127   add_error 'domain_not_found'
128   add_error 'failure'
129   add_error 'host_exists'
130   add_error 'host_mismatch'
131   add_error 'host_not_empty'
132   add_error 'host_not_found'
133   add_error 'invalid_chars'
134   add_error 'invalid_checker_level'
135   add_error 'invalid_mindevcount'
136   add_error 'key_exists'
137   add_error 'no_class'
138   add_error 'no_devices'
139   add_error 'no_domain'
140   add_error 'no_host'
141   add_error 'no_ip'
142   add_error 'no_key'
143   add_error 'no_port'
144   add_error 'none_match'
145   add_error 'plugin_aborted'
146   add_error 'state_too_high'
147   add_error 'size_verify_error'
148   add_error 'unknown_command'
149   add_error 'unknown_host'
150   add_error 'unknown_key'
151   add_error 'unknown_state'
152   add_error 'unreg_domain'
154   private unless defined? $TESTING
156   def shutdown_unlocked # :nodoc:
157     if @socket
158       @socket.close rescue nil # ignore errors
159       @socket = nil
160     end
161   end
163   def dispatch_unlocked(request) # :nodoc:
164     begin
165       io = socket
166       io.timed_write(request, @timeout)
167       io
168     rescue SystemCallError => err
169       @dead[@active_host] = [ Time.now, err ]
170       shutdown_unlocked
171       retry
172     end
173   end
175   # Performs the +cmd+ request with +args+.
176   def do_request(cmd, args, idempotent = false)
177     request = make_request cmd, args
178     @mutex.synchronize do
179       begin
180         io = dispatch_unlocked(request)
181         line = io.timed_gets(@timeout) and return parse_response(line)
183         idempotent or
184           raise EOFError, "end of file reached after: #{request.inspect}"
185         # fall through to retry in loop
186       rescue SystemCallError,
187              MogileFS::UnreadableSocketError,
188              MogileFS::InvalidResponseError, # truncated response
189              MogileFS::Timeout
190         # we got a successful timed_write, but not a timed_gets
191         retry if idempotent
192         shutdown_unlocked
193         raise
194       rescue => err
195         # we DO NOT want the response we timed out waiting for, to crop up later
196         # on, on the same socket, intersperesed with a subsequent request!  we
197         # close the socket if there's any error.
198         shutdown_unlocked
199         raise
200       end while idempotent
201     end # @mutex.synchronize
202   end
204   # Makes a new request string for +cmd+ and +args+.
205   def make_request(cmd, args)
206     "#{cmd} #{url_encode args}\r\n"
207   end
209   # this converts an error code from a mogilefsd tracker to an exception
210   # Most of these exceptions should already be defined, but since the
211   # MogileFS server code is liable to change and we may not always be
212   # able to keep up with the changes
213   def error(err_snake)
214     BACKEND_ERRORS[err_snake] || self.class.add_error(err_snake)
215   end
217   # Turns the +line+ response from the server into a Hash of options, an
218   # error, or raises, as appropriate.
219   def parse_response(line)
220     if line =~ /^ERR\s+(\w+)\s*([^\r\n]*)/
221       @lasterr = $1
222       @lasterrstr = $2 ? url_unescape($2) : nil
223       raise error(@lasterr), @lasterrstr
224     end
226     return url_decode($1) if line =~ /^OK\s+\d*\s*(\S*)\r\n\z/
228     raise MogileFS::InvalidResponseError,
229           "Invalid response from server: #{line.inspect}"
230   end
232   # Returns a socket connected to a MogileFS tracker.
233   def socket
234     return @socket if @socket and not @socket.closed?
236     now = Time.now
238     @hosts.shuffle.each do |host|
239       next if @dead.include?(host) and @dead[host][0] > now - 5
241       begin
242         addr, port = host.split(/:/)
243         @socket = MogileFS::Socket.tcp(addr, port, @timeout)
244         @active_host = host
245       rescue SystemCallError, MogileFS::Timeout => err
246         @dead[host] = [ now, err ]
247         next
248       end
250       return @socket
251     end
253     errors = @dead.map { |host,(_,e)| "#{host} - #{e.message} (#{e.class})" }
254     raise MogileFS::UnreachableBackendError,
255           "couldn't connect to any tracker: #{errors.join(', ')}"
256   end
258   # Turns a url params string into a Hash.
259   def url_decode(str) # :nodoc:
260     Hash[*(str.split(/&/).map! { |pair|
261       pair.split(/=/, 2).map! { |x| url_unescape(x) }
262     } ).flatten]
263   end
265   # :stopdoc:
266   # TODO: see if we can use existing URL-escape/unescaping routines
267   # in the Ruby standard library, Perl MogileFS seems to NIH these
268   #  routines, too
269   # :startdoc:
271   # Turns a Hash (or Array of pairs) into a url params string.
272   def url_encode(params) # :nodoc:
273     params.map do |k,v|
274       "#{url_escape k.to_s}=#{url_escape v.to_s}"
275     end.join("&")
276   end
278   # Escapes naughty URL characters.
279   if ''.respond_to?(:ord) # Ruby 1.9
280     def url_escape(str) # :nodoc:
281       str.gsub(/([^\w\,\-.\/\\\: ])/) { "%%%02x" % $1.ord }.tr(' ', '+')
282     end
283   else # Ruby 1.8
284     def url_escape(str) # :nodoc:
285       str.gsub(/([^\w\,\-.\/\\\: ])/) { "%%%02x" % $1[0] }.tr(' ', '+')
286     end
287   end
289   # Unescapes naughty URL characters.
290   def url_unescape(str) # :nodoc:
291     str.tr('+', ' ').gsub(/%([a-f0-9][a-f0-9])/i) { [$1.to_i(16)].pack 'C' }
292   end