source: baculafs/trunk/baculafs.py@ 1148

Last change on this file since 1148 was 1148, checked in by joergs, on May 22, 2013 at 12:45:35 PM

various improvements

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