store_file/store_content: wire these up to new new_file opts
[ruby-mogilefs-client.git] / lib / mogilefs / mogilefs.rb
blob372eae0349aee875dc93cd7f72ace2ee22870f3d
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.  Defaults to five seconds.
38   attr_accessor :get_file_data_timeout
40   # Creates a new MogileFS::MogileFS instance.  +args+ must include a key
41   # :domain specifying the domain of this client.
42   def initialize(args = {})
43     @domain = args[:domain]
45     @get_file_data_timeout = 5
47     raise ArgumentError, "you must specify a domain" unless @domain
49     if @backend = args[:db_backend]
50       @readonly = true
51     else
52       super
53     end
54   end
56   # Enumerates keys, limited by optional +prefix+
57   def each_key(prefix = "", &block)
58     after = nil
59     begin
60       keys, after = list_keys(prefix, after, 1000, &block)
61     end while keys && keys[0]
62     nil
63   end
65   # Retrieves the contents of +key+.  If +dst+ is specified, +dst+
66   # should be an IO-like object capable of receiving the +write+ method
67   # or a path name.  +copy_length+ may be specified to limit the number of
68   # bytes to retrieve, and +src_offset+ can be specified to specified the
69   # start position of the copy.
70   def get_file_data(key, dst = nil, copy_length = nil, src_offset = nil)
71     paths = get_paths(key)
72     sock = MogileFS::HTTPReader.first(paths, @get_file_data_timeout,
73                                       copy_length, src_offset)
74     if dst
75       sock.stream_to(dst)
76     elsif block_given?
77       yield(sock)
78     else
79       sock.to_s
80     end
81     ensure
82       sock.close if sock && ! sock.closed?
83   end
85   # Get the paths (URLs as strings) for +key+.  If +args+ is specified,
86   # it may contain:
87   # - :noverify -> boolean, whether or not the tracker checks (default: true)
88   # - :pathcount -> a positive integer of URLs to retrieve (default: 2)
89   # - :zone -> "alt" or nil (default: nil)
90   #
91   # :noverify defaults to false because this client library is capable of
92   # verifying paths for readability itself.  It is also faster and more
93   # reliable to verify paths on the client.
94   def get_paths(key, *args)
95     opts = {
96       :domain => @domain,
97       :key => key,
98       :noverify => args[0],
99       :zone => args[1],
100     }
101     if Hash === args[0]
102       args = args[0]
103       opts[:noverify] = args[:noverify]
104       opts[:zone] = args[:zone]
105       pathcount = args[:pathcount] and opts[:pathcount] = pathcount.to_i
106     end
108     opts[:noverify] = false == opts[:noverify] ? 0 : 1
109     @backend.respond_to?(:_get_paths) and return @backend._get_paths(opts)
110     res = @backend.get_paths(opts)
111     (1..res['paths'].to_i).map { |i| res["path#{i}"] }
112   end
114   # Returns +true+ if +key+ exists, +false+ if not
115   def exist?(key)
116     rv = nil
117     args = { :key => key, :domain => @domain }
118     @backend.pipeline_dispatch(:get_paths, args) { |x| rv = (Hash === x) }
119     @backend.pipeline_wait(1)
120     rv
121   end
123   # Get the URIs for +key+ (paths) as URI::HTTP objects
124   def get_uris(key, *args)
125     get_paths(key, *args).map! { |path| URI.parse(path) }
126   end
128   # Creates a new file +key+ in +klass+.  +bytes+ is currently unused.
129   # Consider using store_file instead of this method for large files.
130   # This requires a block passed to it and operates like File.open.
131   # This atomically replaces existing data stored as +key+ when
132   def new_file(key, args = nil, bytes = nil) # :yields: file
133     raise MogileFS::ReadOnlyError if readonly?
134     opts = { :key => key, :multi_dest => 1 }
135     case args
136     when Hash
137       opts[:domain] = args[:domain]
138       klass = args[:class] and "default" != klass and opts[:class] = klass
139     when String
140       opts[:class] = args if "default" != args
141     end
142     opts[:domain] ||= @domain
143     res = @backend.create_open(opts)
145     dests = if dev_count = res['dev_count'] # multi_dest succeeded
146       (1..dev_count.to_i).map { |i| [res["devid_#{i}"], res["path_#{i}"]] }
147     else # single destination returned
148       # 0x0040:  d0e4 4f4b 2064 6576 6964 3d31 2666 6964  ..OK.devid=1&fid
149       # 0x0050:  3d33 2670 6174 683d 6874 7470 3a2f 2f31  =3&path=http://1
150       # 0x0060:  3932 2e31 3638 2e31 2e37 323a 3735 3030  92.168.1.72:7500
151       # 0x0070:  2f64 6576 312f 302f 3030 302f 3030 302f  /dev1/0/000/000/
152       # 0x0080:  3030 3030 3030 3030 3033 2e66 6964 0d0a  0000000003.fid..
154       [[res['devid'], res['path']]]
155     end
157     opts.merge!(args) if Hash === args
158     opts[:backend] = @backend
159     opts[:fid] = res['fid']
160     opts[:content_length] ||= bytes if bytes
162     case (dests[0][1] rescue nil)
163     when %r{\Ahttp://}
164       http_file = MogileFS::HTTPFile.new(dests, opts)
165       if block_given?
166         yield http_file
167         return http_file.commit # calls create_close
168       else
169         return http_file
170       end
171     when nil, ''
172       raise MogileFS::EmptyPathError,
173             "Empty path for mogile upload res=#{res.inspect}"
174     else
175       raise MogileFS::UnsupportedPathError,
176             "paths '#{dests.inspect}' returned by backend is not supported"
177     end
178   end
180   # Copies the contents of +file+ into +key+ in class +klass+.  +file+ can be
181   # either a path name (String or Pathname object) or an IO-like object that
182   # responds to #read or #readpartial.  Returns size of +file+ stored.
183   # This atomically replaces existing data stored as +key+
184   def store_file(key, klass, file, opts = nil)
185     raise MogileFS::ReadOnlyError if readonly?
186     (opts ||= {})[:class] = klass if String === klass
188     new_file(key, opts) { |mfp| mfp.big_io = file }
189   end
191   # Stores +content+ into +key+ in class +klass+, where +content+ is a String
192   # This atomically replaces existing data stored as +key+
193   def store_content(key, klass, content, opts = nil)
194     raise MogileFS::ReadOnlyError if readonly?
195     (opts ||= {})[:class] = klass if String === klass
197     new_file(key, opts) do |mfp|
198       if content.is_a?(MogileFS::Util::StoreContent)
199         mfp.streaming_io = content
200       else
201         mfp << content
202       end
203     end
204   end
206   # Removes +key+.
207   def delete(key)
208     raise MogileFS::ReadOnlyError if readonly?
210     @backend.delete :domain => @domain, :key => key
211     true
212   end
214   # Sleeps +duration+, only used for testing
215   def sleep(duration) # :nodoc:
216     @backend.sleep :duration => duration
217   end
219   # Renames a key +from+ to key +to+.
220   def rename(from, to)
221     raise MogileFS::ReadOnlyError if readonly?
223     @backend.rename :domain => @domain, :from_key => from, :to_key => to
224     nil
225   end
227   # Returns the size of +key+.
228   def size(key)
229     @backend.respond_to?(:_size) and return @backend._size(domain, key)
230     begin
231       file_info(key)["length"].to_i
232     rescue MogileFS::Backend::UnknownCommandError
233       paths_size(get_paths(key))
234     end
235   end
237   def paths_size(paths) # :nodoc:
238     require "mogilefs/paths_size"
239     MogileFS::PathsSize.call(paths)
240   end
242   # Lists keys starting with +prefix+ following +after+ up to +limit+.  If
243   # +after+ is nil the list starts at the beginning.
244   def list_keys(prefix = "", after = nil, limit = 1000, &block)
245     @backend.respond_to?(:_list_keys) and
246       return @backend._list_keys(domain, prefix, after, limit, &block)
248     begin
249       res = @backend.list_keys(:domain => domain, :prefix => prefix,
250                                :after => after, :limit => limit)
251     rescue MogileFS::Backend::NoneMatchError
252       return
253     end
255     keys = (1..res['key_count'].to_i).map { |i| res["key_#{i}"] }
256     if block
257       if 1 == block.arity
258         keys.each { |key| block.call(key) }
259       else
260         list_keys_verbose(keys, block)
261       end
262     end
264     [ keys, res['next_after'] ]
265   end
267   def list_keys_verbose(keys, block) # :nodoc:
268     # emulate the MogileFS::Mysql interface, slowly...
269     ordered = keys.dup
270     ready = {}
271     on_file_info = lambda do |info|
272       Hash === info or raise info
273       file_info_cleanup(info)
275       # deal with trackers with multiple queryworkers responding out-of-order
276       ready[info["key"]] = info
277       while info = ready.delete(ordered[0])
278         block.call(ordered.shift, info["length"], info["devcount"])
279       end
280     end
281     opts = { :domain => @domain }
282     begin
283       keys.each do |key|
284         opts[:key] = key
285         @backend.pipeline_dispatch(:file_info, opts, &on_file_info)
286       end
287       @backend.pipeline_wait
288     rescue MogileFS::Backend::UnknownCommandError # MogileFS < 2.45
289       @backend.shutdown # reset the socket
290       args = { :pathcount => 0x7fffffff }
291       keys.each do |key|
292         paths = get_paths(key, args)
293         block.call(key, paths_size(paths), paths.size)
294       end
295     rescue MogileFS::PipelineError, SystemCallError,
296            MogileFS::RequestTruncatedError,
297            MogileFS::UnreadableSocketError,
298            MogileFS::InvalidResponseError, # truncated response
299            MogileFS::Timeout
300       @backend.shutdown
301       keys = ordered - ready.keys
302       retry
303     rescue
304       @backend.shutdown
305       raise
306     end
307   end
309   # Return metadata about a file as a hash.
310   # Returns the domain, class, length, devcount, etc. as keys.
311   # Optionally, device ids (not paths) can be returned as
312   # well if :devices is specified and +true+.
313   #
314   # This should only be used for informational purposes, and not usually
315   # for dynamically serving files.
316   #
317   #   mg.file_info("bar")
318   #
319   # Returns:
320   #
321   #   {
322   #     "domain" => "foo",
323   #     "key" => "bar",
324   #     "class" => "default",
325   #     "devcount" => 2,
326   #     "length => 666
327   #   }
328   def file_info(key, args = nil)
329     opts = { :domain => @domain, :key => key }
330     args and devices = args[:devices] and opts[:devices] = devices ? 1 : 0
331     file_info_cleanup(@backend.file_info(opts))
332   end
334   def file_info_cleanup(rv) # :nodoc:
335     %w(fid length devcount).each { |f| rv[f] = rv[f].to_i }
336     devids = rv["devids"] and
337       rv["devids"] = devids.split(/,/).map! { |x| x.to_i }
338     rv
339   end
341   # Given an Integer +fid+ or String +key+ and domain, thorougly search
342   # the database for all occurences of a particular fid.
343   #
344   # Use this sparingly, this command hits the master database numerous
345   # times and is very expensive.  This is not for production use, only
346   # troubleshooting and debugging.
347   #
348   # Searches for fid=666:
349   #
350   #   client.file_debug(666)
351   #
352   # Search for key=foo using the default domain for this object:
353   #
354   #   client.file_debug("foo")
355   #
356   # Search for key=foo in domain="bar":
357   #
358   #   client.file_debug(:key => "foo", :domain => "bar")
359   #
360   def file_debug(args)
361     case args
362     when Integer then args = { "fid" => args }
363     when String then args = { "key" => args }
364     end
365     opts = { :domain => args[:domain] || @domain }.merge!(args)
367     rv = @backend.file_debug(opts)
368     rv.each do |k,v|
369       case k
370       when /_(?:classid|devcount|dmid|fid|length|
371             nexttry|fromdevid|failcount|flags|devid|type)\z/x
372         rv[k] = v.to_i
373       when /devids\z/
374         rv[k] = v.split(/,/).map! { |x| x.to_i }
375       end
376     end
377   end