Module: Open
- Defined in:
- lib/scout/open.rb,
lib/scout/open/lock.rb,
lib/scout/open/util.rb,
lib/scout/open/remote.rb,
lib/scout/open/stream.rb,
lib/scout/persist/open.rb
Defined Under Namespace
Modules: NamedStream
Constant Summary collapse
- GREP_CMD =
begin if ENV["GREP_CMD"] ENV["GREP_CMD"] elsif File.exist?('/bin/grep') "/bin/grep" elsif File.exist?('/usr/bin/grep') "/usr/bin/grep" else "grep" end end
- BLOCK_SIZE =
1024 * 8
- PIPE_MUTEX =
Mutex.new
- OPEN_PIPE_IN =
[]
Class Attribute Summary collapse
-
.remote_cache_dir ⇒ Object
Returns the value of attribute remote_cache_dir.
-
.sensible_write_dir ⇒ Object
Returns the value of attribute sensible_write_dir.
-
.sensible_write_lock_dir ⇒ Object
Returns the value of attribute sensible_write_lock_dir.
Class Method Summary collapse
- ._just_open ⇒ Object
- .add_cache(url, data, options = {}) ⇒ Object
- .bgunzip(stream) ⇒ Object
- .bgzip(stream) ⇒ Object
- .bgzip?(file) ⇒ Boolean
- .broken_link?(path) ⇒ Boolean
- .cache_file(url, options) ⇒ Object
-
.collapse_stream(s, line: nil, sep: "\t", header: nil, compact: false, &block) ⇒ Object
def self.sort_stream(stream, header_hash = “#”, cmd_args = “-u”) StringIO.new stream.read.split(“n”).sort.uniq * “n” end.
- .consume_stream(io, in_thread = false, into = nil, into_close = true, &block) ⇒ Object
- .cp(source, target, options = {}) ⇒ Object
- .ctime(file) ⇒ Object
- .digest_url(url, options = {}) ⇒ Object
- .directory?(file) ⇒ Boolean
- .download(url, file) ⇒ Object
- .exist_or_link?(file) ⇒ Boolean
- .exists?(file) ⇒ Boolean (also: exist?)
- .file_open(file, grep = false, mode = 'r', invert_grep = false, fixed_grep = true, options = {}) ⇒ Object
- .file_write(file, content, mode = 'w') ⇒ Object
- .get_stream(file, mode = 'r', options = {}) ⇒ Object
- .grep(stream, grep, invert = false, fixed = nil, options = {}) ⇒ Object
- .gunzip(stream) ⇒ Object
- .gzip(stream) ⇒ Object
-
.gzip?(file) ⇒ Boolean
Questions.
- .gzip_pipe(file) ⇒ Object
- .has_stream?(obj) ⇒ Boolean
- .in_cache(url, options = {}) ⇒ Object
- .init_lock ⇒ Object
- .is_stream?(obj) ⇒ Boolean
- .json(file) ⇒ Object
- .link(source, target, options = {}) ⇒ Object
- .link_dir(source, target) ⇒ Object
- .list(file) ⇒ Object
- .ln(source, target, options = {}) ⇒ Object
- .ln_h(source, target, options = {}) ⇒ Object
- .ln_s(source, target, options = {}) ⇒ Object
- .lock(file, unlock = true, options = {}) ⇒ Object
- .marshal(file) ⇒ Object
- .mkdir(target) ⇒ Object
- .mtime(file) ⇒ Object
- .mv(source, target, options = {}) ⇒ Object
- .notify_write(file) ⇒ Object
- .open(file, *args, **kwargs, &block) ⇒ Object
- .open_cache(url, options = {}) ⇒ Object
- .open_pipe(do_fork = false, close = true) ⇒ Object
- .pipe ⇒ Object
- .purge_pipes(*save) ⇒ Object
- .read(file, options = {}, &block) ⇒ Object
- .read_stream(stream, size) ⇒ Object
- .realpath(file) ⇒ Object
- .release_pipes(*pipes) ⇒ Object
- .remote?(file) ⇒ Boolean
- .remove_from_cache(url, options = {}) ⇒ Object
- .rm(file) ⇒ Object
- .rm_rf(file) ⇒ Object
- .scp(source_file, target_file, target: nil, source: nil) ⇒ Object
- .sensible_write(path, content = nil, options = {}, &block) ⇒ Object
- .sort_stream(stream, header_hash: "#", cmd_args: "-u", memory: false) ⇒ Object
- .ssh(file, options = {}) ⇒ Object
- .ssh?(file) ⇒ Boolean
- .tee_stream(stream) ⇒ Object
- .tee_stream_thread(stream) ⇒ Object
- .tee_stream_thread_multiple(stream, num = 2) ⇒ Object
- .touch(file) ⇒ Object
- .unzip(stream) ⇒ Object
- .wget(url, options = {}) ⇒ Object
- .with_fifo(path = nil, clean = true, &block) ⇒ Object
- .writable?(path) ⇒ Boolean
- .write(file, content = nil, options = {}) ⇒ Object
- .yaml(file) ⇒ Object
- .zip?(file) ⇒ Boolean
Class Attribute Details
.remote_cache_dir ⇒ Object
Returns the value of attribute remote_cache_dir.
7 8 9 |
# File 'lib/scout/open/remote.rb', line 7 def remote_cache_dir @remote_cache_dir end |
.sensible_write_dir ⇒ Object
Returns the value of attribute sensible_write_dir.
13 14 15 |
# File 'lib/scout/open/stream.rb', line 13 def sensible_write_dir @sensible_write_dir end |
.sensible_write_lock_dir ⇒ Object
Returns the value of attribute sensible_write_lock_dir.
5 6 7 |
# File 'lib/scout/open/stream.rb', line 5 def sensible_write_lock_dir @sensible_write_lock_dir end |
Class Method Details
._just_open ⇒ Object
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/scout/resource/open.rb', line 2 def self.open(file, = {}) if IO === file || StringIO === file if block_given? res = yield file, file.close return res else return file end end = IndiferentHash.add_defaults , :noz => false, :mode => 'r' mode = IndiferentHash. , :mode [:noz] = true if mode.include? "w" io = file_open(file, [:grep], mode, [:invert_grep], [:fixed_grep], ) io = unzip(io) if ((String === file and zip?(file)) and not [:noz]) or [:zip] io = gunzip(io) if ((String === file and gzip?(file)) and not [:noz]) or [:gzip] io = bgunzip(io) if ((String === file and bgzip?(file)) and not [:noz]) or [:bgzip] io.extend NamedStream io.filename = file if block_given? res = nil begin res = yield(io) rescue DontClose res = $!.payload rescue Exception io.abort $! if io.respond_to? :abort io.join if io.respond_to? :join raise $! ensure io.close if io.respond_to? :close and not io.closed? io.join if io.respond_to? :join end res else io end end |
.add_cache(url, data, options = {}) ⇒ Object
125 126 127 128 |
# File 'lib/scout/open/remote.rb', line 125 def self.add_cache(url, data, = {}) filename = cache_file(url, ) Open.sensible_write(filename, data, :force => true) end |
.bgunzip(stream) ⇒ Object
33 34 35 |
# File 'lib/scout/open/util.rb', line 33 def self.bgunzip(stream) Bgzf.setup stream end |
.bgzip(stream) ⇒ Object
45 46 47 |
# File 'lib/scout/open/util.rb', line 45 def self.bgzip(stream) CMD.cmd('bgzip', :in => stream, :pipe => true, :no_fail => true, :no_wait => true) end |
.bgzip?(file) ⇒ Boolean
61 62 63 64 |
# File 'lib/scout/open/util.rb', line 61 def self.bgzip?(file) file = file.find if Path === file !! (file =~ /\.bgz$/) end |
.broken_link?(path) ⇒ Boolean
102 103 104 |
# File 'lib/scout/open/util.rb', line 102 def self.broken_link?(path) File.symlink?(path) && ! File.exist?(File.readlink(path)) end |
.cache_file(url, options) ⇒ Object
103 104 105 |
# File 'lib/scout/open/remote.rb', line 103 def self.cache_file(url, ) File.join(self.remote_cache_dir, digest_url(url, )) end |
.collapse_stream(s, line: nil, sep: "\t", header: nil, compact: false, &block) ⇒ Object
def self.sort_stream(stream, header_hash = “#”, cmd_args = “-u”)
StringIO.new stream.read.split("\n").sort.uniq * "\n"
end
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'lib/scout/open/stream.rb', line 443 def self.collapse_stream(s, line: nil, sep: "\t", header: nil, compact: false, &block) sep ||= "\t" Open.open_pipe do |sin| sin.puts header if header line ||= s.gets current_parts = [] while line key, *parts = line.chomp.split(sep, -1) case when key.nil? when current_parts.nil? current_parts = parts current_key = key when current_key == key parts.each_with_index do |part,i| next if compact and part.nil? || part.empty? if current_parts[i].nil? || current_parts[i].empty? if compact current_parts[i] = part.dup else current_parts[i] = "|" << part end else current_parts[i] = current_parts[i] << "|" << part end end (parts.length..current_parts.length-1).to_a.each do |pos| current_parts[pos] = current_parts[pos] << "|" << "" end when current_key.nil? current_key = key current_parts = parts when current_key != key if block_given? res = block.call(current_parts) sin.puts [current_key, res] * sep else sin.puts [current_key, current_parts].flatten * sep end current_key = key current_parts = parts end line = s.gets end if block_given? res = block.call(current_parts) sin.puts [current_key, res] * sep else sin.puts [current_key, current_parts].flatten * sep end unless current_key.nil? end end |
.consume_stream(io, in_thread = false, into = nil, into_close = true, &block) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/scout/open/stream.rb', line 19 def self.consume_stream(io, in_thread = false, into = nil, into_close = true, &block) return if Path === io return unless io.respond_to? :read if io.respond_to? :closed? and io.closed? io.join if io.respond_to? :join return end if in_thread consumer_thread = Thread.new(Thread.current) do |parent| Thread.current["name"] = "Consumer #{Log.fingerprint io}" Thread.current.report_on_exception = false consume_stream(io, false, into, into_close) end io.threads.push(consumer_thread) if io.respond_to?(:threads) Thread.pass until consumer_thread["name"] consumer_thread else if into Log.low "Consuming stream #{Log.fingerprint io} -> #{Log.fingerprint into}" else Log.low "Consuming stream #{Log.fingerprint io}" end begin into = into.find if Path === into if String === into dir = File.dirname(into) Open.mkdir dir unless File.exist?(dir) into_path, into = into, File.open(into, 'w') end into_close = false unless into.respond_to? :close while c = io.read(BLOCK_SIZE) into << c if into last_c = c if c break if io.closed? end io.join if io.respond_to? :join io.close unless io.closed? into.join if into and into_close and into.respond_to?(:joined?) and not into.joined? into.close if into and into_close and not into.closed? block.call if block_given? last_c rescue Aborted Thread.current["exception"] = true Log.low "Consume stream Aborted #{Log.fingerprint io} into #{into_path || into}" io.abort $! if io.respond_to? :abort into.close if into.respond_to?(:closed?) && ! into.closed? FileUtils.rm into_path if into_path and File.exist?(into_path) rescue Exception Thread.current["exception"] = true Log.low "Consume stream Exception reading #{Log.fingerprint io} into #{into_path || into} - #{$!.}" exception = (io.respond_to?(:stream_exception) && io.stream_exception) ? io.stream_exception : $! io.abort exception if io.respond_to? :abort into.close if into.respond_to?(:closed?) && ! into.closed? into_path = into if into_path.nil? && String === into if into_path and File.exist?(into_path) FileUtils.rm into_path end raise exception end end end |
.cp(source, target, options = {}) ⇒ Object
189 190 191 192 193 194 195 196 |
# File 'lib/scout/open/util.rb', line 189 def self.cp(source, target, = {}) source = source.find if Path === source target = target.find if Path === target FileUtils.mkdir_p File.dirname(target) unless File.exist?(File.dirname(target)) FileUtils.rm_rf target if File.exist?(target) FileUtils.cp_r source, target end |
.ctime(file) ⇒ Object
161 162 163 164 |
# File 'lib/scout/open/util.rb', line 161 def self.ctime(file) file = file.find if Path === file File.ctime(file) end |
.digest_url(url, options = {}) ⇒ Object
98 99 100 101 |
# File 'lib/scout/open/remote.rb', line 98 def self.digest_url(url, = {}) params = [url, .values_at("--post-data", "--post-data="), (.include?("--post-file")? Open.read(["--post-file"]).split("\n").sort * "\n" : "")] Misc.digest([url, params]) end |
.directory?(file) ⇒ Boolean
106 107 108 109 |
# File 'lib/scout/open/util.rb', line 106 def self.directory?(file) file = file.find if Path === file File.directory?(file) end |
.download(url, file) ⇒ Object
89 90 91 92 93 94 95 96 |
# File 'lib/scout/open/remote.rb', line 89 def self.download(url, file) begin CMD.cmd_log(:wget, "'#{url}' -O '#{file}'") rescue FileUtils.rm(file) if File.exist?(file) raise $! end end |
.exist_or_link?(file) ⇒ Boolean
117 118 119 |
# File 'lib/scout/open/util.rb', line 117 def self.exist_or_link?(file) self.exists?(file) || File.symlink?(file) end |
.exists?(file) ⇒ Boolean Also known as: exist?
111 112 113 114 |
# File 'lib/scout/open/util.rb', line 111 def self.exists?(file) file = file.find if Path === file File.exist?(file) end |
.file_open(file, grep = false, mode = 'r', invert_grep = false, fixed_grep = true, options = {}) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/scout/open.rb', line 34 def self.file_open(file, grep = false, mode = 'r', invert_grep = false, fixed_grep = true, = {}) Open.mkdir File.dirname(file) if mode.include? 'w' stream = get_stream(file, mode, ) if grep grep(stream, grep, invert_grep, fixed_grep) else stream end end |
.file_write(file, content, mode = 'w') ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/scout/open.rb', line 46 def self.file_write(file, content, mode = 'w') File.open(file, mode) do |f| begin f.flock(File::LOCK_EX) f.write content f.flock(File::LOCK_UN) ensure f.close unless f.closed? end end end |
.get_stream(file, mode = 'r', options = {}) ⇒ Object
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/scout/open.rb', line 23 def self.get_stream(file, mode = 'r', = {}) return file if Open.is_stream?(file) return file.stream if Open.has_stream?(file) file = file.find if Path === file return Open.ssh(file, ) if Open.ssh?(file) return Open.wget(file, ) if Open.remote?(file) File.open(file, mode) end |
.grep(stream, grep, invert = false, fixed = nil, options = {}) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/scout/open/util.rb', line 14 def self.grep(stream, grep, invert = false, fixed = nil, = {}) case when Array === grep TmpFile.with_file(grep * "\n", false) do |f| if FalseClass === fixed CMD.cmd("#{GREP_CMD} #{invert ? '-v' : ''} -", "-f" => f, :in => stream, :pipe => true, :post => proc{FileUtils.rm f}) else CMD.cmd("#{GREP_CMD} #{invert ? '-v' : ''} -", "-w" => true, "-F" => true, "-f" => f, :in => stream, :pipe => true, :post => proc{FileUtils.rm f}) end end else CMD.cmd("#{GREP_CMD} #{invert ? '-v ' : ''} '#{grep}' -", :in => stream, :nofail => true, :pipe => true, :post => proc{begin stream.force_close; rescue Exception; end if stream.respond_to?(:force_close)}) end end |
.gunzip(stream) ⇒ Object
37 38 39 |
# File 'lib/scout/open/util.rb', line 37 def self.gunzip(stream) CMD.cmd('zcat', :in => stream, :pipe => true, :no_fail => true, :no_wait => true) end |
.gzip(stream) ⇒ Object
41 42 43 |
# File 'lib/scout/open/util.rb', line 41 def self.gzip(stream) CMD.cmd('gzip', :in => stream, :pipe => true, :no_fail => true, :no_wait => true) end |
.gzip?(file) ⇒ Boolean
Questions
56 57 58 59 |
# File 'lib/scout/open/util.rb', line 56 def self.gzip?(file) file = file.find if Path === file !! (file =~ /\.gz$/) end |
.gzip_pipe(file) ⇒ Object
29 30 31 |
# File 'lib/scout/open/util.rb', line 29 def self.gzip_pipe(file) Open.gzip?(file) ? "<(gunzip -c '#{file}')" : "'#{file}'" end |
.has_stream?(obj) ⇒ Boolean
75 76 77 |
# File 'lib/scout/open/util.rb', line 75 def self.has_stream?(obj) obj.respond_to?(:stream) end |
.in_cache(url, options = {}) ⇒ Object
107 108 109 110 111 112 113 114 |
# File 'lib/scout/open/remote.rb', line 107 def self.in_cache(url, = {}) filename = cache_file(url, ) if File.exist? filename return filename else nil end end |
.init_lock ⇒ Object
7 8 9 10 11 |
# File 'lib/scout/open/lock.rb', line 7 def self.init_lock Lockfile.refresh = 2 Lockfile.max_age = 30 Lockfile.suspend = 4 end |
.is_stream?(obj) ⇒ Boolean
71 72 73 |
# File 'lib/scout/open/util.rb', line 71 def self.is_stream?(obj) IO === obj || StringIO === obj end |
.json(file) ⇒ Object
6 7 8 |
# File 'lib/scout/persist/open.rb', line 6 def self.json(file) Open.open(file){|f| JSON.load(f) } end |
.link(source, target, options = {}) ⇒ Object
235 236 237 238 239 240 241 242 243 |
# File 'lib/scout/open/util.rb', line 235 def self.link(source, target, = {}) begin Open.ln(source, target, ) rescue Log.debug "Could not make regular link, trying symbolic: #{Misc.fingerprint(source)} -> #{Misc.fingerprint(target)}" Open.ln_s(source, target, ) end nil end |
.link_dir(source, target) ⇒ Object
245 246 247 248 |
# File 'lib/scout/open/util.rb', line 245 def self.link_dir(source, target) Log.debug "Copy with hard-links #{Log.fingerprint source}->#{Log.fingerprint target}" FileUtils.cp_lr(source, target) end |
.list(file) ⇒ Object
250 251 252 253 |
# File 'lib/scout/open/util.rb', line 250 def self.list(file) file = file.produce_and_find if Path === file Open.read(file).split("\n") end |
.ln(source, target, options = {}) ⇒ Object
210 211 212 213 214 215 216 217 218 219 |
# File 'lib/scout/open/util.rb', line 210 def self.ln(source, target, = {}) source = source.find if Path === source target = target.find if Path === target source = File.realpath(source) if File.symlink?(source) FileUtils.mkdir_p File.dirname(target) unless File.exist?(File.dirname(target)) FileUtils.rm target if File.exist?(target) FileUtils.rm target if File.symlink?(target) FileUtils.ln source, target end |
.ln_h(source, target, options = {}) ⇒ Object
221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/scout/open/util.rb', line 221 def self.ln_h(source, target, = {}) source = source.find if Path === source target = target.find if Path === target FileUtils.mkdir_p File.dirname(target) unless File.exist?(File.dirname(target)) FileUtils.rm target if File.exist?(target) begin CMD.cmd("ln -L '#{ source }' '#{ target }'") rescue ProcessFailed Log.debug "Could not hard link #{source} and #{target}: #{$!..gsub("\n", '. ')}" CMD.cmd("cp -L '#{ source }' '#{ target }'") end end |
.ln_s(source, target, options = {}) ⇒ Object
199 200 201 202 203 204 205 206 207 208 |
# File 'lib/scout/open/util.rb', line 199 def self.ln_s(source, target, = {}) source = source.find if Path === source target = target.find if Path === target target = File.join(target, File.basename(source)) if File.directory? target FileUtils.mkdir_p File.dirname(target) unless File.exist?(File.dirname(target)) FileUtils.rm target if File.exist?(target) FileUtils.rm target if File.symlink?(target) FileUtils.ln_s source, target end |
.lock(file, unlock = true, options = {}) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/scout/open/lock.rb', line 15 def self.lock(file, unlock = true, = {}) unlock, = true, unlock if Hash === unlock return yield if file.nil? and not Lockfile === [:lock] if Lockfile === file lockfile = file else file = file.find if Path === file FileUtils.mkdir_p File.dirname(File.(file)) unless File.exist? File.dirname(File.(file)) case [:lock] when Lockfile lockfile = [:lock] when FalseClass lockfile = nil unlock = false when Path, String lock_path = [:lock].find lockfile = Lockfile.new(lock_path, ) else lock_path = File.(file + '.lock') lockfile = Lockfile.new(lock_path, ) end end begin lockfile.lock unless lockfile.nil? || lockfile.locked? rescue Aborted, Interrupt raise LockInterrupted end res = nil begin res = yield lockfile rescue KeepLocked unlock = false res = $!.payload ensure if unlock begin if lockfile.locked? lockfile.unlock end rescue Exception Log.warn "Exception unlocking: #{lockfile.path}" Log.exception $! end end end res end |
.marshal(file) ⇒ Object
14 15 16 |
# File 'lib/scout/persist/open.rb', line 14 def self.marshal(file) Open.open(file){|f| Marshal.load(f) } end |
.mkdir(target) ⇒ Object
143 144 145 146 147 148 |
# File 'lib/scout/open/util.rb', line 143 def self.mkdir(target) target = target.find if Path === target if ! File.exist?(target) FileUtils.mkdir_p target end end |
.mtime(file) ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/scout/open/util.rb', line 171 def self.mtime(file) file = file.find if Path === file begin if File.symlink?(file) || File.stat(file).nlink > 1 if File.exist?(file + '.info') && defined?(Step) done = Persist.load(file + '.info', Step::SERIALIZER)[:done] return done if done end file = Pathname.new(file).realpath.to_s end return nil unless File.exist?(file) File.mtime(file) rescue nil end end |
.mv(source, target, options = {}) ⇒ Object
121 122 123 124 125 126 127 128 129 |
# File 'lib/scout/open/util.rb', line 121 def self.mv(source, target, = {}) target = target.find if Path === target source = source.find if Path === source FileUtils.mkdir_p File.dirname(target) unless File.exist?(File.dirname(target)) tmp_target = File.join(File.dirname(target), '.tmp_mv.' + File.basename(target)) FileUtils.mv source, tmp_target FileUtils.mv tmp_target, target return nil end |
.notify_write(file) ⇒ Object
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/scout/open/util.rb', line 80 def self.notify_write(file) begin notification_file = file + '.notify' if Open.exists? notification_file key = Open.read(notification_file).strip key = nil if key.empty? if key && key.include?("@") to = from = key subject = "Wrote " << file = "Content attached" Misc.send_email(from, to, subject, , :files => [file]) else Misc.notify("Wrote " << file, nil, key) end Open.rm notification_file end rescue Log.exception $! Log.warn "Error notifying write of #{ file }" end end |
.open(file, *args, **kwargs, &block) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
# File 'lib/scout/open.rb', line 58 def self.open(file, = {}) if IO === file || StringIO === file if block_given? res = yield file, file.close return res else return file end end = IndiferentHash.add_defaults , :noz => false, :mode => 'r' mode = IndiferentHash. , :mode [:noz] = true if mode.include? "w" io = file_open(file, [:grep], mode, [:invert_grep], [:fixed_grep], ) io = unzip(io) if ((String === file and zip?(file)) and not [:noz]) or [:zip] io = gunzip(io) if ((String === file and gzip?(file)) and not [:noz]) or [:gzip] io = bgunzip(io) if ((String === file and bgzip?(file)) and not [:noz]) or [:bgzip] io.extend NamedStream io.filename = file if block_given? res = nil begin res = yield(io) rescue DontClose res = $!.payload rescue Exception io.abort $! if io.respond_to? :abort io.join if io.respond_to? :join raise $! ensure io.close if io.respond_to? :close and not io.closed? io.join if io.respond_to? :join end res else io end end |
.open_cache(url, options = {}) ⇒ Object
130 131 132 133 |
# File 'lib/scout/open/remote.rb', line 130 def self.open_cache(url, = {}) filename = cache_file(url, ) Open.open(filename) end |
.open_pipe(do_fork = false, close = true) ⇒ Object
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
# File 'lib/scout/open/stream.rb', line 214 def self.open_pipe(do_fork = false, close = true) raise "No block given" unless block_given? sout, sin = Open.pipe if do_fork pid = Process.fork { begin purge_pipes(sin) sout.close yield sin sin.close if close and not sin.closed? rescue Exception Log.exception $! Kernel.exit!(-1) end Kernel.exit! 0 } sin.close ConcurrentStream.setup sout, :pids => [pid] else ConcurrentStream.setup sin, :pair => sout ConcurrentStream.setup sout, :pair => sin thread = Thread.new do begin ConcurrentStream.process_stream(sin, :message => "Open pipe") do Thread.current.report_on_exception = false Thread.current["name"] = "Pipe input #{Log.fingerprint sin} => #{Log.fingerprint sout}" yield sin end end end sin.threads = [thread] sout.threads = [thread] Thread.pass until thread["name"] end sout end |
.pipe ⇒ Object
173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/scout/open/stream.rb', line 173 def self.pipe OPEN_PIPE_IN.delete_if{|pipe| pipe.closed? } res = PIPE_MUTEX.synchronize do sout, sin = IO.pipe OPEN_PIPE_IN << sin [sout, sin] end Log.low{"Creating pipe #{[Log.fingerprint(res.last), Log.fingerprint(res.first)] * " -> "}"} res end |
.purge_pipes(*save) ⇒ Object
205 206 207 208 209 210 211 212 |
# File 'lib/scout/open/stream.rb', line 205 def self.purge_pipes(*save) PIPE_MUTEX.synchronize do OPEN_PIPE_IN.each do |pipe| next if save.include? pipe pipe.close unless pipe.closed? end end end |
.read(file, options = {}, &block) ⇒ Object
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
# File 'lib/scout/open.rb', line 104 def self.read(file, = {}, &block) open(file, ) do |f| if block_given? res = [] while not f.eof? l = f.gets l = Misc.fixutf8(l) unless [:nofix] res << yield(l) end res else if [:nofix] f.read else Misc.fixutf8(f.read) end end end end |
.read_stream(stream, size) ⇒ Object
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/scout/open/stream.rb', line 381 def self.read_stream(stream, size) str = nil Thread.pass while IO.select([stream],nil,nil,1).nil? while not str = stream.read(size) IO.select([stream],nil,nil,1) Thread.pass raise ClosedStream if stream.eof? end while str.length < size raise ClosedStream if stream.eof? IO.select([stream],nil,nil,1) if new = stream.read(size-str.length) str << new end end str end |
.realpath(file) ⇒ Object
166 167 168 169 |
# File 'lib/scout/open/util.rb', line 166 def self.realpath(file) file = file.find if Path === file Pathname.new(File.(file)).realpath.to_s end |
.release_pipes(*pipes) ⇒ Object
197 198 199 200 201 202 203 |
# File 'lib/scout/open/stream.rb', line 197 def self.release_pipes(*pipes) PIPE_MUTEX.synchronize do pipes.flatten.each do |pipe| pipe.close unless pipe.closed? end end end |
.remote?(file) ⇒ Boolean
14 15 16 |
# File 'lib/scout/open/remote.rb', line 14 def self.remote?(file) !! (file =~ /^(?:https?|ftp|ssh):\/\//) end |
.remove_from_cache(url, options = {}) ⇒ Object
116 117 118 119 120 121 122 123 |
# File 'lib/scout/open/remote.rb', line 116 def self.remove_from_cache(url, = {}) filename = cache_file(url, ) if File.exist? filename FileUtils.rm filename else nil end end |
.rm(file) ⇒ Object
131 132 133 |
# File 'lib/scout/open/util.rb', line 131 def self.rm(file) FileUtils.rm(file) if File.exist?(file) || Open.broken_link?(file) end |
.rm_rf(file) ⇒ Object
135 136 137 |
# File 'lib/scout/open/util.rb', line 135 def self.rm_rf(file) FileUtils.rm_rf(file) end |
.scp(source_file, target_file, target: nil, source: nil) ⇒ Object
135 136 137 138 139 140 |
# File 'lib/scout/open/remote.rb', line 135 def self.scp(source_file, target_file, target: nil, source: nil) CMD.cmd_log("ssh #{target} mkdir -p #{File.dirname(target_file)}") target_file = [target, target_file] * ":" if target && ! target_file.start_with?(target+":") source_file = [source, source_file] * ":" if source && ! source_file.start_with?(source+":") CMD.cmd_log("scp -r '#{ source_file }' #{target_file}") end |
.sensible_write(path, content = nil, options = {}, &block) ⇒ Object
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/scout/open/stream.rb', line 91 def self.sensible_write(path, content = nil, = {}, &block) force = IndiferentHash. , :force if File.exist?(path) and not force Open.consume_stream content return end = IndiferentHash.pull_keys .dup, :lock = [:lock] if Hash === [:lock] tmp_path = TmpFile.tmp_for_file(path, {:dir => Open.sensible_write_dir}) tmp_path_lock = TmpFile.tmp_for_file(path, {:dir => Open.sensible_write_lock_dir}) tmp_path_lock = nil if FalseClass === [:lock] Open.lock tmp_path_lock, do if File.exist? path and not force Log.warn "Path exists in sensible_write, not forcing update: #{ path }" Open.consume_stream content else FileUtils.mkdir_p File.dirname(tmp_path) unless File.directory?(File.dirname(tmp_path)) FileUtils.rm_f tmp_path if File.exist? tmp_path Log.low "Sensible write stream #{Log.fingerprint content} -> #{Log.fingerprint path}" if IO === content begin case when block_given? File.open(tmp_path, 'wb', &block) when String === content File.open(tmp_path, 'wb') do |f| f.write content end when (IO === content or StringIO === content or File === content) Open.write(tmp_path) do |f| while block = content.read(BLOCK_SIZE) f.write block break if content.closed? end end else if content.respond_to?(:write_file) content.write_file(tmp_path) else File.open(tmp_path, 'wb') do |f| f.write content.to_s end end end begin Misc.insist do Open.mv tmp_path, path, end rescue Exception raise $! unless File.exist? path end Open.touch path if File.exist? path content.join if content.respond_to?(:join) and not Path === content and not (content.respond_to?(:joined?) && content.joined?) Open.notify_write(path) rescue Aborted Log.low "Aborted sensible_write -- #{ Log.reset << path }" content.abort if content.respond_to? :abort Open.rm path if File.exist? path rescue Exception exception = (AbortedStream === content and content.exception) ? content.exception : $! Log.low "Exception in sensible_write: [#{Process.pid}] #{exception.} -- #{ path }" content.abort(exception) if content.respond_to? :abort Open.rm path if File.exist? path raise exception rescue raise $! ensure FileUtils.rm_f tmp_path if File.exist? tmp_path if Lockfile === [:lock] and [:lock].locked? [:lock].unlock end end end end end |
.sort_stream(stream, header_hash: "#", cmd_args: "-u", memory: false) ⇒ Object
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/scout/open/stream.rb', line 410 def self.sort_stream(stream, header_hash: "#", cmd_args: "-u", memory: false) sout = Open.open_pipe do |sin| ConcurrentStream.process_stream(stream) do line = stream.gets while line && line.start_with?(header_hash) do sin.puts line line = stream.gets end line_stream = Open.open_pipe do |line_stream_in| line_stream_in.puts line if line Open.consume_stream(stream, false, line_stream_in) end Log.low "Sub-sort stream #{Log.fingerprint stream} -> #{Log.fingerprint line_stream}" if memory line_stream.read.split("\n").sort.each do |line| sin.puts line end else io = CMD.cmd("env LC_ALL=C sort #{cmd_args || ""}", :in => line_stream, :pipe => true) Open.consume_stream(io, false, sin) end end end Log.low "Sort #{Log.fingerprint stream} -> #{Log.fingerprint sout}" sout end |
.ssh(file, options = {}) ⇒ Object
22 23 24 25 26 27 28 29 30 31 |
# File 'lib/scout/open/remote.rb', line 22 def self.ssh(file, = {}) m = file.match(/ssh:\/\/([^:]+):(.*)/) server = m[1] file = m[2] if server == 'localhost' Open.open(file) else CMD.cmd("ssh '#{server}' cat '#{file}'", :pipe => true, :autojoin => true) end end |
.ssh?(file) ⇒ Boolean
18 19 20 |
# File 'lib/scout/open/remote.rb', line 18 def self.ssh?(file) !! (file =~ /^ssh:\/\//) end |
.tee_stream(stream) ⇒ Object
377 378 379 |
# File 'lib/scout/open/stream.rb', line 377 def self.tee_stream(stream) tee_stream_thread(stream) end |
.tee_stream_thread(stream) ⇒ Object
373 374 375 |
# File 'lib/scout/open/stream.rb', line 373 def self.tee_stream_thread(stream) tee_stream_thread_multiple(stream, 2) end |
.tee_stream_thread_multiple(stream, num = 2) ⇒ Object
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
# File 'lib/scout/open/stream.rb', line 263 def self.tee_stream_thread_multiple(stream, num = 2) in_pipes = [] out_pipes = [] num.times do sout, sin = Open.pipe in_pipes << sin out_pipes << sout end Log.low("Tee stream #{Log.fingerprint stream} -> #{Log.fingerprint out_pipes}") filename = stream.filename if stream.respond_to? :filename splitter_thread = Thread.new(Thread.current) do |parent| begin Thread.current.report_on_exception = false Thread.current["name"] = "Splitter #{Log.fingerprint stream}" skip = [false] * num while block = stream.read(BLOCK_SIZE) in_pipes.each_with_index do |sin,i| begin sin.write block rescue IOError Log.warn("Tee stream #{i} #{Log.fingerprint stream} IOError: #{$!.} (#{Log.fingerprint sin})"); skip[i] = true rescue Log.warn("Tee stream #{i} #{Log.fingerprint stream} Exception: #{$!.} (#{Log.fingerprint sin})"); raise $! end unless skip[i] end break if stream.closed? end stream.join if stream.respond_to? :join in_pipes.first.close unless in_pipes.first.closed? rescue Aborted, Interrupt stream.abort if stream.respond_to?(:abort) && ! stream.aborted? out_pipes.reverse.each do |sout| sout.threads.delete(Thread.current) begin sout.abort($!) if sout.respond_to?(:abort) && ! sout.aborted? rescue end end in_pipes.each do |sin| sin.close unless sin.closed? end Log.low "Tee aborting #{Log.fingerprint stream}" raise $! rescue Exception begin stream.abort($!) if stream.respond_to?(:abort) && ! stream.aborted? out_pipes.reverse.each do |sout| sout.threads.delete(Thread.current) begin sout.abort($!) if sout.respond_to?(:abort) && ! sout.aborted? rescue end end in_pipes.each do |sin| sin.close unless sin.closed? end Log.low "Tee exception #{Log.fingerprint stream}" rescue ensure begin in_pipes.each do |sin| sin.close unless sin.closed? end ensure raise $! end end end end Thread.pass until splitter_thread["name"] main_pipe = out_pipes.first ConcurrentStream.setup(main_pipe, :threads => [splitter_thread], :filename => filename, :autojoin => true) out_pipes[1..-1].each do |sout| ConcurrentStream.setup sout, :filename => filename, :threads => [splitter_thread] end main_pipe.callback = proc do begin stream.join if stream.respond_to?(:join) && ! stream.joined? in_pipes[1..-1].each do |sin| sin.close unless sin.closed? end rescue main_pipe.abort_callback.call($!) raise $! end end main_pipe.abort_callback = proc do |exception| stream.abort(exception) out_pipes[1..-1].each do |sout| sout.abort(exception) end end out_pipes end |
.touch(file) ⇒ Object
139 140 141 |
# File 'lib/scout/open/util.rb', line 139 def self.touch(file) FileUtils.touch(file) end |
.unzip(stream) ⇒ Object
49 50 51 52 53 |
# File 'lib/scout/open/util.rb', line 49 def self.unzip(stream) TmpFile.with_file(stream.read) do |filename| StringIO.new(CMD.cmd("unzip '{opt}' #{filename}", "-p" => true, :pipe => true).read) end end |
.wget(url, options = {}) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/scout/open/remote.rb', line 33 def self.wget(url, = {}) = [:wget_options] if .include?(:wget_options) if ! ([:force] || [:nocache]) && cache_file = in_cache(url, ) return file_open(cache_file) end Log.low "WGET:\n -URL: #{ url }\n -OPTIONS: #{.inspect}" = IndiferentHash.add_defaults , "--user-agent=" => 'rbbt', :pipe => true, :autojoin => true wait([:nice], [:nice_key]) if [:nice] .delete(:nice) .delete(:nice_key) pipe = .delete(:pipe) quiet = .delete(:quiet) post = .delete(:post) = .delete(:cookies) nocache = .delete(:nocache) ["--quiet"] = quiet if ["--quiet"].nil? ["--post-data="] ||= post if post if ["--save-cookies"] = ["--load-cookies"] = ["--keep-session-cookies"] = true end stderr = case when ['stderr'] ['stderr'] when ['--quiet'] false else nil end begin = .dup = .merge( '-O' => '-') unless .include?('--output-document') [:pipe] = pipe unless pipe.nil? [:stderr] = stderr unless stderr.nil? io = CMD.cmd("wget '#{ url }'", ) if nocache && nocache.to_s != 'update' io else add_cache(url, io, ) open_cache(url, ) end rescue STDERR.puts $!.backtrace.inspect raise OpenURLError, "Error reading remote url: #{ url }.\n#{$!.}" end end |
.with_fifo(path = nil, clean = true, &block) ⇒ Object
185 186 187 188 189 190 191 192 193 194 195 |
# File 'lib/scout/open/stream.rb', line 185 def self.with_fifo(path = nil, clean = true, &block) begin erase = path.nil? path = TmpFile.tmp_file if path.nil? File.rm path if clean && File.exist?(path) File.mkfifo path yield path ensure FileUtils.rm path if erase && File.exist?(path) end end |
.writable?(path) ⇒ Boolean
150 151 152 153 154 155 156 157 158 159 |
# File 'lib/scout/open/util.rb', line 150 def self.writable?(path) path = path.find if Path === path if File.symlink?(path) File.writable?(File.dirname(path)) elsif File.exist?(path) File.writable?(path) else File.writable?(File.dirname(File.(path))) end end |
.write(file, content = nil, options = {}) ⇒ Object
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/scout/open.rb', line 124 def self.write(file, content = nil, = {}) = IndiferentHash.add_defaults , :mode => 'w' file = file.find([:where]) if Path === file mode = IndiferentHash. , :mode FileUtils.mkdir_p File.dirname(file) case when block_given? begin f = File.open(file, mode) begin yield f ensure f.close unless f.closed? end rescue Exception FileUtils.rm file if File.exist? file raise $! end when content.nil? file_write(file, "", mode) when String === content file_write(file, content, mode) when (IO === content || StringIO === content) begin File.open(file, mode) do |f| f.flock(File::LOCK_EX) while block = content.read(Open::BLOCK_SIZE) f.write block end f.flock(File::LOCK_UN) end rescue Exception FileUtils.rm_rf file if File.exist? file raise $! end content.close unless content.closed? content.join if content.respond_to? :join else raise "Content unknown #{Log.fingerprint content}" end notify_write(file) end |
.yaml(file) ⇒ Object
10 11 12 |
# File 'lib/scout/persist/open.rb', line 10 def self.yaml(file) Open.open(file){|f| YAML.unsafe_load(f) } end |
.zip?(file) ⇒ Boolean
66 67 68 69 |
# File 'lib/scout/open/util.rb', line 66 def self.zip?(file) file = file.find if Path === file !! (file =~ /\.zip$/) end |