1 | #!/usr/bin/env python
|
---|
2 | # -*- coding: utf-8 -*-
|
---|
3 |
|
---|
4 | # $URL: baculafs/trunk/baculafs.py $
|
---|
5 | # $Id: baculafs.py 789 2009-08-27 22:01:44Z joergs $
|
---|
6 |
|
---|
7 | import fuse
|
---|
8 | import logging
|
---|
9 | import stat
|
---|
10 | import errno
|
---|
11 | import os
|
---|
12 | import pexpect
|
---|
13 | import sys
|
---|
14 | import re
|
---|
15 |
|
---|
16 | fuse.fuse_python_api = (0, 2)
|
---|
17 |
|
---|
18 | ###### bconsole
|
---|
19 | ################
|
---|
20 |
|
---|
21 | BACULA_FS_VERSION = "$Rev: 789 $"
|
---|
22 |
|
---|
23 | LOG_FILENAME = '/tmp/baculafs.log'
|
---|
24 | LOG_BCONSOLE_DUMP = '/tmp/bconsole.out'
|
---|
25 |
|
---|
26 |
|
---|
27 | #BACULA_CMD = 'strace -f -o /tmp/bconsole.strace /usr/sbin/bconsole -n'
|
---|
28 | BACULA_CMD = '/usr/sbin/bconsole -n'
|
---|
29 |
|
---|
30 | BCONSOLE_CMD_PROMPT='\*'
|
---|
31 | BCONSOLE_SELECT_PROMPT='Select .*:.*'
|
---|
32 | BCONSOLE_RESTORE_PROMPT='\$ '
|
---|
33 |
|
---|
34 | # define the states bconsole can be in
|
---|
35 | class BconsoleState:
|
---|
36 | UNKNOWN = ''
|
---|
37 | CMD_PROMPT = BCONSOLE_CMD_PROMPT
|
---|
38 | SELECT_PROMPT = BCONSOLE_SELECT_PROMPT
|
---|
39 | RESTORE_PROMPT = BCONSOLE_RESTORE_PROMPT
|
---|
40 | ERROR = "error"
|
---|
41 |
|
---|
42 | # direct access to the program bconsole
|
---|
43 | class Bconsole:
|
---|
44 |
|
---|
45 | def __init__(self):
|
---|
46 | #logging.debug('BC init')
|
---|
47 |
|
---|
48 | self.cwd = "/"
|
---|
49 | self.state = BconsoleState.UNKNOWN
|
---|
50 | self.last_items_dict = {}
|
---|
51 |
|
---|
52 | self.bconsole = pexpect.spawn( BACULA_CMD, logfile=file(LOG_BCONSOLE_DUMP, 'w'), timeout=10 )
|
---|
53 | self.bconsole.setecho( False )
|
---|
54 | self.bconsole.expect( BCONSOLE_CMD_PROMPT )
|
---|
55 | self.bconsole.sendline( 'restore' )
|
---|
56 | self.bconsole.expect( BCONSOLE_SELECT_PROMPT )
|
---|
57 | self.bconsole.sendline( "5" )
|
---|
58 | self.wait_for_prompt()
|
---|
59 |
|
---|
60 |
|
---|
61 | def _normalize_dir( self, path ):
|
---|
62 | # guarantee that directory path ends with (exactly one) "/"
|
---|
63 | return path.rstrip('/') + "/"
|
---|
64 |
|
---|
65 | def _get_select_items(self,lines):
|
---|
66 | re_select_items = re.compile('\s*[0-9]+:\s*.+')
|
---|
67 | return filter( re_select_items.match, lines )
|
---|
68 |
|
---|
69 | def _get_item_dict( self,lines ):
|
---|
70 | dictionary = {}
|
---|
71 | for line in self._get_select_items(lines):
|
---|
72 | number,item = line.split( ":", 1 )
|
---|
73 | item = self._normalize_dir( item.strip() )
|
---|
74 | number = number.strip()
|
---|
75 | dictionary[item]=number
|
---|
76 | return dictionary
|
---|
77 |
|
---|
78 |
|
---|
79 |
|
---|
80 | def wait_for_prompt(self):
|
---|
81 |
|
---|
82 | # set to error state.
|
---|
83 | # Only set back to valid state,
|
---|
84 | # if a valid prompt is received
|
---|
85 | self.state=BconsoleState.ERROR
|
---|
86 |
|
---|
87 | try:
|
---|
88 | index = self.bconsole.expect( [ BCONSOLE_SELECT_PROMPT, BCONSOLE_RESTORE_PROMPT ] )
|
---|
89 | if index == 0:
|
---|
90 | # SELECT_PROMPT
|
---|
91 | self.state=BconsoleState.SELECT_PROMPT
|
---|
92 | lines = self.bconsole.before.splitlines()
|
---|
93 | self.last_items_dict = self._get_item_dict(lines)
|
---|
94 | logging.debug( str( self.last_items_dict ) )
|
---|
95 | elif index == 1:
|
---|
96 | # RESTORE_PROMPT
|
---|
97 | self.state=BconsoleState.RESTORE_PROMPT
|
---|
98 | else:
|
---|
99 | logging.error( "unexpected result" )
|
---|
100 | except pexpect.EOF:
|
---|
101 | logging.error( "EOF bconsole" )
|
---|
102 | except pexpect.TIMEOUT:
|
---|
103 | logging.error( "TIMEOUT bconsole" )
|
---|
104 |
|
---|
105 | return self.state
|
---|
106 |
|
---|
107 |
|
---|
108 |
|
---|
109 | def cd(self,path):
|
---|
110 | path = self._normalize_dir( path )
|
---|
111 | logging.debug( "(" + path + ")" )
|
---|
112 |
|
---|
113 | # parse for BCONSOLE_SELECT_PROMPT or BCONSOLE_RESTORE_PROMPT
|
---|
114 | # BCONSOLE_SELECT_PROMPT: take first part of path and try to match. send number. iterate
|
---|
115 | # BCONSOLE_RESTORE_PROMPT: cd to directory (as before)
|
---|
116 |
|
---|
117 | if not path:
|
---|
118 | return True
|
---|
119 |
|
---|
120 | if path == "/":
|
---|
121 | return True
|
---|
122 |
|
---|
123 | if self.state == BconsoleState.SELECT_PROMPT:
|
---|
124 | return self.cd_select( path )
|
---|
125 | elif self.state == BconsoleState.RESTORE_PROMPT:
|
---|
126 | return self.cd_restore( path )
|
---|
127 | # else error
|
---|
128 | return False
|
---|
129 |
|
---|
130 |
|
---|
131 | def cd_select(self, path):
|
---|
132 | logging.debug( "(" + path + ")" )
|
---|
133 |
|
---|
134 | # get top level directory
|
---|
135 | directory,sep,path=path.lstrip( "/" ).partition( "/" )
|
---|
136 | directory=self._normalize_dir(directory)
|
---|
137 | logging.debug( "directory: " + directory )
|
---|
138 |
|
---|
139 | if self.last_items_dict[directory]:
|
---|
140 | logging.debug( "directory: " + directory + " (" + self.last_items_dict[directory] + ")" )
|
---|
141 | self.bconsole.sendline( self.last_items_dict[directory] )
|
---|
142 | self.wait_for_prompt()
|
---|
143 | self.cd( path )
|
---|
144 | return True
|
---|
145 |
|
---|
146 | return False
|
---|
147 |
|
---|
148 |
|
---|
149 |
|
---|
150 | def cd_restore(self, path):
|
---|
151 | logging.debug( "(" + path + ")" )
|
---|
152 |
|
---|
153 | self.bconsole.sendline( 'cd ' + path )
|
---|
154 | #self.bconsole.expect( BCONSOLE_RESTORE_PROMPT, timeout=10 )
|
---|
155 | #self.bconsole.sendline( 'pwd' )
|
---|
156 |
|
---|
157 | index = self.bconsole.expect( ["cwd is: " + path + "[/]?", BCONSOLE_RESTORE_PROMPT, pexpect.EOF, pexpect.TIMEOUT ] )
|
---|
158 | logging.debug( "cd result: " + str(index) )
|
---|
159 |
|
---|
160 | if index == 0:
|
---|
161 | # path ok, now wait for prompt
|
---|
162 | self.bconsole.expect( BCONSOLE_RESTORE_PROMPT )
|
---|
163 | return True
|
---|
164 | elif index == 1:
|
---|
165 | #print "wrong path"
|
---|
166 | return False
|
---|
167 | elif index == 2:
|
---|
168 | logging.error( "EOF bconsole" )
|
---|
169 | #raise?
|
---|
170 | return False
|
---|
171 | elif index == 3:
|
---|
172 | logging.error( "TIMEOUT bconsole" )
|
---|
173 | return False
|
---|
174 |
|
---|
175 | def ls(self, path):
|
---|
176 | logging.debug( "(" + path + ")" )
|
---|
177 |
|
---|
178 | if self.cd( path ):
|
---|
179 | if self.state == BconsoleState.SELECT_PROMPT:
|
---|
180 | return self.last_items_dict.keys()
|
---|
181 | elif self.state == BconsoleState.RESTORE_PROMPT:
|
---|
182 | return self.ls_restore( path )
|
---|
183 | else:
|
---|
184 | return
|
---|
185 |
|
---|
186 |
|
---|
187 | def ls_restore( self, path ):
|
---|
188 | self.bconsole.sendline( 'ls' )
|
---|
189 | self.bconsole.expect( BCONSOLE_RESTORE_PROMPT )
|
---|
190 | lines = self.bconsole.before.splitlines()
|
---|
191 | #logging.debug( str(lines) )
|
---|
192 | return lines
|
---|
193 |
|
---|
194 |
|
---|
195 | ###############
|
---|
196 |
|
---|
197 | class BaculaFS(fuse.Fuse):
|
---|
198 |
|
---|
199 | TYPE_NONE = 0
|
---|
200 | TYPE_FILE = 1
|
---|
201 | TYPE_DIR = 2
|
---|
202 |
|
---|
203 | files = { '': {'type': TYPE_DIR} }
|
---|
204 |
|
---|
205 | def __init__(self, *args, **kw):
|
---|
206 | logging.debug('init')
|
---|
207 | #self.console = Bconsole()
|
---|
208 | fuse.Fuse.__init__(self, *args, **kw)
|
---|
209 | #logging.debug('init finished')
|
---|
210 |
|
---|
211 |
|
---|
212 | def _getattr(self,path):
|
---|
213 | # TODO: may cause problems with filenames that ends with "/"
|
---|
214 | path = path.rstrip( '/' )
|
---|
215 | logging.debug( '"' + path + '"' )
|
---|
216 |
|
---|
217 | if (path in self.files):
|
---|
218 | #logging.debug( "(" + path + ")=" + str(self.files[path]) )
|
---|
219 | return self.files[path]
|
---|
220 |
|
---|
221 | if Bconsole().cd(path):
|
---|
222 | # don't define files, because these have not been checked
|
---|
223 | self.files[path] = { 'type': self.TYPE_DIR, 'dirs': [ ".", ".." ] }
|
---|
224 |
|
---|
225 | return self.files[path]
|
---|
226 |
|
---|
227 | # TODO: only works after readdir for the directory (eg. ls)
|
---|
228 | def getattr(self, path):
|
---|
229 |
|
---|
230 | # TODO: may cause problems with filenames that ends with "/"
|
---|
231 | path = path.rstrip( '/' )
|
---|
232 | logging.debug( '"' + path + '"' )
|
---|
233 |
|
---|
234 | st = fuse.Stat()
|
---|
235 |
|
---|
236 | if not (path in self.files):
|
---|
237 | self._getattr(path)
|
---|
238 |
|
---|
239 | if not (path in self.files):
|
---|
240 | return -errno.ENOENT
|
---|
241 |
|
---|
242 | file = self.files[path]
|
---|
243 |
|
---|
244 | if file['type'] == self.TYPE_FILE:
|
---|
245 | st.st_mode = stat.S_IFREG | 0444
|
---|
246 | st.st_nlink = 1
|
---|
247 | st.st_size = 0
|
---|
248 | return st
|
---|
249 | elif file['type'] == self.TYPE_DIR:
|
---|
250 | st.st_mode = stat.S_IFDIR | 0755
|
---|
251 | if 'dirs' in file:
|
---|
252 | st.st_nlink = len(file['dirs'])
|
---|
253 | else:
|
---|
254 | st.st_nlink = 2
|
---|
255 | return st
|
---|
256 |
|
---|
257 | # TODO: check for existens
|
---|
258 | return -errno.ENOENT
|
---|
259 |
|
---|
260 |
|
---|
261 |
|
---|
262 | def _getdir(self, path):
|
---|
263 |
|
---|
264 | # TODO: may cause problems with filenames that ends with "/"
|
---|
265 | path = path.rstrip( '/' )
|
---|
266 | logging.debug( '"' + path + '"' )
|
---|
267 |
|
---|
268 | if (path in self.files):
|
---|
269 | #logging.debug( "(" + path + ")=" + str(self.files[path]) )
|
---|
270 | if self.files[path]['type'] == self.TYPE_NONE:
|
---|
271 | logging.info( '"' + path + '" does not exist (cached)' )
|
---|
272 | return self.files[path]
|
---|
273 | elif self.files[path]['type'] == self.TYPE_FILE:
|
---|
274 | logging.info( '"' + path + '"=file (cached)' )
|
---|
275 | return self.files[path]
|
---|
276 | elif ((self.files[path]['type'] == self.TYPE_DIR) and ('files' in self.files[path])):
|
---|
277 | logging.info( '"' + path + '"=dir (cached)' )
|
---|
278 | return self.files[path]
|
---|
279 |
|
---|
280 | try:
|
---|
281 | files = Bconsole().ls(path)
|
---|
282 | logging.debug( " files: " + str( files ) )
|
---|
283 |
|
---|
284 | # setting initial empty directory. Add entires later in this function
|
---|
285 | self.files[path] = { 'type': self.TYPE_DIR, 'dirs': [ ".", ".." ], 'files': [] }
|
---|
286 | for i in files:
|
---|
287 | if i.endswith('/'):
|
---|
288 | # we expect a directory
|
---|
289 | # TODO: error with filesnames, that ends with '/'
|
---|
290 | i = i.rstrip( '/' )
|
---|
291 | self.files[path]['dirs'].append(i)
|
---|
292 | if not (i in self.files):
|
---|
293 | self.files[path + "/" + i] = { 'type': self.TYPE_DIR }
|
---|
294 | else:
|
---|
295 | self.files[path]['files'].append(i)
|
---|
296 | self.files[path + "/" + i] = { 'type': self.TYPE_FILE }
|
---|
297 |
|
---|
298 | except Exception as e:
|
---|
299 | logging.exception(e)
|
---|
300 | logging.error( "no access to path " + path )
|
---|
301 | self.files[path] = { 'type': self.TYPE_NONE }
|
---|
302 |
|
---|
303 | logging.debug( '"' + path + '"=' + str( self.files[path] ) )
|
---|
304 | return self.files[path]
|
---|
305 |
|
---|
306 |
|
---|
307 |
|
---|
308 | def readdir(self, path, offset):
|
---|
309 | logging.debug( '"' + path + '", offset=' + str(offset) + ')' )
|
---|
310 |
|
---|
311 | dir = self._getdir( path )
|
---|
312 |
|
---|
313 | #logging.debug( " readdir: type: " + str( dir['type'] ) )
|
---|
314 | #logging.debug( " readdir: dirs: " + str( dir['dirs'] ) )
|
---|
315 | #logging.debug( " readdir: file: " + str( dir['files'] ) )
|
---|
316 |
|
---|
317 | if dir['type'] != self.TYPE_DIR:
|
---|
318 | return -errno.ENOENT
|
---|
319 | else:
|
---|
320 | return [fuse.Direntry(f) for f in dir['files'] + dir['dirs']]
|
---|
321 |
|
---|
322 | #def open( self, path, flags ):
|
---|
323 | #logging.debug( "open " + path )
|
---|
324 | #return -errno.ENOENT
|
---|
325 |
|
---|
326 | #def read( self, path, length, offset):
|
---|
327 | #logging.debug( "read " + path )
|
---|
328 | #return -errno.ENOENT
|
---|
329 |
|
---|
330 | if __name__ == "__main__":
|
---|
331 | # initialize logging
|
---|
332 | logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,format="%(asctime)s %(process)5d(%(threadName)s) %(levelname)-7s %(funcName)s( %(message)s )")
|
---|
333 |
|
---|
334 |
|
---|
335 | usage = """
|
---|
336 | Bacula filesystem: displays files from Bacula backups as a (userspace) filesystem.
|
---|
337 | Internaly, it uses Baculas bconsole.
|
---|
338 |
|
---|
339 | """ + fuse.Fuse.fusage
|
---|
340 |
|
---|
341 |
|
---|
342 | fs = BaculaFS(
|
---|
343 | version="%prog: " + BACULA_FS_VERSION,
|
---|
344 | usage=usage,
|
---|
345 | # required to let "-s" set single-threaded execution
|
---|
346 | dash_s_do='setsingle'
|
---|
347 | )
|
---|
348 |
|
---|
349 | #server.parser.add_option(mountopt="root", metavar="PATH", default='/',help="mirror filesystem from under PATH [default: %default]")
|
---|
350 | #server.parse(values=server, errex=1)
|
---|
351 | fs.parse()
|
---|
352 |
|
---|
353 | fs.main()
|
---|