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