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