1 import sys, os, pwd, subprocess, errno, socket, select, mmap, stat, re
4 # Write (blockingly) to sockets that may or may not be in blocking mode.
5 # We need this because our stderr is sometimes eaten by subprocesses
6 # (probably ssh) that sometimes make it nonblocking, if only temporarily,
7 # leading to race conditions. Ick. We'll do it the hard way.
8 def _hard_write(fd, buf):
10 (r,w,x) = select.select([], [fd], [], None)
12 raise IOError('select(fd) returned without being writable')
14 sz = os.write(fd, buf)
16 if e.errno != errno.EAGAIN:
22 _hard_write(sys.stderr.fileno(), s)
29 if e.errno == errno.EEXIST:
46 if e.errno == errno.ENOENT:
47 pass # it doesn't exist, that's what you asked for
51 p = subprocess.Popen(argv, stdout=subprocess.PIPE)
57 # FIXME: this function isn't very generic, because it splits the filename
58 # in an odd way and depends on a terminating '/' to indicate directories.
59 # But it's used in a couple of places, so let's put it here.
62 l = [i+'/' for i in l[:-1]] + l[-1:]
64 l.pop() # extra blank caused by terminating '/'
68 # like os.path.realpath, but doesn't follow a symlink for the last element.
69 # (ie. if 'p' itself is itself a symlink, this one won't follow it)
75 if st and stat.S_ISLNK(st.st_mode):
76 (dir, name) = os.path.split(p)
77 dir = os.path.realpath(dir)
78 out = os.path.join(dir, name)
80 out = os.path.realpath(p)
81 #log('realpathing:%r,%r\n' % (p, out))
91 _username = pwd.getpwuid(uid)[0]
93 _username = 'user%d' % uid
100 if not _userfullname:
103 _userfullname = pwd.getpwuid(uid)[4].split(',')[0]
105 _userfullname = 'user%d' % uid
113 _hostname = socket.getfqdn()
117 class NotOk(Exception):
121 def __init__(self, inp, outp):
125 def read(self, size):
127 return self.inp.read(size)
131 return self.inp.readline()
133 def write(self, data):
134 #log('%d writing: %d bytes\n' % (os.getpid(), len(data)))
135 self.outp.write(data)
138 [rl, wl, xl] = select.select([self.inp.fileno()], [], [], 0)
140 assert(rl[0] == self.inp.fileno())
149 s = re.sub(r'\s+', ' ', str(s))
150 self.write('\nerror %s\n' % s)
152 def _check_ok(self, onempty):
155 for rl in linereader(self.inp):
156 #log('%d got line: %r\n' % (os.getpid(), rl))
157 if not rl: # empty line
161 elif rl.startswith('error '):
162 #log('client: error: %s\n' % rl[6:])
166 raise Exception('server exited unexpectedly; see errors above')
168 def drain_and_check_ok(self):
171 return self._check_ok(onempty)
175 raise Exception('expected "ok", got %r' % rl)
176 return self._check_ok(onempty)
187 def chunkyreader(f, count = None):
190 b = f.read(min(count, 65536))
192 raise IOError('EOF with %d bytes remaining' % count)
203 def __init__(self, it, ondone = None):
211 return self.it.next()
221 if s and not s.endswith('/'):
227 def _mmap_do(f, len, flags, prot):
229 st = os.fstat(f.fileno())
231 map = mmap.mmap(f.fileno(), len, flags, prot)
232 f.close() # map will persist beyond file close
236 def mmap_read(f, len = 0):
237 return _mmap_do(f, len, mmap.MAP_PRIVATE, mmap.PROT_READ)
240 def mmap_readwrite(f, len = 0):
241 return _mmap_do(f, len, mmap.MAP_SHARED, mmap.PROT_READ|mmap.PROT_WRITE)
245 g = re.match(r'([-+\d.e]+)\s*(\w*)', str(s))
247 raise ValueError("can't parse %r as a number" % s)
248 (val, unit) = g.groups()
251 if unit in ['t', 'tb']:
252 mult = 1024*1024*1024*1024
253 elif unit in ['g', 'gb']:
254 mult = 1024*1024*1024
255 elif unit in ['m', 'mb']:
257 elif unit in ['k', 'kb']:
259 elif unit in ['', 'b']:
262 raise ValueError("invalid unit %r in number %r" % (unit, s))
266 # count the number of elements in an iterator (consumes the iterator)
268 return reduce(lambda x,y: x+1, l)
280 saved_errors.append(e)
283 istty = os.isatty(2) or atoi(os.environ.get('BUP_FORCE_TTY'))
290 oldhook = sys.excepthook
291 def newhook(exctype, value, traceback):
292 if exctype == KeyboardInterrupt:
293 log('Interrupted.\n')
295 return oldhook(exctype, value, traceback)
296 sys.excepthook = newhook