]> git.cworth.org Git - sup/blob - lib/sup/mbox/ssh-file.rb
many changes (while on the airplane).
[sup] / lib / sup / mbox / ssh-file.rb
1 require 'net/ssh'
2
3 module Redwood
4 module MBox
5
6 class SSHFileError < StandardError; end
7
8 ## this is a file-like interface to a file that actually lives on the
9 ## other end of an ssh connection. it works by using wc, head and tail
10 ## to simulate (buffered) random access. on a fast connection, this
11 ## can have a good bandwidth, but the latency is pretty terrible:
12 ## about 1 second (!) per request.  luckily, we're either just reading
13 ## straight through the mbox (an import) or we're reading a few
14 ## messages at a time (viewing messages) so the latency is not a problem.
15
16 ## all of the methods here can throw SSHFileErrors, SocketErrors,
17 ## Net::SSH::Exceptions and Errno::ENOENTs.
18
19 ## debugging TODO: remove me
20 def debug s
21   Redwood::log s
22 end
23 module_function :debug
24
25 ## a simple buffer of contiguous data
26 class Buffer
27   def initialize
28     clear!
29   end
30
31   def clear!
32     @start = nil
33     @buf = ""
34   end
35
36   def empty?; @start.nil?; end
37   def start; @start; end
38   def endd; @start + @buf.length; end
39
40   def add data, offset=endd
41     #MBox::debug "+ adding #{data.length} bytes; size will be #{size + data.length}; limit #{SSHFile::MAX_BUF_SIZE}"
42
43     if start.nil?
44       @buf = data
45       @start = offset
46       return
47     end
48
49     raise "non-continguous data added to buffer (data #{offset}:#{offset + data.length}, buf range #{start}:#{endd})" if offset + data.length < start || offset > endd
50
51     if offset < start
52       @buf = data[0 ... (start - offset)] + @buf
53       @start = offset
54     else
55       return if offset + data.length < endd
56       @buf += data[(endd - offset) .. -1]
57     end
58   end
59
60   def [](o)
61     raise "only ranges supported due to programmer's laziness" unless o.is_a? Range
62     @buf[Range.new(o.first - @start, o.last - @start, o.exclude_end?)]
63   end
64
65   def index what, start=0
66     x = @buf.index(what, start - @start)
67     x.nil? ? nil : x + @start
68   end
69   def rindex what, start=0
70     x = @buf.rindex(what, start - @start)
71     x.nil? ? nil : x + @start
72   end
73
74   def size; empty? ? 0 : @buf.size; end
75   def to_s; empty? ? "<empty>" : "[#{start}, #{endd})"; end # for debugging
76 end
77
78 ## the file-like interface to a remote file
79 class SSHFile
80   MAX_BUF_SIZE = 1024 * 1024 # bytes
81   MAX_TRANSFER_SIZE = 1024 * 64
82   REASONABLE_TRANSFER_SIZE = 1024 * 32
83   SIZE_CHECK_INTERVAL = 60 * 1 # seconds
84
85   def initialize host, fn, ssh_opts={}
86     @buf = Buffer.new
87     @host = host
88     @fn = fn
89     @ssh_opts = ssh_opts
90     @file_size = nil
91     @offset = 0
92     @say_id = nil
93     @broken_msg = nil
94   end
95
96   def broken?; !@broken_msg.nil?; end
97
98   def say s
99     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
100     Redwood::log s
101   end
102   private :say
103
104   def shutup
105     BufferManager.clear @say_id if BufferManager.instantiated?
106     @say_id = nil
107   end
108
109   def connect
110     return if @session
111     raise SSHFileError, @broken_msg if broken?
112
113     say "Opening SSH connection to #{@host}..."
114
115     begin
116       #raise SSHFileError, "simulated SSH file error"
117       #@session = Net::SSH.start @host, @ssh_opts
118       sleep 3
119       say "Starting SSH shell..."
120       # @shell = @session.shell.sync
121       sleep 3
122       say "Checking for #@fn..."
123       sleep 1
124       raise Errno::ENOENT, @fn
125       raise Errno::ENOENT, @fn unless @shell.test("-e #@fn").status == 0
126     ensure
127       shutup
128     end
129   end
130
131   def eof?; @offset >= size; end
132   def eof; eof?; end # lame but IO's method is named this and rmail calls that
133   def seek loc; @offset = loc; end
134   def tell; @offset; end
135   def total; size; end
136
137   def size
138     if @file_size.nil? || (Time.now - @last_size_check) > SIZE_CHECK_INTERVAL
139       @last_size_check = Time.now
140       @file_size = do_remote("wc -c #@fn").split.first.to_i
141     end
142     @file_size
143   end
144
145   def gets
146     return nil if eof?
147     make_buf_include @offset
148     expand_buf_forward while @buf.index("\n", @offset).nil? && @buf.endd < size
149     returning(@buf[@offset .. (@buf.index("\n", @offset) || -1)]) { |line| @offset += line.length }
150   end
151
152   def read n
153     return nil if eof?
154     make_buf_include @offset, n
155     @buf[@offset ... (@offset += n)]
156   end
157
158 private
159
160   def do_remote cmd, expected_size=0
161     begin
162       retries = 0
163       connect
164       MBox::debug "sending command: #{cmd.inspect}"
165       begin
166         result = @shell.send_command cmd
167         raise SSHFileError, "Failure during remote command #{cmd.inspect}: #{result.stderr[0 .. 100]}" unless result.status == 0
168       rescue Net::SSH::Exception # these happen occasionally for no apparent reason. gotta love that nondeterminism!
169         retry if (retries += 1) < 3
170         raise
171       end
172     rescue Net::SSH::Exception, SSHFileError, Errno::ENOENT => e
173       @broken_msg = e.message
174       raise
175     end
176     result.stdout
177   end
178
179   def get_bytes offset, size
180     do_remote "tail -c +#{offset + 1} #@fn | head -c #{size}", size
181   end
182
183   def expand_buf_forward n=REASONABLE_TRANSFER_SIZE
184     @buf.add get_bytes(@buf.endd, n)
185   end
186
187   ## try our best to transfer somewhere between
188   ## REASONABLE_TRANSFER_SIZE and MAX_TRANSFER_SIZE bytes
189   def make_buf_include offset, size=0
190     good_size = [size, REASONABLE_TRANSFER_SIZE].max
191
192     trans_start, trans_size = 
193       if @buf.empty?
194         [offset, good_size]
195       elsif offset < @buf.start
196         if @buf.start - offset <= good_size
197           start = [@buf.start - good_size, 0].max
198           [start, @buf.start - start]
199         elsif @buf.start - offset < MAX_TRANSFER_SIZE
200           [offset, @buf.start - offset]
201         else
202           MBox::debug "clearing SSH buffer because buf.start #{@buf.start} - offset #{offset} >= #{MAX_TRANSFER_SIZE}"
203           @buf.clear!
204           [offset, good_size]
205         end
206       else
207         return if [offset + size, self.size].min <= @buf.endd # whoohoo!
208         if offset - @buf.endd <= good_size
209           [@buf.endd, good_size]
210         elsif offset - @buf.endd < MAX_TRANSFER_SIZE
211           [@buf.endd, offset - @buf.endd]
212         else
213           MBox::debug "clearing SSH buffer because offset #{offset} - buf.end #{@buf.endd} >= #{MAX_TRANSFER_SIZE}"
214           @buf.clear!
215           [offset, good_size]
216         end
217       end          
218
219     @buf.clear! if @buf.size > MAX_BUF_SIZE
220     @buf.add get_bytes(trans_start, trans_size), trans_start
221   end
222 end
223
224 end
225 end