client: each_key: accept optional :after and :limit args
[ruby-mogilefs-client.git] / lib / mogilefs / mogilefs.rb
blobcd6f7c6cb108d5eed28583d2b7f6b5dbe0be2f8a
1 # -*- encoding: binary -*-
3 # \MogileFS file manipulation client.
5 #   Create a new instance that will communicate with these trackers:
6 #   hosts = %w[192.168.1.69:6001 192.168.1.70:6001]
7 #   mg = MogileFS::MogileFS.new(:domain => 'test', :hosts => hosts)
9 #   # Stores "A bunch of text to store" into 'some_key' with a class of 'text'.
10 #   mg.store_content('some_key', 'text', "A bunch of text to store")
12 #   # Retrieve data from 'some_key' as a string
13 #   data = mg.get_file_data('some_key')
15 #   # Store the contents of 'image.jpeg' into the key 'my_image' with a
16 #   # class of 'image'.
17 #   mg.store_file('my_image', 'image', 'image.jpeg')
19 #   # Store the contents of 'image.jpeg' into the key 'my_image' with a
20 #   # class of 'image' using an open IO object.
21 #   File.open('image.jpeg') { |fp| mg.store_file('my_image', 'image', fp) }
23 #   # Retrieve the contents of 'my_image' into '/path/to/huge_file'
24 #   # without slurping the entire contents into memory:
25 #   mg.get_file_data('my_image', '/path/to/huge_file')
27 #   # Remove the key 'my_image' and 'some_key'.
28 #   mg.delete('my_image')
29 #   mg.delete('some_key')
31 class MogileFS::MogileFS < MogileFS::Client
32   include MogileFS::Bigfile
34   # The domain of keys for this MogileFS client.
35   attr_accessor :domain
37   # The timeout for get_file_data (per-read() system call).
38   # Defaults to five seconds.
39   attr_accessor :get_file_data_timeout
41   # The maximum allowed time for creating a new_file.  Defaults to 1 hour.
42   attr_accessor :new_file_max_time
44   # Creates a new MogileFS::MogileFS instance.  +args+ must include a key
45   # :domain specifying the domain of this client.
46   #
47   # Optional parameters for +args+:
48   #
49   # [:get_file_data_timeout => Numeric]
50   #
51   #   See get_file_data_timeout
52   #
53   # [:new_file_max_time => Numeric]
54   #
55   #   See new_file_max_time
56   #
57   # [:fail_timeout => Numeric]
58   #
59   #   Delay before retrying a failed tracker backends.
60   #   Defaults to 5 seconds.
61   #
62   # [:timeout => Numeric]
63   #
64   #   Timeout for tracker backend responses.
65   #   Defaults to 3 seconds.
66   #
67   def initialize(args = {})
68     @domain = args[:domain]
70     @get_file_data_timeout = args[:get_file_data_timeout] || 5
71     @new_file_max_time = args[:new_file_max_time] || 3600.0
72     @nhp_get = MogileFS::NHP.new('get')
73     @nhp_get.open_timeout = @nhp_get.read_timeout = @get_file_data_timeout
74     @nhp_put = MogileFS::NHP.new('put')
75     @nhp_put.open_timeout = @nhp_put.read_timeout = @new_file_max_time
77     raise ArgumentError, "you must specify a domain" unless @domain
79     if @backend = args[:db_backend]
80       @readonly = true
81     else
82       super
83     end
84   end
86   # Enumerates keys, limited by optional +prefix+
87   # +args+ may also be specified for an optional +:limit+
88   # and +:after+ (default: nil)
89   def each_key(prefix = "", args = nil, &block)
90     after = limit = nil
91     if args
92       after = args[:after]
93       limit = args[:limit]
94     end
95     begin
96       keys, after = list_keys(prefix, after, limit || 1000, &block)
97       return unless keys && keys[0]
98       limit -= keys.size if limit
99     end while limit == nil || limit > 0
100     nil
101   end
103   # Enumerates keys and yields a +file_info+ hash for each key matched by
104   # +prefix+
105   def each_file_info(prefix = "", args = nil)
106     # FIXME: there's a lot of duplicate code from list_keys_verbose here...
107     raise ArgumentError, "need block" unless block_given?
108     ordered = ready = nil
109     on_file_info = lambda do |info|
110       Hash === info or raise info
111       file_info_cleanup(info)
113       # deal with trackers with multiple queryworkers responding out-of-order
114       ready[info["key"]] = info
115       while info = ready.delete(ordered[-1])
116         ordered.pop
117         yield info
118       end
119     end
121     nr = 0
122     opts = { :domain => @domain }
123     opts[:devices] = 1 if args && args[:devices]
124     after = args ? args[:after] : nil
125     limit = args ? args[:limit] : nil
127     begin
128       keys, after = list_keys(prefix, after, limit || 1000)
129       return nr unless keys && keys[0]
130       ordered = keys.reverse
131       ready = {}
132       nr += keys.size
133       limit -= keys.size if limit
135       keys.each do |key|
136         opts[:key] = key
137         @backend.pipeline_dispatch(:file_info, opts, &on_file_info)
138       end
139       @backend.pipeline_wait
140     rescue MogileFS::PipelineError, SystemCallError,
141            MogileFS::RequestTruncatedError,
142            MogileFS::UnreadableSocketError,
143            MogileFS::InvalidResponseError, # truncated response
144            MogileFS::Timeout
145       @backend.shutdown
146       keys = (ordered - ready.keys).reverse!
147       retry
148     end while limit == nil || limit > 0
149   rescue
150     @backend.shutdown
151     raise
152   end
154   # Retrieves the contents of +key+.  If +dst+ is specified, +dst+
155   # should be an IO-like object capable of receiving the +write+ method
156   # or a path name.  +copy_length+ may be specified to limit the number of
157   # bytes to retrieve, and +src_offset+ can be specified to specified the
158   # start position of the copy.
159   def get_file_data(key, dst = nil, copy_length = nil, src_offset = nil)
160     paths = get_paths(key)
161     if src_offset || copy_length
162       src_offset ||= 0
163       range_end = copy_length ? src_offset + copy_length - 1 : nil
164       range = [ src_offset, range_end ]
165     end
167     if dst
168       sock = MogileFS::HTTPReader.first(paths, @get_file_data_timeout, range)
169       sock.stream_to(dst)
170     elsif block_given?
171       sock = MogileFS::HTTPReader.first(paths, @get_file_data_timeout, range)
172       yield(sock)
173     else
174       errors = nil
175       paths.each do |path|
176         uri = URI.parse(path)
177         get = Net::HTTP::Get.new(uri.path)
178         get["range"] = "bytes=#{range[0]}-#{range[1]}" if range
179         begin
180           res = @nhp_get.request(uri, get)
181           case res.code.to_i
182           when 200, 206
183             return res.body
184           end
185           (errors ||= []) << "#{path} - #{res.message} (#{res.class})"
186         rescue => e
187           (errors ||= []) << "#{path} - #{e.message} (#{e.class})"
188         end
189       end
190       raise MogileFS::Error,
191             "all paths failed with GET: #{errors.join(', ')}", []
192     end
193   ensure
194     sock.close if sock && ! sock.closed?
195   end
197   # Get the paths (URLs as strings) for +key+.  If +args+ is specified,
198   # it may contain:
199   # - :noverify -> boolean, whether or not the tracker checks (default: true)
200   # - :pathcount -> a positive integer of URLs to retrieve (default: 2)
201   # - :zone -> "alt" or nil (default: nil)
202   #
203   # :noverify defaults to true because this client library is capable of
204   # verifying paths for readability itself.  It is also faster and more
205   # reliable to verify paths on the client.
206   def get_paths(key, *args)
207     opts = {
208       :domain => @domain,
209       :key => key,
210       :noverify => args[0],
211       :zone => args[1],
212     }
213     if Hash === args[0]
214       args = args[0]
215       opts[:noverify] = args[:noverify]
216       zone = args[:zone] and opts[:zone] = zone
217       pathcount = args[:pathcount] and opts[:pathcount] = pathcount.to_i
218     end
220     opts[:noverify] = false == opts[:noverify] ? 0 : 1
221     @backend.respond_to?(:_get_paths) and return @backend._get_paths(opts)
222     res = @backend.get_paths(opts)
223     (1..res['paths'].to_i).map { |i| res["path#{i}"] }
224   end
226   # Returns +true+ if +key+ exists, +false+ if not
227   def exist?(key)
228     args = { :key => key, :domain => @domain , :ruby_no_raise => true}
229     case rv = @backend.get_paths(args)
230     when Hash
231       true
232     when MogileFS::Backend::UnknownKeyError
233       false
234     else
235       raise rv
236     end
237   end
239   # Get the URIs for +key+ (paths) as URI::HTTP objects
240   def get_uris(key, *args)
241     get_paths(key, *args).map! { |path| URI.parse(path) }
242   end
244   # Creates a new file +key+ in the domain of this object.
245   #
246   # +bytes+ is the expected size of the file if known in advance
247   #
248   # It operates like File.open(..., "w") and may take an optional
249   # block, yielding an IO-like object with support for the methods
250   # documented in MogileFS::NewFile::Writer.
251   #
252   # This atomically replaces existing data stored as +key+
253   # when the block exits or when the returned object is closed.
254   #
255   # +args+ may contain the following options:
256   #
257   # [:content_length => Integer]
258   #
259   #   This has the same effect as the (deprecated) +bytes+ parameter.
260   #
261   # [ :largefile => :stream, :content_range or :tempfile ]
262   #
263   #   See MogileFS::NewFile for more information on this
264   #
265   # [ :class => String]
266   #
267   #   The MogileFS storage class of the object.
268   #
269   # [:content_md5 => String, Proc, or :trailer]
270   #
271   #   This can either be a Base64-encoded String, a Proc object, or
272   #   the :trailer symbol.  If given a String, it will be used as the
273   #   Content-MD5 HTTP header.  If given the :trailer symbol, this library
274   #   will automatically generate an Content-MD5 HTTP trailer.  If given
275   #   a Proc object, this Proc object should give a Base64-encoded string
276   #   which can be used as the Content-MD5 HTTP trailer when called at the
277   #   end of the request.
278   #
279   #   Keep in mind most HTTP servers do not support HTTP trailers, so
280   #   passing a String is usually the safest way to use this.
281   #
282   # [:info => Hash]
283   #
284   #   This is an empty hash that will be filled the same information
285   #   MogileFS::MogileFS#file_info.
286   #
287   #   Additionally, it contains one additional key: :uris,
288   #   an array of URI::HTTP objects to the stored destinations
289   def new_file(key, args = nil, bytes = nil) # :yields: file
290     raise MogileFS::ReadOnlyError if readonly?
291     opts = { :key => key, :multi_dest => 1 }
292     case args
293     when Hash
294       opts[:domain] = args[:domain]
295       open_args = args[:create_open_args]
296       klass = args[:class] and "default" != klass and opts[:class] = klass
297     when String
298       opts[:class] = args if "default" != args
299     end
300     opts[:domain] ||= @domain
301     res = @backend.create_open(open_args ? open_args.merge(opts) : opts)
302     opts[:nhp_put] = @nhp_put
304     dests = if dev_count = res['dev_count'] # multi_dest succeeded
305       (1..dev_count.to_i).map { |i| [res["devid_#{i}"], res["path_#{i}"]] }
306     else # single destination returned
307       # 0x0040:  d0e4 4f4b 2064 6576 6964 3d31 2666 6964  ..OK.devid=1&fid
308       # 0x0050:  3d33 2670 6174 683d 6874 7470 3a2f 2f31  =3&path=http://1
309       # 0x0060:  3932 2e31 3638 2e31 2e37 323a 3735 3030  92.168.1.72:7500
310       # 0x0070:  2f64 6576 312f 302f 3030 302f 3030 302f  /dev1/0/000/000/
311       # 0x0080:  3030 3030 3030 3030 3033 2e66 6964 0d0a  0000000003.fid..
313       [[res['devid'], res['path']]]
314     end
316     opts.merge!(args) if Hash === args
317     opts[:backend] = @backend
318     opts[:fid] = res['fid']
319     opts[:content_length] ||= bytes if bytes
320     opts[:new_file_max_time] ||= @new_file_max_time
321     opts[:start_time] = Time.now
322     info = opts[:info] and info["class"] = klass || "default"
324     case (dests[0][1] rescue nil)
325     when %r{\Ahttp://}
326       http_file = MogileFS::NewFile.new(dests, opts)
327       if block_given?
328         yield http_file
329         return http_file.commit # calls create_close
330       else
331         return http_file
332       end
333     when nil, ''
334       raise MogileFS::EmptyPathError,
335             "Empty path for mogile upload res=#{res.inspect}"
336     else
337       raise MogileFS::UnsupportedPathError,
338             "paths '#{dests.inspect}' returned by backend is not supported"
339     end
340   end
342   # Copies the contents of +file+ into +key+ in class +klass+.  +file+ can be
343   # either a path name (String or Pathname object) or an IO-like object that
344   # responds to #read or #readpartial.  Returns size of +file+ stored.
345   # This atomically replaces existing data stored as +key+
346   def store_file(key, klass, file, opts = nil)
347     raise MogileFS::ReadOnlyError if readonly?
348     (opts ||= {})[:class] = klass if String === klass
350     new_file(key, opts) { |mfp| mfp.big_io = file }
351   end
353   # Stores +content+ into +key+ in class +klass+, where +content+ is a String
354   # This atomically replaces existing data stored as +key+
355   def store_content(key, klass, content, opts = nil)
356     raise MogileFS::ReadOnlyError if readonly?
357     (opts ||= {})[:class] = klass if String === klass
359     new_file(key, opts) do |mfp|
360       if content.is_a?(MogileFS::Util::StoreContent)
361         mfp.streaming_io = content
362       else
363         mfp << content
364       end
365     end
366   end
368   # Removes +key+.
369   def delete(key)
370     raise MogileFS::ReadOnlyError if readonly?
372     @backend.delete :domain => @domain, :key => key
373     true
374   end
376   # Updates +key+ to +newclass+
377   def updateclass(key, newclass)
378     raise MogileFS::ReadOnlyError if readonly?
380     @backend.updateclass(:domain => @domain, :key => key, :class => newclass)
381     true
382   end
384   # Sleeps +duration+, only used for testing
385   def sleep(duration) # :nodoc:
386     @backend.sleep :duration => duration
387   end
389   # Renames a key +from+ to key +to+.
390   def rename(from, to)
391     raise MogileFS::ReadOnlyError if readonly?
393     @backend.rename :domain => @domain, :from_key => from, :to_key => to
394     nil
395   end
397   # Returns the size of +key+.
398   def size(key)
399     @backend.respond_to?(:_size) and return @backend._size(domain, key)
400     begin
401       file_info(key)["length"].to_i
402     rescue MogileFS::Backend::UnknownCommandError
403       paths_size(get_paths(key))
404     end
405   end
407   def paths_size(paths) # :nodoc:
408     require "mogilefs/paths_size"
409     MogileFS::PathsSize.call(paths)
410   end
412   # Lists keys starting with +prefix+ following +after+ up to +limit+.  If
413   # +after+ is nil the list starts at the beginning.
414   def list_keys(prefix = "", after = nil, limit = 1000, &block)
415     @backend.respond_to?(:_list_keys) and
416       return @backend._list_keys(domain, prefix, after, limit, &block)
418     res = @backend.list_keys(:domain => domain, :prefix => prefix,
419                              :after => after, :limit => limit,
420                              :ruby_no_raise => true)
421     MogileFS::Backend::NoneMatchError === res and return
422     raise res if MogileFS::Error === res
424     keys = (1..res['key_count'].to_i).map { |i| res["key_#{i}"] }
425     if block
426       if 1 == block.arity
427         keys.each { |key| block.call(key) }
428       else
429         list_keys_verbose(keys, block)
430       end
431     end
433     [ keys, res['next_after'] ]
434   end
436   def list_keys_verbose(keys, block) # :nodoc:
437     # emulate the MogileFS::Mysql interface, slowly...
438     ordered = keys.reverse
439     ready = {}
440     on_file_info = lambda do |info|
441       Hash === info or raise info
442       file_info_cleanup(info)
444       # deal with trackers with multiple queryworkers responding out-of-order
445       ready[info["key"]] = info
446       while info = ready.delete(ordered[-1])
447         block.call(ordered.pop, info["length"], info["devcount"])
448       end
449     end
450     opts = { :domain => @domain }
451     begin
452       keys.each do |key|
453         opts[:key] = key
454         @backend.pipeline_dispatch(:file_info, opts, &on_file_info)
455       end
456       @backend.pipeline_wait
457     rescue MogileFS::Backend::UnknownCommandError # MogileFS < 2.45
458       @backend.shutdown # reset the socket
459       args = { :pathcount => 0x7fffffff }
460       keys.each do |key|
461         paths = get_paths(key, args)
462         block.call(key, paths_size(paths), paths.size)
463       end
464     rescue MogileFS::PipelineError, SystemCallError,
465            MogileFS::RequestTruncatedError,
466            MogileFS::UnreadableSocketError,
467            MogileFS::InvalidResponseError, # truncated response
468            MogileFS::Timeout
469       @backend.shutdown
470       keys = (ordered - ready.keys).reverse!
471       retry
472     rescue
473       @backend.shutdown
474       raise
475     end
476   end
478   # Return metadata about a file as a hash.
479   # Returns the domain, class, length, devcount, etc. as keys.
480   # Optionally, device ids (not paths) can be returned as
481   # well if :devices is specified and +true+.
482   #
483   # This should only be used for informational purposes, and not usually
484   # for dynamically serving files.
485   #
486   #   mg.file_info("bar")
487   #
488   # Returns:
489   #
490   #   {
491   #     "domain" => "foo",
492   #     "key" => "bar",
493   #     "class" => "default",
494   #     "devcount" => 2,
495   #     "length => 666
496   #   }
497   def file_info(key, args = nil)
498     opts = { :domain => @domain, :key => key }
499     args and devices = args[:devices] and opts[:devices] = devices ? 1 : 0
500     file_info_cleanup(@backend.file_info(opts))
501   end
503   def file_info_cleanup(rv) # :nodoc:
504     %w(fid length devcount).each { |f| rv[f] = rv[f].to_i }
505     devids = rv["devids"] and
506       rv["devids"] = devids.split(/,/).map! { |x| x.to_i }
507     rv
508   end
510   # Given an Integer +fid+ or String +key+ and domain, thorougly search
511   # the database for all occurences of a particular fid.
512   #
513   # Use this sparingly, this command hits the master database numerous
514   # times and is very expensive.  This is not for production use, only
515   # troubleshooting and debugging.
516   #
517   # Searches for fid=666:
518   #
519   #   client.file_debug(666)
520   #
521   # Search for key=foo using the default domain for this object:
522   #
523   #   client.file_debug("foo")
524   #
525   # Search for key=foo in domain="bar":
526   #
527   #   client.file_debug(:key => "foo", :domain => "bar")
528   #
529   def file_debug(args)
530     case args
531     when Integer then args = { "fid" => args }
532     when String then args = { "key" => args }
533     end
534     opts = { :domain => args[:domain] || @domain }.merge!(args)
536     rv = @backend.file_debug(opts)
537     rv.each do |k,v|
538       case k
539       when /_(?:classid|devcount|dmid|fid|length|
540             nexttry|fromdevid|failcount|flags|devid|type)\z/x
541         rv[k] = v.to_i
542       when /devids\z/
543         rv[k] = v.split(/,/).map! { |x| x.to_i }
544       end
545     end
546   end