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