source: baculafs/trunk/baculafs.py@ 898

Last change on this file since 898 was 789, checked in by joergs, on Aug 28, 2009 at 12:01:44 AM

beautified

  • Property svn:executable set to *
  • Property svn:keywords set to
    Id
    Rev
    URL
File size: 10.7 KB
RevLine 
[778]1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
[783]4# $URL: baculafs/trunk/baculafs.py $
5# $Id: baculafs.py 789 2009-08-27 22:01:44Z joergs $
6
[787]7import fuse
[778]8import logging
9import stat
10import errno
11import os
12import pexpect
13import sys
[784]14import re
[778]15
16fuse.fuse_python_api = (0, 2)
17
18###### bconsole
19################
20
[783]21BACULA_FS_VERSION = "$Rev: 789 $"
[782]22
[778]23LOG_FILENAME = '/tmp/baculafs.log'
24LOG_BCONSOLE_DUMP = '/tmp/bconsole.out'
25
26
27#BACULA_CMD = 'strace -f -o /tmp/bconsole.strace /usr/sbin/bconsole -n'
28BACULA_CMD = '/usr/sbin/bconsole -n'
29
30BCONSOLE_CMD_PROMPT='\*'
[784]31BCONSOLE_SELECT_PROMPT='Select .*:.*'
[778]32BCONSOLE_RESTORE_PROMPT='\$ '
33
[787]34# define the states bconsole can be in
[785]35class BconsoleState:
[787]36 UNKNOWN = ''
37 CMD_PROMPT = BCONSOLE_CMD_PROMPT
38 SELECT_PROMPT = BCONSOLE_SELECT_PROMPT
39 RESTORE_PROMPT = BCONSOLE_RESTORE_PROMPT
40 ERROR = "error"
[785]41
[787]42# direct access to the program bconsole
[778]43class Bconsole:
44
[785]45 def __init__(self):
[780]46 #logging.debug('BC init')
[784]47
48 self.cwd = "/"
[785]49 self.state = BconsoleState.UNKNOWN
[787]50 self.last_items_dict = {}
[784]51
[778]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' )
[784]56 self.bconsole.expect( BCONSOLE_SELECT_PROMPT )
[778]57 self.bconsole.sendline( "5" )
[787]58 self.wait_for_prompt()
[784]59
[778]60
[784]61 def _normalize_dir( self, path ):
[787]62 # guarantee that directory path ends with (exactly one) "/"
[784]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 )
[787]73 item = self._normalize_dir( item.strip() )
[784]74 number = number.strip()
75 dictionary[item]=number
76 return dictionary
77
78
[778]79
[785]80 def wait_for_prompt(self):
[784]81
[785]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
[784]87 try:
88 index = self.bconsole.expect( [ BCONSOLE_SELECT_PROMPT, BCONSOLE_RESTORE_PROMPT ] )
89 if index == 0:
90 # SELECT_PROMPT
[785]91 self.state=BconsoleState.SELECT_PROMPT
[787]92 lines = self.bconsole.before.splitlines()
93 self.last_items_dict = self._get_item_dict(lines)
94 logging.debug( str( self.last_items_dict ) )
[784]95 elif index == 1:
96 # RESTORE_PROMPT
[785]97 self.state=BconsoleState.RESTORE_PROMPT
98 else:
99 logging.error( "unexpected result" )
[784]100 except pexpect.EOF:
101 logging.error( "EOF bconsole" )
102 except pexpect.TIMEOUT:
103 logging.error( "TIMEOUT bconsole" )
104
[785]105 return self.state
[784]106
[785]107
[787]108
[785]109 def cd(self,path):
110 path = self._normalize_dir( path )
111 logging.debug( "(" + path + ")" )
112
[786]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
[785]117 if not path:
118 return True
119
[787]120 if path == "/":
121 return True
122
123 if self.state == BconsoleState.SELECT_PROMPT:
[785]124 return self.cd_select( path )
[787]125 elif self.state == BconsoleState.RESTORE_PROMPT:
[785]126 return self.cd_restore( path )
127 # else error
128 return False
129
130
[784]131 def cd_select(self, path):
132 logging.debug( "(" + path + ")" )
133
[787]134 # get top level directory
[784]135 directory,sep,path=path.lstrip( "/" ).partition( "/" )
[787]136 directory=self._normalize_dir(directory)
[784]137 logging.debug( "directory: " + directory )
138
[787]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()
[784]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
[778]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 ] )
[780]158 logging.debug( "cd result: " + str(index) )
[778]159
160 if index == 0:
161 # path ok, now wait for prompt
162 self.bconsole.expect( BCONSOLE_RESTORE_PROMPT )
[781]163 return True
[778]164 elif index == 1:
165 #print "wrong path"
[781]166 return False
[778]167 elif index == 2:
[781]168 logging.error( "EOF bconsole" )
169 #raise?
170 return False
[778]171 elif index == 3:
[781]172 logging.error( "TIMEOUT bconsole" )
173 return False
174
175 def ls(self, path):
176 logging.debug( "(" + path + ")" )
177
178 if self.cd( path ):
[787]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 )
[781]183 else:
[778]184 return
185
[787]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
[778]195###############
196
197class 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
[781]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
[787]227 # TODO: only works after readdir for the directory (eg. ls)
228 def getattr(self, path):
[781]229
[787]230 # TODO: may cause problems with filenames that ends with "/"
231 path = path.rstrip( '/' )
232 logging.debug( '"' + path + '"' )
[781]233
[787]234 st = fuse.Stat()
[781]235
[787]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
[778]262 def _getdir(self, path):
263
264 # TODO: may cause problems with filenames that ends with "/"
265 path = path.rstrip( '/' )
[780]266 logging.debug( '"' + path + '"' )
[778]267
268 if (path in self.files):
[780]269 #logging.debug( "(" + path + ")=" + str(self.files[path]) )
[781]270 if self.files[path]['type'] == self.TYPE_NONE:
271 logging.info( '"' + path + '" does not exist (cached)' )
[778]272 return self.files[path]
[781]273 elif self.files[path]['type'] == self.TYPE_FILE:
274 logging.info( '"' + path + '"=file (cached)' )
275 return self.files[path]
[778]276 elif ((self.files[path]['type'] == self.TYPE_DIR) and ('files' in self.files[path])):
[781]277 logging.info( '"' + path + '"=dir (cached)' )
[778]278 return self.files[path]
279
280 try:
281 files = Bconsole().ls(path)
[781]282 logging.debug( " files: " + str( files ) )
[780]283
284 # setting initial empty directory. Add entires later in this function
285 self.files[path] = { 'type': self.TYPE_DIR, 'dirs': [ ".", ".." ], 'files': [] }
[778]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
[780]298 except Exception as e:
299 logging.exception(e)
[778]300 logging.error( "no access to path " + path )
[787]301 self.files[path] = { 'type': self.TYPE_NONE }
[784]302
[780]303 logging.debug( '"' + path + '"=' + str( self.files[path] ) )
[778]304 return self.files[path]
305
306
307
308 def readdir(self, path, offset):
[780]309 logging.debug( '"' + path + '", offset=' + str(offset) + ')' )
[778]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
330if __name__ == "__main__":
[780]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
[782]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)
[778]351 fs.parse()
[782]352
[778]353 fs.main()
Note: See TracBrowser for help on using the repository browser.