source: baculafs/trunk/baculafs.py@ 786

Last change on this file since 786 was 786, checked in by joergs, on Aug 27, 2009 at 5:49:44 PM

cleanup

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