]> git.cworth.org Git - sup/blob - lib/sup/mbox/ssh-file.rb
c2479a8b1a5b15ba13a6580301887dd68148dcf6
[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 ## sharing a ssh connection to one machines between sources seems to
79 ## create lots of broken situations: commands returning bizarre (large
80 ## positive integer) return codes despite working; commands
81 ## occasionally not working, etc. i suspect this is because of the
82 ## fragile nature of the ssh syncshell. 
83 ##
84 ## at any rate, we now open up one ssh connection per file, which is
85 ## probably silly in the extreme case.
86
87 ## the file-like interface to a remote file
88 class SSHFile
89   MAX_BUF_SIZE = 1024 * 1024 # bytes
90   MAX_TRANSFER_SIZE = 1024 * 128
91   REASONABLE_TRANSFER_SIZE = 1024 * 32
92   SIZE_CHECK_INTERVAL = 60 * 1 # seconds
93
94   def initialize host, fn, ssh_opts={}
95     @buf = Buffer.new
96     @host = host
97     @fn = fn
98     @ssh_opts = ssh_opts
99     @file_size = nil
100     @offset = 0
101     @say_id = nil
102     @broken_msg = nil
103     @shell = nil
104     @shell_mutex = Mutex.new
105   end
106
107   def to_s; "mbox+ssh://#@host/#@fn"; end ## TODO: remove thisis EVILness
108   def broken?; !@broken_msg.nil?; end
109
110   ## TODO: share this code with imap
111   def say s
112     @say_id = BufferManager.say s, @say_id if BufferManager.instantiated?
113     Redwood::log s
114   end
115   def shutup
116     BufferManager.clear @say_id if BufferManager.instantiated?
117     @say_id = nil
118   end
119   private :say, :shutup
120
121   def connect
122     raise SSHFileError, @broken_msg if broken?
123
124     @shell_mutex.synchronize do
125       return if @shell
126
127       begin
128         say "Opening SSH connection to #{@host}..."
129         #raise SSHFileError, "simulated SSH file error"
130         session = Net::SSH.start @host, @ssh_opts
131         say "Starting SSH shell..."
132         @shell = session.shell.sync
133         say "Checking for #@fn..."
134         raise Errno::ENOENT, @fn unless @shell.test("-e #@fn").status == 0
135       ensure
136         shutup
137       end
138     end
139   end
140
141   def eof?; @offset >= size; end
142   def eof; eof?; end # lame but IO's method is named this and rmail calls that
143   def seek loc; @offset = loc; end
144   def tell; @offset; end
145   def total; size; end
146
147   def size
148     if @file_size.nil? || (Time.now - @last_size_check) > SIZE_CHECK_INTERVAL
149       @last_size_check = Time.now
150       @file_size = do_remote("wc -c #@fn").split.first.to_i
151     end
152     @file_size
153   end
154
155   def gets
156     return nil if eof?
157     make_buf_include @offset
158     expand_buf_forward while @buf.index("\n", @offset).nil? && @buf.endd < size
159     returning(@buf[@offset .. (@buf.index("\n", @offset) || -1)]) { |line| @offset += line.length }
160   end
161
162   def read n
163     return nil if eof?
164     make_buf_include @offset, n
165     @buf[@offset ... (@offset += n)]
166   end
167
168 private
169
170   def do_remote cmd, expected_size=0
171     begin
172       retries = 0
173       connect
174       # MBox::debug "sending command: #{cmd.inspect}"
175       begin
176         result = @shell.send_command cmd
177         result = @shell.sync { @shell.send_command cmd }
178         raise SSHFileError, "Failure during remote command #{cmd.inspect}: #{(result.stderr || result.stdout || "")[0 .. 100]}" unless result.status == 0
179       rescue Net::SSH::Exception # these happen occasionally for no apparent reason. gotta love that nondeterminism!
180         retry if (retries += 1) <= 3
181         raise
182       rescue Errno::EPIPE
183         if (retries += 1) <= e
184           @shell = nil
185           connect
186           retry
187         end
188       end
189     rescue Net::SSH::Exception, SSHFileError, Errno::ENOENT => e
190       @broken_msg = e.message
191       raise
192     end
193     result.stdout
194   end
195
196   def get_bytes offset, size
197     do_remote "tail -c +#{offset + 1} #@fn | head -c #{size}", size
198   end
199
200   def expand_buf_forward n=REASONABLE_TRANSFER_SIZE
201     @buf.add get_bytes(@buf.endd, n)
202   end
203
204   ## try our best to transfer somewhere between
205   ## REASONABLE_TRANSFER_SIZE and MAX_TRANSFER_SIZE bytes
206   def make_buf_include offset, size=0
207     good_size = [size, REASONABLE_TRANSFER_SIZE].max
208
209     trans_start, trans_size = 
210       if @buf.empty?
211         [offset, good_size]
212       elsif offset < @buf.start
213         if @buf.start - offset <= good_size
214           start = [@buf.start - good_size, 0].max
215           [start, @buf.start - start]
216         elsif @buf.start - offset < MAX_TRANSFER_SIZE
217           [offset, @buf.start - offset]
218         else
219           MBox::debug "clearing SSH buffer because buf.start #{@buf.start} - offset #{offset} >= #{MAX_TRANSFER_SIZE}"
220           @buf.clear!
221           [offset, good_size]
222         end
223       else
224         return if [offset + size, self.size].min <= @buf.endd # whoohoo!
225         if offset - @buf.endd <= good_size
226           [@buf.endd, good_size]
227         elsif offset - @buf.endd < MAX_TRANSFER_SIZE
228           [@buf.endd, offset - @buf.endd]
229         else
230           MBox::debug "clearing SSH buffer because offset #{offset} - buf.end #{@buf.endd} >= #{MAX_TRANSFER_SIZE}"
231           @buf.clear!
232           [offset, good_size]
233         end
234       end          
235
236     @buf.clear! if @buf.size > MAX_BUF_SIZE
237     @buf.add get_bytes(trans_start, trans_size), trans_start
238   end
239 end
240
241 end
242 end