get_paths: expand and improve tests
[ruby-mogilefs-client.git] / lib / mogilefs / mogilefs.rb
blobf132dd7e7a76d3a07dab797f504030d61c177d68
1 # -*- encoding: binary -*-
3 ##
4 # MogileFS File manipulation client.
6 class MogileFS::MogileFS < MogileFS::Client
8   include MogileFS::Bigfile
10   ##
11   # The domain of keys for this MogileFS client.
13   attr_reader :domain
15   ##
16   # The timeout for get_file_data.  Defaults to five seconds.
18   attr_accessor :get_file_data_timeout
20   ##
21   # Creates a new MogileFS::MogileFS instance.  +args+ must include a key
22   # :domain specifying the domain of this client.
24   def initialize(args = {})
25     @domain = args[:domain]
26     @zone = args[:zone]
28     @get_file_data_timeout = 5
30     raise ArgumentError, "you must specify a domain" unless @domain
32     if @backend = args[:db_backend]
33       @readonly = true
34     else
35       super
36     end
37   end
39   ##
40   # Enumerates keys starting with +key+.
42   def each_key(prefix = "")
43     after = nil
45     keys, after = list_keys prefix
47     until keys.nil? or keys.empty? do
48       keys.each { |k| yield k }
49       keys, after = list_keys prefix, after
50     end
52     nil
53   end
55   ##
56   # Retrieves the contents of +key+.  If +dest+ is specified, +dest+
57   # should be an IO-like object capable of receiving the +write+ method
58   # or a path name.
60   def get_file_data(key, dest = nil)
61     paths = get_paths(key)
62     sock = MogileFS::HTTPReader.first(paths, @get_file_data_timeout)
63     if dest
64       MogileFS::X.copy_stream(sock, dest)
65     elsif block_given?
66       yield(sock)
67     else
68       sock.to_s
69     end
70     ensure
71       sock.close unless sock.closed?
72   end
74   ##
75   # Get the paths for +key+.
77   def get_paths(key, *args)
78     opts = {
79       :domain => @domain,
80       :key => key,
81       :noverify => args[0],
82       :zone => args[1],
83     }
84     if Hash === args[0]
85       args = args[0]
86       opts[:noverify] = args[:noverify]
87       opts[:zone] = args[:zone]
88       pathcount = args[:pathcount] and opts[:pathcount] = pathcount.to_i
89     end
91     opts[:zone] ||= @zone
92     opts[:noverify] = opts[:noverify] ? 1 : 0
93     @backend.respond_to?(:_get_paths) and return @backend._get_paths(opts)
94     res = @backend.get_paths(opts)
95     (1..res['paths'].to_i).map { |i| res["path#{i}"] }.compact
96   end
98   ##
99   # Get the URIs for +key+.
101   def get_uris(key, *args)
102     get_paths(key, *args).map! { |path| URI.parse(path) }
103   end
105   ##
106   # Creates a new file +key+ in +klass+.  +bytes+ is currently unused.
107   #
108   # The +block+ operates like File.open.
110   def new_file(key, klass = nil, bytes = 0) # :yields: file
111     raise MogileFS::ReadOnlyError if readonly?
112     opts = { :domain => @domain, :key => key, :multi_dest => 1 }
113     opts[:class] = klass if klass && klass != "default"
114     res = @backend.create_open(opts)
116     dests = if dev_count = res['dev_count'] # multi_dest succeeded
117       (1..dev_count.to_i).map do |i|
118         [res["devid_#{i}"], res["path_#{i}"]]
119       end
120     else # single destination returned
121       # 0x0040:  d0e4 4f4b 2064 6576 6964 3d31 2666 6964  ..OK.devid=1&fid
122       # 0x0050:  3d33 2670 6174 683d 6874 7470 3a2f 2f31  =3&path=http://1
123       # 0x0060:  3932 2e31 3638 2e31 2e37 323a 3735 3030  92.168.1.72:7500
124       # 0x0070:  2f64 6576 312f 302f 3030 302f 3030 302f  /dev1/0/000/000/
125       # 0x0080:  3030 3030 3030 3030 3033 2e66 6964 0d0a  0000000003.fid..
127       [[res['devid'], res['path']]]
128     end
130     case (dests[0][1] rescue nil)
131     when /^http:\/\// then
132       http_file = MogileFS::HTTPFile.new(dests, bytes)
133       yield http_file
134       rv = http_file.commit
135       @backend.create_close(:fid => res['fid'],
136                             :devid => http_file.devid,
137                             :domain => @domain,
138                             :key => key,
139                             :path => http_file.uri.to_s,
140                             :size => rv)
141       rv
142     when nil, '' then
143       raise MogileFS::EmptyPathError,
144             "Empty path for mogile upload res=#{res.inspect}"
145     else
146       raise MogileFS::UnsupportedPathError,
147             "paths '#{dests.inspect}' returned by backend is not supported"
148     end
149   end
151   ##
152   # Copies the contents of +file+ into +key+ in class +klass+.  +file+ can be
153   # either a path name (String or Pathname object) or an IO-like object that
154   # responds to #read or #readpartial.  Returns size of +file+ stored.
156   def store_file(key, klass, file)
157     raise MogileFS::ReadOnlyError if readonly?
159     new_file(key, klass) { |mfp| mfp.big_io = file }
160   end
162   ##
163   # Stores +content+ into +key+ in class +klass+.
165   def store_content(key, klass, content)
166     raise MogileFS::ReadOnlyError if readonly?
168     new_file key, klass do |mfp|
169       if content.is_a?(MogileFS::Util::StoreContent)
170         mfp.streaming_io = content
171       else
172         mfp << content
173       end
174     end
175   end
177   ##
178   # Removes +key+.
180   def delete(key)
181     raise MogileFS::ReadOnlyError if readonly?
183     @backend.delete :domain => @domain, :key => key
184     true
185   end
187   ##
188   # Sleeps +duration+.
190   def sleep(duration)
191     @backend.sleep :duration => duration
192   end
194   ##
195   # Renames a key +from+ to key +to+.
197   def rename(from, to)
198     raise MogileFS::ReadOnlyError if readonly?
200     @backend.rename :domain => @domain, :from_key => from, :to_key => to
201     nil
202   end
204   ##
205   # Returns the size of +key+.
206   def size(key)
207     @backend.respond_to?(:_size) and return @backend._size(domain, key)
208     begin
209       file_info(key)["length"].to_i
210     rescue MogileFS::Backend::UnknownCommandError
211       paths_size(get_paths(key))
212     end
213   end
215   def paths_size(paths) # :nodoc:
216     require "mogilefs/paths_size"
217     MogileFS::PathsSize.call(paths)
218   end
220   ##
221   # Lists keys starting with +prefix+ follwing +after+ up to +limit+.  If
222   # +after+ is nil the list starts at the beginning.
224   def list_keys(prefix = "", after = nil, limit = 1000)
225     if @backend.respond_to?(:_list_keys)
226       block_given? or return @backend._list_keys(domain, prefix, after, limit)
227       return @backend._list_keys(domain, prefix, after, limit) do |*a|
228         yield(*a)
229       end
230     end
232     res = begin
233       @backend.list_keys(:domain => domain, :prefix => prefix,
234                          :after => after, :limit => limit)
235     rescue MogileFS::Backend::NoneMatchError
236       return
237     end
239     keys = (1..res['key_count'].to_i).map { |i| res["key_#{i}"] }
240     if block_given?
241       # emulate the MogileFS::Mysql interface, slowly...
242       keys.each do |key|
243         begin
244           res = file_info(key)
245         rescue MogileFS::Backend::UnknownCommandError # MogileFS < 2.45
246           paths = get_paths(key)
247           res = { "length" => paths_size(paths), "devcount" => paths.size }
248         end
249         yield key, res["length"], res["devcount"]
250       end
251     end
253     [ keys, res['next_after'] ]
254   end
256   # Return metadata about a file as a hash.
257   # Returns the domain, class, expected length, devcount, etc.
258   # Optionally device ids (not paths) can be returned as
259   # well if :devices is specified and +true+.
260   #
261   # This should only be used for informational purposes, and not usually
262   # for dynamically serving files.
263   def file_info(key, args = nil)
264     opts = { :domain => @domain, :key => key }
265     args and devices = args[:devices] and opts[:devices] = devices ? 1 : 0
266     rv = @backend.file_info(opts)
267     %w(fid length devcount).each { |f| rv[f] = rv[f].to_i }
268     devids = rv["devids"] and
269       rv["devids"] = devids.split(/,/).map! { |x| x.to_i }
270     rv
271   end
273   # Given an Integer +fid+ or String +key+ and domain, thorougly search
274   # the database for all occurences of a particular fid.
275   #
276   # Use this sparingly, this command hits the master database numerous
277   # times and is very expensive.  This is not for production use, only
278   # troubleshooting and debugging.
279   #
280   # Searches for fid=666:
281   #
282   #   client.file_debug(666)
283   #
284   # Search for key=foo using the default domain for this object:
285   #
286   #   client.file_debug("foo")
287   #
288   # Search for key=foo in domain="bar":
289   #
290   #   client.file_debug(:key => "foo", :domain => "bar")
291   #
292   def file_debug(args)
293     case args
294     when Integer then args = { "fid" => args }
295     when String then args = { "key" => args }
296     end
297     opts = { :domain => args[:domain] || @domain }.merge!(args)
299     rv = @backend.file_debug(opts)
300     rv.each do |k,v|
301       case k
302       when /_(?:classid|devcount|dmid|fid|length|
303             nexttry|fromdevid|failcount|flags|devid|type)\z/x
304         rv[k] = v.to_i
305       when /devids\z/
306         rv[k] = v.split(/,/).map! { |x| x.to_i }
307       end
308     end
309   end