rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
expected_status_tree)
expected_status_tree, None, None, None, None, 1)
def update_props(): "receive properties via update" # Bootstrap sbox = sandbox(update_props) wc_dir = os.path.join (svntest.main.general_wc_dir, sbox) if svntest.actions.make_repo_and_wc(sbox): return 1 # Make a backup copy of the working copy wc_backup = wc_dir + 'backup' svntest.actions.duplicate_dir(wc_dir, wc_ba...
if target_ob.install == 'test' and bldtype == 'exe' \ and parser.get(target, 'testing') != 'skip': test_progs.append(tpath)
if target_ob.install == 'test' and bldtype == 'exe': test_deps.append(tpath) if parser.get(target, 'testing') != 'skip': test_progs.append(tpath)
def main(fname, oname=None, skip_depends=0): parser = ConfigParser.ConfigParser(_cfg_defaults) parser.read(fname) if oname is None: oname = os.path.splitext(os.path.basename(fname))[0] + '-outputs.mk' ofile = open(oname, 'w') ofile.write('# DO NOT EDIT -- AUTOMATICALLY GENERATED\n\n') errors = 0 targets = { } groups...
diff_pure_repository_update_a_file ]
diff_pure_repository_update_a_file, diff_only_property_change ]
def diff_pure_repository_update_a_file(sbox): "pure repository diff update a file" if sbox.build(): return 1 wc_dir = sbox.wc_dir was_cwd = os.getcwd() os.chdir(wc_dir) # rev 2 update_a_file() svntest.main.run_svn(None, 'ci', '-m', '"log msg"') # rev 3 add_a_file_in_a_subdir() svntest.main.run_svn(None, 'ci', '-m',...
update_binary_file
update_binary_file, update_binary_file_2
def update_binary_file_2(): "update to an old revision of a binary files" sbox = sandbox(update_binary_file_2) wc_dir = os.path.join (svntest.main.general_wc_dir, sbox) if svntest.actions.make_repo_and_wc(sbox): return 1 # Suck up contents of a test .png file. fp = open("theta.png") theta_contents = fp.read() fp.clo...
return check_update_a_file(diff_output)
if check_update_a_file(diff_output): return 1 os.chdir(wc_dir) diff_output, err_output = svntest.main.run_svn(None, 'diff', '-r1:2') os.chdir(was_cwd) if check_update_a_file(diff_output): return 1 diff_output, err_output = svntest.main.run_svn(None, 'diff', '-r2:3', url) if check_add_a_file_in_a_subdir(diff_output): ...
def diff_pure_repository_update_a_file(sbox): "pure repository diff update a file" if sbox.build(): return 1 wc_dir = sbox.wc_dir was_cwd = os.getcwd() os.chdir(wc_dir) update_a_file() svntest.main.run_svn(None, 'ci') os.chdir(was_cwd) url = svntest.main.test_area_url + '/' + svntest.main.current_repo_dir diff_outp...
rm = re.compile ('^(..)(.)(.+)(\d+)\s+(.+)')
rm = re.compile ('^(..)(.)([^0-9]+)(\d+|-)\s+(.+)')
def build_tree_from_status(lines): "Return a tree derived by parsing the output LINES from 'st'." root = SVNTreeNode(root_node_name) rm = re.compile ('^.+\:.+(\d+)') lastline = string.strip(lines.pop()) match = rm.search(lastline) if match and match.groups(): repos_rev = match.group(1) else: repos_rev = '?' rm = re.c...
new_branch = create_from_path(match.group(5), None, {}, {'status' : match.group(1), 'locked' : match.group(2), 'wc_rev' : match.group(4), 'repos_rev' : repos_rev})
if match.group(4) != '-': new_branch = create_from_path(match.group(5), None, {}, {'status' : match.group(1), 'locked' : match.group(2), 'wc_rev' : match.group(4), 'repos_rev' : repos_rev})
def build_tree_from_status(lines): "Return a tree derived by parsing the output LINES from 'st'." root = SVNTreeNode(root_node_name) rm = re.compile ('^.+\:.+(\d+)') lastline = string.strip(lines.pop()) match = rm.search(lastline) if match and match.groups(): repos_rev = match.group(1) else: repos_rev = '?' rm = re.c...
output_list = [ [os.path.join(wc_backup, mu_path),
output_list = [ [mu_path,
def update_props(): "receive properties via update" # Bootstrap sbox = sandbox(update_props) wc_dir = os.path.join (svntest.main.general_wc_dir, sbox) if svntest.actions.make_repo_and_wc(sbox): return 1 # Make a backup copy of the working copy wc_backup = wc_dir + 'backup' svntest.actions.duplicate_dir(wc_dir, wc_ba...
[os.path.join(wc_backup, H_path),
[H_path,
def update_props(): "receive properties via update" # Bootstrap sbox = sandbox(update_props) wc_dir = os.path.join (svntest.main.general_wc_dir, sbox) if svntest.actions.make_repo_and_wc(sbox): return 1 # Make a backup copy of the working copy wc_backup = wc_dir + 'backup' svntest.actions.duplicate_dir(wc_dir, wc_ba...
"unversioned",
"Can't find an entry",
def commit_unversioned_thing(sbox): "committing unversioned object produces error" if sbox.build(): return 1 wc_dir = sbox.wc_dir # Create an unversioned file in the wc. svntest.main.file_append(os.path.join(wc_dir, 'blorg'), "nothing to see") # Commit a non-existent file and *expect* failure: return svntest.action...
def make_vardict(_group): vars = {} _cur = libweb100.web100_var_head(_group) while _cur != None: var = Web100Var(_cur, _group) vars[str(var)] = var _cur = libweb100.web100_var_next(_cur) return vars
def make_vardict(_group): vars = {} _cur = libweb100.web100_var_head(_group) while _cur != None: var = Web100Var(_cur, _group) vars[str(var)] = var _cur = libweb100.web100_var_next(_cur) return vars
self.write_vars = make_vardict(self._tune_group) self.read_vars = make_vardict(self._read_group) for (name, var) in self.write_vars.items(): try: self.read_vars[name] except: self.read_vars[name] = var
_cur = libweb100.web100_var_head(self._read_group) while _cur != None: var = Web100Var(_cur, self._read_group) self.read_vars[str(var)] = var _cur = libweb100.web100_var_next(_cur)
def __init__(self, host=None): if (host != None): raise error("Remote agents not supported.") _agent = libweb100.web100_attach(libweb100.WEB100_AGENT_TYPE_LOCAL, None) if _agent == None: libweb100_err() self._agent = _agent self._tune_group = libweb100.web100_group_find(_agent, "tune") if self._tune_group == None: lib...
try: libweb100.delete_bufp(self.bufp) except: pass
libweb100.delete_bufp(self.bufp)
def __del__(self): try: libweb100.delete_bufp(self.bufp) except: pass
var.valtobuf(val, self.agent.bufp) if libweb100.web100_raw_write(var._var, self._connection, self.agent.bufp) != \
buf = var.valtobuf(val, self.agent.bufp) if libweb100.web100_raw_write(var._var, self._connection, buf) != \
def write(self, name, val): """Write a value to a single variable.""" try: var = self.agent.write_vars[name] except KeyError: raise error("No writable variable '%s' found."%name) var.valtobuf(val, self.agent.bufp) if libweb100.web100_raw_write(var._var, self._connection, self.agent.bufp) != \ libweb100.WEB100_ERR_SUCC...
class Web100ReadLog: def __init__(self, logname): self._log = libweb100.web100_log_open_read(logname) if self._log == None: libweb100_err() self._snap = libweb100.web100_snapshot_alloc_from_log(self._log) if self._snap == None: libweb100_err() self.vars = make_vardict(libweb100.web100_get_log_group(self._log)) self.b...
def write(self, name, val): """Write a value to a single variable.""" try: var = self.agent.write_vars[name] except KeyError: raise error("No writable variable '%s' found."%name) var.valtobuf(val, self.agent.bufp) if libweb100.web100_raw_write(var._var, self._connection, self.agent.bufp) != \ libweb100.WEB100_ERR_SUCC...
elif self._type == libweb100.WEB100_TYPE_INET_ADDRESS_IPV4 or \ self._type == libweb100.WEB100_TYPE_IP_ADDRESS or \ self._type == libweb100.WEB100_TYPE_INET_ADDRESS_IPV6 or \ self._type == libweb100.WEB100_TYPE_INET_ADDRESS:
else:
def val(self, bufp): if self._type == libweb100.WEB100_TYPE_INET_PORT_NUMBER or\ self._type == libweb100.WEB100_TYPE_UNSIGNED16: return libweb100.u16p_value(libweb100.bufp_to_u16p(bufp)) elif self._type == libweb100.WEB100_TYPE_INTEGER or \ self._type == libweb100.WEB100_TYPE_INTEGER32: return libweb100.s32p_value(libw...
else: raise error("Unknown Web100 type: %d"%self._type)
def val(self, bufp): if self._type == libweb100.WEB100_TYPE_INET_PORT_NUMBER or\ self._type == libweb100.WEB100_TYPE_UNSIGNED16: return libweb100.u16p_value(libweb100.bufp_to_u16p(bufp)) elif self._type == libweb100.WEB100_TYPE_INTEGER or \ self._type == libweb100.WEB100_TYPE_INTEGER32: return libweb100.s32p_value(libw...
print cfgtuple
def main(): from twisted.internet import reactor from ConfigParser import SafeConfigParser # Read the configuration file configFile = '/etc/pybal/pybal.conf' config = SafeConfigParser() config.read(configFile) services = {} for section in config.sections(): cfgtuple = ( config.get(section, 'protocol'), config.get(s...
s = hmac.HMAC(secret, digestmod = MD5)
s = hmac.HMAC(secret, digestmod = SHA256)
def gen_hmac(secret, ip): epoch_mins = (long)(time()/60) s = hmac.HMAC(secret, digestmod = MD5) s.update(socket.inet_aton(socket.gethostbyname(ip))) s.update(struct.pack("i", epoch_mins)) # "i" is for integer print s.hexdigest()
r" *use +(?P<module>[a-zA-Z_][a-zA-Z_0-9]*)(?P<only> *, *only:)? *(?P<imports>.*)$",
r" *use +(?P<module>[a-zA-Z_][a-zA-Z_0-9]*)(?P<only> *, *only *:)? *(?P<imports>.*)$",
def parseUse(inFile): """Parses the use statements in inFile The parsing stops at the first non use statement. Returns something like: ([{'module':'module1','only':['el1',el2=>el3']},...], '! comment1\\n!comment2...\\n', 'last line (the line that stopped the parsing)') """ useStartRe=re.compile( r" *(?P<use>use[^&!]*)(...
elif m.has_key('renames'): outFile.write(" USE "+m['module']+","+ string.ljust("",38)) if m['renames']: outFile.write(m['renames'][0]) for i in range(1,len(m['renames'])): write(",&\n"+string.ljust("",45)+m['renames'][i])
else: outFile.write(" USE "+m['module']) if m.has_key('renames') and m['renames']: outFile.write(","+string.ljust("",38)+ m['renames'][0]) for i in range(1,len(m['renames'])): outFile.write(",&\n"+string.ljust("",45)+m['renames'][i])
def writeUseLong(modules,outFile): for m in modules: if m.has_key('only'): outFile.write(" USE "+m['module']+","+ string.rjust('ONLY: ',38-len(m['module']))) if m['only']: outFile.write(m['only'][0]) for i in range(1,len(m['only'])): outFile.write(",&\n"+string.ljust("",45)+m['only'][i]) elif m.has_key('renames'): out...
outFile.write("\n") outFile.write('\n'.join(m['comments']))
file.write("\n") file.write('\n'.join(m['comments']))
def writeUseShort(modules,file): """Writes a declaration in a compact way""" for m in modules: uLine=[] if m.has_key('only'): uLine.append(" USE "+m['module']+", ONLY: ") for k in m['only'][:-1]: uLine.append(k+", ") uLine.append(m['only'][-1]) elif m.has_key('renames') and m['renames']: uLine.append(" USE "+m['modul...
nonWordRe=re.compile(r"(\W)")
nonWordRe=re.compile(r"([^a-zA-Z0-9_.])")
def writeInCols(dLine,indentCol,maxCol,indentAtt,file): """writes out the strings (trying not to cut them) in dLine up to maxCol indenting each newline with indentCol. The '&' of the continuation line is at maxCol. indentAtt is the actual intent, and the new indent is returned""" strRe=re.compile(r"('[^'\n]*'|\"[^\"\n]...
try: prettfyInplace(fileName,bkDir, normalize_use=defaultsDict['normalize-use'], upcase_keywords=defaultsDict['upcase'], interfaces_dir=defaultsDict['interface-dir'], replace=defaultsDict['replace']) except: import traceback sys.stdout.write('-'*60+"\n") traceback.print_exc(file=sys.stdout) sys.stdout.write('-'*60+"\n"...
prettfyInplace(fileName,bkDir, normalize_use=defaultsDict['normalize-use'], upcase_keywords=defaultsDict['upcase'], interfaces_dir=defaultsDict['interface-dir'], replace=defaultsDict['replace'])
def prettfyInplace(fileName,bkDir="preprettify",normalize_use=1, upcase_keywords=1, interfaces_dir=None, replace=None,logFile=sys.stdout): """Same as prettify, but inplace, replaces only if needed""" if not os.path.exists(bkDir): os.mkdir(bkDir) if not os.path.isdir(bkDir): raise Error("bk-dir must be a directory, was ...
nullifys="".join(nullifyRe.findall(rest))
nullifys=",".join(nullifyRe.findall(rest))
def cleanDeclarations(routine,logFile=sys.stdout): """cleans up the declaration part of the given parsed routine removes unused variables""" global rVar commentToRemoveRe=re.compile(r" *! *(?:interface|arguments|parameters|locals?|\** *local +variables *\**|\** *local +parameters *\**) *$",re.IGNORECASE) nullifyRe=re.c...
'g4x6':{'atoms':[3,4,5,6],'distances':[7,8,9,10,11],'molecule':[2]},
'g4x6':{'atoms':[3,4,5,6],'distances':[7,8,9,10,11,12],'molecule':[2]},
def cons_conv(oldInput,oldSect,newInput,new_sect,conv): del new_sect.auto_g new_sect.pre_comments=oldSect.pre_comments new_sect.post_comments=oldSect.post_comments consTypes={'g3x3':{'atoms':[3,4,5],'distances':[6,7,8],'molecule':[2]}, 'g4x6':{'atoms':[3,4,5,6],'distances':[7,8,9,10,11],'molecule':[2]}, 'dist':{'atoms'...
if line.split()[0].lower()=="end":break
ll=line.split() if ll[0].lower()=="end":break
def ff_conv(oldInput,oldSect,newInput,new_sect,conv): del new_sect.auto_g new_sect.pre_comments=oldSect.pre_comments new_sect.post_comments=oldSect.post_comments l_nr=0 nl=len(oldSect.raw_lines) while 1: if l_nr>=nl: break line=oldSect.raw_lines[l_nr] ll=line.strip().lower() if ll=="charges": while 1: l_nr+=1 if l_nr>=...
ch.add_keyword(Keyword(conv.upcase("atoms"),values=line.split()[1:3])) ch.add_keyword(Keyword(conv.upcase("k"),values=[line.split()[3]])) ch.add_keyword(Keyword(conv.upcase("r0"),values=[line.split()[4]]))
ch.add_keyword(Keyword(conv.upcase("atoms"),values=ll[1:3])) if ll[0].lower()=="harmonic": ch.add_keyword(Keyword(conv.upcase("k"),values=[ll[3]])) ch.add_keyword(Keyword(conv.upcase("r0"),values=[line.split()[4]])) elif ll[0].lower()=="quartic": ch.add_keyword(Keyword(conv.upcase("k"),values=ll[3:6])) ch.add_keyword(K...
def ff_conv(oldInput,oldSect,newInput,new_sect,conv): del new_sect.auto_g new_sect.pre_comments=oldSect.pre_comments new_sect.post_comments=oldSect.post_comments l_nr=0 nl=len(oldSect.raw_lines) while 1: if l_nr>=nl: break line=oldSect.raw_lines[l_nr] ll=line.strip().lower() if ll=="charges": while 1: l_nr+=1 if l_nr>=...
ch.add_keyword(Keyword("atom",l[1:3]))
ch.add_keyword(Keyword("atoms",l[1:3]))
def ff_conv(oldInput,oldSect,newInput,new_sect,conv): del new_sect.auto_g new_sect.pre_comments=oldSect.pre_comments new_sect.post_comments=oldSect.post_comments l_nr=0 nl=len(oldSect.raw_lines) while 1: if l_nr>=nl: break line=oldSect.raw_lines[l_nr] ll=line.strip().lower() if ll=="charges": while 1: l_nr+=1 if l_nr>=...
nrRe=re.compile("[-+]?[0-9]*\\.?[0-9]+([eEdD][-+]?[0-9]+)?")
nrRe=re.compile("[-+]?[0-9]*\\.?[0-9]+([eEdD][-+]?[0-9]+)?$")
def diffEpsilon(str1, str2,incomparable_val=1): """retuns the difference between two strings, parsing numbers and confronting them.""" import re nrRe=re.compile("[-+]?[0-9]*\\.?[0-9]+([eEdD][-+]?[0-9]+)?") tokens1=str1.split() tokens2=str2.split() distance=0.0 if len(tokens1)!=len(tokens2): return incomparable_val i=0 ...
alive = Alive()
def eekMexLogging(): # ------------------------------------------------------------ # Base Logging Setup # ------------------------------------------------------------ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-2s %(module)-10s %(levelname)-4s %(message)s', filename='eekmex.log', filemode='a'...
alive.data()
def eekMexLogging(): # ------------------------------------------------------------ # Base Logging Setup # ------------------------------------------------------------ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-2s %(module)-10s %(levelname)-4s %(message)s', filename='eekmex.log', filemode='a'...
self.backend = Backend(self.uri[1:].split('/')[0], self.factory ("http://" + self.uri[1:].split('/')[0]))
self.backend = Backend(self.uri[1:].split('/')[0], self.factory, ("http://" + self.uri[1:].split('/')[0],))
def process(self): """ Each new request begins processing here """ log.debug("Request: " + self.method + " " + self.uri); # Clean up URL self.uri = self.simplify_path(self.uri)
if log.isEnabled('apt'): self.cache = apt_pkg.GetCache() else: self.__fake_stdout() self.cache = apt_pkg.GetCache() self.__restore_stdout()
self.cache = apt_pkg.GetCache()
def load(self): """ Regenerates the fake configuration and load the packages server. """ if not self.loaded: shutil.rmtree(self.status_dir+'/apt/lists/') os.makedirs(self.status_dir+'/apt/lists/partial') sources = open(self.status_dir+'/'+'apt/etc/sources.list', 'w') for file in self.packages.keys(): # we should probab...
def import_directory(factory, dir, recursive=0): """ Import all files in a given directory into the cache This is used by apt-proxy-import to import new files into the cache """ if not os.path.exists(dir): log.err('Directory ' + dir + ' does not exist', 'import') return if recursive: log.debug("Importing packages from...
def compare(a, b): return apt_pkg.VersionCompare(a[0], b[0])
def import_debs(factory, dir): if not os.path.exists(dir): os.makedirs(dir) for file in os.listdir(dir): if file[-4:]!='.deb': log.msg("IGNORING:"+ file, 'import') continue log.msg("considering:"+ dir+'/'+file, 'import') paths = get_mirror_path(factory, dir+'/'+file) if paths: if len(paths) != 1: log.msg("WARNING: mult...
def import_file(factory, dir, file): """ Import a .deb into cache from given filename """ if file[-4:]!='.deb': log.msg("Ignoring (unknown file type):"+ file, 'import') return log.debug("considering: " + dir + '/' + file, 'import') paths = get_mirror_path(factory, dir+'/'+file) if paths: if len(paths) != 1: log.debug(...
def import_debs(factory, dir): if not os.path.exists(dir): os.makedirs(dir) for file in os.listdir(dir): if file[-4:]!='.deb': log.msg("IGNORING:"+ file, 'import') continue log.msg("considering:"+ dir+'/'+file, 'import') paths = get_mirror_path(factory, dir+'/'+file) if paths: if len(paths) != 1: log.msg("WARNING: mult...
log.msg("Not found, trying to guess", 'import') path = closest_match(AptDpkgInfo(dir+'/'+file), get_mirror_versions(factory, dir+'/'+file)) if path: log.msg("MIRROR_PATH:"+ path, 'import') spath = dir+'/'+file dpath = factory.cache_dir+path if not os.path.exists(dpath): log.msg("IMPORTING:"+spath, 'import') dpath = re....
log.msg(file + ' skipped - already in cache', 'import') else: log.msg(file + ' skipped - no suitable backend found', 'import')
def import_debs(factory, dir): if not os.path.exists(dir): os.makedirs(dir) for file in os.listdir(dir): if file[-4:]!='.deb': log.msg("IGNORING:"+ file, 'import') continue log.msg("considering:"+ dir+'/'+file, 'import') paths = get_mirror_path(factory, dir+'/'+file) if paths: if len(paths) != 1: log.msg("WARNING: mult...
log.debug('Opening database ' + filename)
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
try: shelve.verify(filename) except: os.rename(filename, filename+'.error') log.msg(filename+' could not be opened, moved to '+filename+'.error','db', 1) log.msg('Recreating '+ filename,'db', 1)
try: log.debug('Verifying database: ' + filename) shelve.verify(filename) except: os.rename(filename, filename+'.error') log.msg(filename+' could not be opened, moved to '+filename+'.error','db', 1) log.msg('Recreating '+ filename,'db', 1)
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
shelve = dbshelve.open(filename)
log.debug('Opening database ' + filename) shelve = dbshelve.open(filename)
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
log.debug('Upgrading from previous database format: %s' % filename + '.previous') from bsddb import dbshelve as old_dbshelve
log.msg('Upgrading from previous database format: %s' % filename + '.previous') import bsddb.dbshelve
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
previous_shelve = old_dbshelve.open(filename + '.previous')
previous_shelve = bsddb.dbshelve.open(filename + '.previous')
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
log.debug("abort - not implemented")
log.debug("abort - method not implemented")
def process(self): """ Each new request begins processing here """ log.debug("Request: " + self.method + " " + self.uri); # Clean up URL self.uri = self.simplify_path(self.uri)
from bsddb3 import db,dbshelve,DBInvalidArgError
from bsddb3 import db,dbshelve
def open_shelve(filename): from bsddb3 import db,dbshelve,DBInvalidArgError log.debug('Opening database ' + filename)
except DBInvalidArgError:
except db.DBInvalidArgError:
def open_shelve(filename): from bsddb3 import db,dbshelve,DBInvalidArgError log.debug('Opening database ' + filename)
del self.factory.runningClients[self.request.uri]
try: del self.factory.runningClients[self.request.uri] except exceptions.KeyError: self.factory.debug("We are not on runningClients!!!") self.factory.debug(str(self.factory.runningClients)) raise exceptions.KeyError
def aptEnd(self): """ Called by subclasses when aptDataEnd does too much things.
self.process = reactor.spawnProcess(self, exe, args)
self.nullhandle = open("/dev/null", "w") self.process = reactor.spawnProcess(self, exe, args, childFDs = { 0:"w", 1:self.nullhandle.fileno(), 2:"r" })
def __init__(self, request): self.factory = request.factory self.deferred = defer.Deferred() # Deferred that passes status back self.path = request.local_file
log.debug("Last request removed",'client')
log.debug("Last request removed",'Fetcher')
def remove_request(self, request): """ Request should NOT be served through this Fetcher, the client probably closed the connection. If this is our last request, we may also close the connection with the server depending on the configuration.
"telling the transport to loseConnection",'client')
"telling the transport to loseConnection",'Fetcher')
def remove_request(self, request): """ Request should NOT be served through this Fetcher, the client probably closed the connection. If this is our last request, we may also close the connection with the server depending on the configuration.
log.debug(str(request.backend) + request.uri, 'fetcher_activate')
log.debug(str(request.backend) + request.uri, 'Fetcher.activate')
def activate(self, request): log.debug(str(request.backend) + request.uri, 'fetcher_activate') self.local_file = request.local_file self.local_mtime = request.local_mtime self.factory = request.factory self.request = request request.content.read()
log.debug("Finished receiving data, status:%d saveData:%d" %(self.status_code, saveData));
log.debug("Finished receiving data, status:%d saveData:%d" %(self.status_code, saveData), 'Fetcher');
def apDataEnd(self, data, saveData=True): """ Called by subclasses when the data transfer is over.
log.debug("no local time: "+self.local_file,'client')
log.debug("no local time: "+self.local_file,'Fetcher')
def apDataEnd(self, data, saveData=True): """ Called by subclasses when the data transfer is over.
"connection already closed")
"connection already closed", 'Fetcher')
def apDataEnd(self, data, saveData=True): """ Called by subclasses when the data transfer is over.
log.debug("We are not on runningFetchers!!!",'client')
log.debug("We are not on runningFetchers!!!",'Fetcher')
def apEnd(self): """ Called by subclasses when apDataEnd does too many things.
'client')
'Fetcher')
def apEnd(self): """ Called by subclasses when apDataEnd does too many things.
log.debug(' URI:' + self.request.uri, 'fetcher_activate')
log.debug(' URI:' + self.request.uri, 'Fetcher')
def apEnd(self): """ Called by subclasses when apDataEnd does too many things.
+str(self.factory.runningFetchers),'client')
+str(self.factory.runningFetchers),'Fetcher')
def apEnd(self): """ Called by subclasses when apDataEnd does too many things.
log.debug("have active Fetcher",'file_client')
log.debug("have active Fetcher",'Fetcher')
def apEndTransfer(self, fetcher_class): """ Remove this Fetcher and transfer all it's requests to a new instance of 'fetcher_class'. """ #Consider something like this: #req = dummyFetcher.fix_ref_request() #fetcher = fetcher_class() #dummyFetcher.transfer_requests(fetcher) #dummyFetcher.apEnd() #fetcher.activate(req)
log.debug("Connection Failed: "+str(reason))
log.debug("Connection Failed: "+str(reason), 'Fetcher')
def connectionFailed(self, reason=None): """ Tell our requests that the connection with the server failed. """ msg = '[%s] Connection Failed: %s/%s'%( self.request.backend.base, self.request.backendServer.path, self.request.backend_uri)
'client','9')
'Fetcher','9')
def connectionFailed(self, reason=None): """ Tell our requests that the connection with the server failed. """ msg = '[%s] Connection Failed: %s/%s'%( self.request.backend.base, self.request.backendServer.path, self.request.backend_uri)
request.transport.loseConnection
request.finish()
def start_transfer(self, request): self.if_modified(request) if len(self.requests) == 0: #we had a single request and didn't have to send it self.apEnd() return
def open_shelve(filename):
def open_shelve(dbname):
def open_shelve(filename): from bsddb3 import db,dbshelve
db_dir = self.cache_dir+'/'+status_dir+'/db' if not os.path.exists(db_dir): os.makedirs(db_dir)
def open_shelve(filename): from bsddb3 import db,dbshelve
self.update_times = open_shelve(db_dir+'/update.db')
self.update_times = open_shelve('update')
def open_shelve(filename): from bsddb3 import db,dbshelve
self.access_times = open_shelve(db_dir+'/access.db')
self.access_times = open_shelve('access')
def open_shelve(filename): from bsddb3 import db,dbshelve
self.packages = open_shelve(db_dir+'/packages.db')
self.packages = open_shelve('packages')
def open_shelve(filename): from bsddb3 import db,dbshelve
self.local_mtime = os.stat(self.host_file)[stat.ST_MTIME]
if os.path.exists(self.host_file): self.local_mtime = os.stat(self.host_file)[stat.ST_MTIME]
def host_transfer_done(self): """ Called by our LoopbackRequest when the real Fetcher calls finish() on it.
basic.FileSender().beginFileTransfer(file, request).addCallback(self.apEnd).addCallback(lambda r: file.close())
basic.FileSender().beginFileTransfer(file, request).addCallback(self.apEnd).addCallback(lambda r: file.close()).addCallback(lambda r: request.transport.loseConnection())
def insert_request(self, request): if not request.serve_if_cached: request.finish() return Fetcher.insert_request(self, request) self.if_modified(request) file = open(self.local_file,'rb') fcntl.lockf(file.fileno(), fcntl.LOCK_SH)
basic.FileSender().beginFileTransfer(file, self.request).addCallback(self.apEnd).addCallback(lambda r: file.close())
basic.FileSender().beginFileTransfer(file, self.request).addCallback(self.apEnd).addCallback(lambda r: file.close()).addCallback(lambda r: request.transport.loseConnection())
def activate(self, request): Fetcher.activate(self, request) if not request.apFetcher: return self.factory.file_served(request.uri)
FileType( re.compile(r"/(Packages|Release|Sources|Contents-.*)(\.(gz|bz2))?$"), "text/plain", 1),
FileType(re.compile(r"/(Packages|Release(\.gpg)?|Sources|Contents-.*)" r"(\.(gz|bz2))?$"), "text/plain", 1),
def check (self, name): "Returns true if name is of this filetype" if self.regex.search(name): return 1 else: return 0
import bsddb
from bsddb import dbshelve as old_dbshelve
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
previous_shelve = bsddb.dbshelve.open(filename + '.previous')
previous_shelve = old_dbshelve.open(filename + '.previous')
def open_shelve(filename): from bsddb3 import db,dbshelve log.debug('Opening database ' + filename)
def __fake_stdout(self): import tempfile null = tempfile.TemporaryFile() self.real_stdout_fd = os.dup(sys.stdout.fileno()) os.dup2(null.fileno(), sys.stdout.fileno())
def __save_stdout(self): self.real_stdout_fd = os.dup(1) os.close(1)
def __fake_stdout(self): import tempfile null = tempfile.TemporaryFile() self.real_stdout_fd = os.dup(sys.stdout.fileno()) os.dup2(null.fileno(), sys.stdout.fileno())
os.dup2(self.real_stdout_fd, sys.stdout.fileno())
os.dup2(self.real_stdout_fd, 1)
def __restore_stdout(self): os.dup2(self.real_stdout_fd, sys.stdout.fileno()) os.close(self.real_stdout_fd) del self.real_stdout_fd
self.cache = apt_pkg.GetCache()
if log.isEnabled('apt'): self.cache = apt_pkg.GetCache() else: self.__save_stdout() self.cache = apt_pkg.GetCache() self.__restore_stdout()
def load(self): """ Regenerates the fake configuration and load the packages server. """ if not self.loaded: shutil.rmtree(self.status_dir+'/apt/lists/') os.makedirs(self.status_dir+'/apt/lists/partial') sources = open(self.status_dir+'/'+'apt/etc/sources.list', 'w') for file in self.packages.keys(): # we should probab...
"Tryes to make the packages server quit."
"Tries to make the packages server quit."
def unload(self): "Tryes to make the packages server quit." if self.loaded: del self.cache del self.records self.loaded = 0
laterID = None file = None
def loseConnection(self): "Kill rsync process" if self.transport: if self.transport.pid: log.debug("killing rsync child" + str(self.transport.pid), 'rsync_client') os.kill(self.transport.pid, signal.SIGTERM) #self.transport.loseConnection()
self.file = open(self.local_file,'rb') fcntl.lockf(self.file.fileno(), fcntl.LOCK_SH)
file = open(self.local_file,'rb') fcntl.lockf(file.fileno(), fcntl.LOCK_SH)
def activate(self, request): Fetcher.activate(self, request) if not request.apFetcher: return self.factory.file_served(request.uri)
self.readBuffer() def readBuffer(self): self.laterID = None data = self.file.read(abstract.FileDescriptor.bufferSize) self.apDataReceived(data) if self.file.tell() == self.size: self.apDataReceived("") for req in self.requests: req.finish() self.apEnd() else: self.laterID = reactor.callLater(0, self.readBuffer) def ...
basic.FileSender().beginFileTransfer(file, self.request).addCallback(self.apEnd).addCallback(lambda r: file.close()) def apEnd(self, ignored=None): if len(self.requests) == 0: Fetcher.apEnd(self)
def activate(self, request): Fetcher.activate(self, request) if not request.apFetcher: return self.factory.file_served(request.uri)
'serve_cached': this is somewhat of a hack only usefull for
'serve_cached': this is somewhat of a hack only useful for
def fetch(self, serve_cached=1): """ Serve 'self' from cache or through the appropriate Fetcher depending on the asociated backend. Use post_convert and gzip_convert regular expresions of the Fetcher to gzip/gunzip file before and after download. 'serve_cached': this is somewhat of a hack only usefull for LoopbackReq...
"If he wanted to know, tell dady that we are served."
"If he wanted to know, tell daddy that we are served."
def finish(self): "If he wanted to know, tell dady that we are served." if self.finish_cb: self.finish_cb() self.transport = None pass
Each incomming request is passed to a new Request instance.
Each incoming request is passed to a new Request instance.
def finish(self): "If he wanted to know, tell dady that we are served." if self.finish_cb: self.finish_cb() self.transport = None pass
"If the connection is lost, notify all my requets"
"If the connection is lost, notify all my requests"
def connectionLost(self, reason=None): "If the connection is lost, notify all my requets" __pychecker__ = 'unusednames=reason' for req in self.requests: req.connectionLost() log.debug("Client connection closed") if log.isEnabled('memleak'): memleak.print_top_10()
if re.search('/../', self.uri):
if re.search('/\.\./', self.uri):
def process(self): """ Each new request begins processing here """ log.debug("Request: " + self.method + " " + self.uri); # Clean up URL self.uri = self.simplify_path(self.uri)
if (self.__class__ != FetcherFile or req.serve_if_cached):
if (fetcher_class != FetcherFile or req.serve_if_cached):
def apEndTransfer(self, fetcher_class): """ Remove this Fetcher and transfer all it's requests to a new instance of 'fetcher_class'. """ #Consider something like this: #req = dummyFetcher.fix_ref_request() #fetcher = fetcher_class() #dummyFetcher.transfer_requests(fetcher) #dummyFetcher.apEnd() #fetcher.activate(req)
def activate(self, request):
def activate(self, request, postconverting=0):
def activate(self, request): Fetcher.activate(self, request) if not request.apFetcher: return
loop = LoopbackRequest(request, self.host_transfer_done) loop.uri = host_uri loop.local_file = self.host_file loop.process() self.loop_req = loop loop.fetch(serve_cached=0)
running = self.factory.runningFetchers if not postconverting or running.has_key(self.host_file): loop = LoopbackRequest(request, self.host_transfer_done) loop.uri = host_uri loop.local_file = self.host_file loop.process() self.loop_req = loop loop.serve_if_cached=0 if running.has_key(self.host_file): running[self.hos...
def activate(self, request): Fetcher.activate(self, request) if not request.apFetcher: return
if self.loop_req.code != http.OK:
if self.loop_req and self.loop_req.code != http.OK:
def host_transfer_done(self): """ Called by our LoopbackRequest when the real Fetcher calls finish() on it.
post_convert = re.compile(r"^Should not match anything$") gzip_convert = post_convert
post_convert = re.compile(r"/Packages.gz$") gzip_convert = re.compile(r"^Should not match anything$")
def processEnded(self, reason=None): log.debug("Status: %d" %(self.process.status),'rsync_client') if self.process.status != 0: self.setResponseCode(http.NOT_FOUND) if not os.path.exists(self.local_file): try: os.removedirs(self.local_dir) except: pass
print "CONVERT:", fetcher.post_convert
def fetch_real(result, dummyFetcher, cached, running): """ This is called after verifying if the file is properly cached. If 'cached' the requested file is properly cached. If not 'cached' the requested file was not there, didn't pass the integrity check or may be outdated. """ if len(dummyFetcher.requests)==0: #The r...
FetcherGzip(loop)
gzip = FetcherGzip() gzip.activate(loop, postconverting=1)
def fetch_real(result, dummyFetcher, cached, running): """ This is called after verifying if the file is properly cached. If 'cached' the requested file is properly cached. If not 'cached' the requested file was not there, didn't pass the integrity check or may be outdated. """ if len(dummyFetcher.requests)==0: #The r...
log.debug("have active fetcher",'client')
log.debug("have active fetcher: "+self.uri,'client')
def fetch_real(result, dummyFetcher, cached, running): """ This is called after verifying if the file is properly cached. If 'cached' the requested file is properly cached. If not 'cached' the requested file was not there, didn't pass the integrity check or may be outdated. """ if len(dummyFetcher.requests)==0: #The r...
creator = ClientCreator(reactor, ftp.FTPClient, passive=0)
if not request.backend.username: creator = ClientCreator(reactor, ftp.FTPClient, passive=0) else: creator = ClientCreator(reactor, ftp.FTPClient, request.backend.username, request.backend.password, passive=0)
def activate (self, request): Fetcher.activate(self, request) if not request.apFetcher: return
for k previous_shelve.keys():
for k in previous_shelve.keys():
def open_shelve(filename): from bsddb3 import db,dbshelve,DBInvalidArgError log.debug('Opening database ' + filename)
moderated = self.getValueFor('moderated')
moderated = group.getValueFor('moderated')
def send_email(self, REQUEST, RESPONSE, group_id, email_address, email_id, message, subject=''): """ Send an email to the group. """ list_manager = self.get_xwfMailingListManager() sec = getSecurityManager() user = sec.getUser() if email_address not in user.get_emailAddresses(): raise 'Forbidden', 'Only the authent...
subject = 'Re: %s' % orig_email.getProperty('subject')
subject = 'Re: %s' % orig_email.getProperty('mailSubject')
def send_email(self, REQUEST, RESPONSE, group_id, email_address, email_id, message, subject=''): """ Send an email to the group. We send the email via the mail server so it will handle things like message ID's for us. """ list_manager = self.get_xwfMailingListManager() sec = getSecurityManager() user = sec.getUser...
class GSBaseMessageView(Products.Five.BrowserView):
class GSNewTopicView(Products.Five.BrowserView, GSGroupObject):
def get_group_info(self): assert self.__groupInfo retval = self.__groupInfo assert retval return retval
self.set_archive(self.context.messages) self.set_emailId(self.context.REQUEST.form.get('id', None)) self.init_email() self.init_topic() assert self.archive assert self.emailId assert self.email assert self.topic def set_archive(self, archive): """Set the email message archive to "archive".""" assert archive self.arch...
def __init__(self, context, request): # Preconditions assert context assert request Products.Five.BrowserView.__init__(self, context, request) self.set_archive(self.context.messages) self.set_emailId(self.context.REQUEST.form.get('id', None)) self.init_email() self.init_topic() # Postconditions assert self.archive as...
self.init_threads() def init_threads(self): assert self.topic assert self.archive self.threads = self.archive.get_all_threads({}, 'mailDate', 'asc') self.threadNames = map(lambda thread: thread[1][0]['mailSubject'], self.threads) currThreadName = self.get_topic_name() assert currThreadName in self.threadNames self.c...
def __init__(self, context, request): # Preconditions assert context assert request GSBaseMessageView.__init__(self, context, request) GSGroupObject.__init__(self, context) self.init_threads()
pp = '/'.join(indexable.getPhysicalPath())
pp = '/'.join(object.getPhysicalPath())
def reindex_mailObjects(self): """ Reindex the mailObjects that we contain. """ for object in self.archive.objectValues('Folder'): if hasattr(object, 'mailFrom'): pp = '/'.join(indexable.getPhysicalPath()) self.Catalog.uncatalog_object(pp) self.Catalog.catalog_object(indexable, pp) return indexables