mog: small cleanups
[ruby-mogilefs-client.git] / bin / mog
blobf8647b6add253d16f8ba7921cf5c4dc322522376
1 #!/usr/bin/env ruby
2 require 'mogilefs'
3 require 'optparse'
4 $stdin.binmode
5 $stdout.binmode
6 $stderr.sync = $stdout.sync = true
8 trap('INT') { exit 130 }
9 trap('PIPE') { exit 0 }
11 # this is to be compatible with config files used by the Perl tools
12 def parse_config_file!(path, overwrite = false)
13 dest = {}
14 File.open(path).each_line do |line|
15 line.strip!
16 if /^(domain|class)\s*=\s*(\S+)/.match(line)
17 dest[$1.to_sym] = $2
18 elsif m = /^(?:trackers|hosts)\s*=\s*(.*)/.match(line)
19 dest[:hosts] = $1.split(/\s*,\s*/)
20 elsif m = /^timeout\s*=\s*(.*)/.match(line)
21 dest[:timeout] = m[1].to_f
22 else
23 warn "Ignored configuration line: #{line}" unless /^#/.match(line)
24 end
25 end
26 dest
27 end
29 # parse the default config file if one exists
30 def_file = File.expand_path("~/.mogilefs-client.conf")
31 def_cfg = File.exist?(def_file) ? parse_config_file!(def_file) : {}
33 # parse the command-line first, these options take precedence over all else
34 cli_cfg = {}
35 config_file = nil
36 ls_l = false
37 ls_h = false
38 test = {}
39 cat = { :raw => false }
41 ARGV.options do |x|
42 x.banner = "Usage: #{$0} [options] <command> [<arguments>]"
43 x.separator ''
45 x.on('-c', '--config=/path/to/config',
46 'config file to load') { |file| config_file = file }
48 x.on('-t', '--trackers=host1[,host2]', '--hosts=host1[,host2]', Array,
49 'hostnames/IP addresses of trackers') do |trackers|
50 cli_cfg[:hosts] = trackers
51 end
53 x.on('-e', 'True if key exists') { test[:e] = true }
54 x.on('-r', '--raw', 'show raw big_info file information') { cat[:raw] = true }
56 x.on('-C', '--class=s', 'class') { |klass| cli_cfg[:class] = klass }
57 x.on('-d', '--domain=s', 'domain') { |domain| cli_cfg[:domain] = domain }
58 x.on('-l', "long listing format (`ls' command)") { ls_l = true }
59 x.on('-h', '--human-readable',
60 "print sizes in human-readable format (`ls' command)") { ls_h = true }
62 x.separator ''
63 x.on('--help', 'Show this help message.') { puts x; exit }
64 x.parse!
65 end
67 # parse the config file specified at the command-line
68 file_cfg = config_file ? parse_config_file!(config_file, true) : {}
70 # read environment variables, too. This Ruby API favors the term
71 # "hosts", however upstream MogileFS teminology favors "trackers" instead.
72 # Favor the term more consistent with what the MogileFS inventors used.
73 env_cfg = {}
74 if ENV["MOG_TRACKERS"]
75 env_cfg[:hosts] = ENV["MOG_TRACKERS"].split(/\s*,\s*/)
76 end
77 if ENV["MOG_HOSTS"] && (env_cfg[:hosts] || []).empty?
78 env_cfg[:hosts] = ENV["MOG_HOSTS"].split(/\s*,\s*/)
79 end
80 env_cfg[:domain] = ENV["MOG_DOMAIN"] if ENV["MOG_DOMAIN"]
81 env_cfg[:class] = ENV["MOG_CLASS"] if ENV["MOG_CLASS"]
83 # merge the configs, favoring them in order specified:
84 cfg = {}.merge(def_cfg).merge(env_cfg).merge(file_cfg).merge(cli_cfg)
86 # error-checking
87 err = []
88 err << "trackers must be specified" if cfg[:hosts].nil? || cfg[:hosts].empty?
89 err << "domain must be specified" unless cfg[:domain]
90 if err.any?
91 warn "Errors:\n #{err.join("\n ")}"
92 warn ARGV.options
93 exit 1
94 end
96 unless cmd = ARGV.shift
97 warn ARGV.options
98 exit 1
99 end
101 cfg[:timeout] ||= 30 # longer timeout for interactive use
102 mg = MogileFS::MogileFS.new(cfg)
104 def store_file_retry(mg, key, storage_class, filepath)
105 tries = 0
106 begin
107 mg.store_file(key, storage_class, filepath)
108 rescue MogileFS::UnreadableSocketError,
109 MogileFS::Backend::NoDevicesError => err
110 if ((tries += 1) < 10)
111 warn "Retrying on error: #{err}: #{err.message} tries: #{tries}"
112 retry
113 else
114 warn "FATAL: #{err}: #{err.message} tries: #{tries}"
116 exit 1
120 def human_size(size)
121 suff = ''
122 %w(K M G).each do |s|
123 size /= 1024.0
124 if size <= 1024
125 suff = s
126 break
129 sprintf("%.1f%s", size, suff)
132 begin
133 case cmd
134 when 'cp'
135 filename = ARGV.shift or raise ArgumentError, '<filename> <key>'
136 key = ARGV.shift or raise ArgumentError, '<filename> <key>'
137 ARGV.shift and raise ArgumentError, '<filename> <key>'
138 store_file_retry(mg, key, cfg[:class], filename)
139 when 'cat'
140 ARGV.empty? and raise ArgumentError, '<key1> [<key2> ...]'
141 ARGV.each do |key|
142 if (!cat[:raw] && key =~ /^_big_info:/)
143 mg.bigfile_write(key, $stdout, {:verify => true})
144 else
145 mg.get_file_data(key, $stdout)
148 when 'ls'
149 prefixes = ARGV.empty? ? [ nil ] : ARGV
150 if ls_l
151 each_key = lambda do |key, size, devcount|
152 size = ls_h && size > 1024 ? human_size(size) : size.to_s
153 size = (' ' * (12 - size.length)) << size # right justify
154 puts [ sprintf("% 2d", devcount), size, key ].pack("A4 A16 A*")
156 else
157 each_key = lambda { |key| puts key }
159 prefixes.each { |prefix| mg.each_key(prefix, &each_key) }
160 when 'rm'
161 ARGV.empty? and raise ArgumentError, '<key1> [<key2>]'
162 ARGV.each { |key| mg.delete(key) }
163 when 'mv'
164 from = ARGV.shift or raise ArgumentError, '<from> <to>'
165 to = ARGV.shift or raise ArgumentError, '<from> <to>'
166 ARGV.shift and raise ArgumentError, '<from> <to>'
167 mg.rename(from, to)
168 when 'stat' # this outputs a RFC822-like format
169 ARGV.empty? and raise ArgumentError, '<key1> [<key2>]'
170 ARGV.each_with_index do |key, i|
171 if size = mg.size(key)
172 puts "Key: #{key}"
173 puts "Size: #{size}"
174 mg.get_paths(key).each_with_index do |path,i|
175 puts "URL-#{i}: #{path}"
177 puts ""
178 else
179 warn "No such key: #{key}"
182 when 'tee'
183 require 'tempfile'
184 key = ARGV.shift or raise ArgumentError, '<key>'
185 ARGV.shift and raise ArgumentError, '<key>'
186 cfg[:class] or raise ArgumentError, 'E: --class must be specified'
187 buf = ''
188 tmp = Tempfile.new('mog-tee') # TODO: explore Transfer-Encoding:chunked :)
190 # if stdout is pointing to /dev/null, don't bother installing the filter.
191 tee_obj = tmp
192 if File.stat('/dev/null') != $stdout.stat
193 tee_obj = lambda do |buf|
194 rv = nil
195 [ $stdout, tmp ].each { |io| rv = io.write(buf) }
198 def tee_obj.write(buf)
199 self[buf]
202 begin
203 MogileFS::X.copy_stream($stdin, tee_obj)
204 store_file_retry(mg, key, cfg[:class], tmp.path)
205 ensure
206 tmp.close!
208 when 'test'
209 truth, ok = true, nil
210 raise ArgumentError, "-e must be specified" unless (test.size == 1)
212 truth, key = case ARGV.size
213 when 1
214 [ true, ARGV[0] ]
215 when 2
216 if ARGV[0] != "!"
217 raise ArgumentError, "#{ARGV[0]}: binary operator expected"
219 [ false, ARGV[1] ]
220 else
221 raise ArgumentError, "Too many arguments"
224 paths = mg.get_paths(key)
225 if test[:e]
226 ok = !!(paths && paths.size > 0)
227 else
228 raise ArgumentError, "Unknown flag: -#{test.keys.first}"
231 truth or ok = ! ok
232 exit ok ? 0 : 1
233 else
234 raise ArgumentError, "Unknown command: #{cmd}"
236 rescue ArgumentError => err
237 warn "Usage: #{$0} #{cmd} #{err.message}"
238 exit 1
240 exit 0