+ def process(self, sizequery, moredata, max_batch):
+ # sizequery() should return size of batch so far
+ # moredata(s) should add s to batch
+ self._log(DBG.QUEUE, 'process...')
+ while True:
+ try: (dummy, packet) = self._pq[0]
+ except IndexError:
+ self._log(DBG.QUEUE, 'process... empty')
+ break
+
+ self._log(DBG.QUEUE_CTRL, 'process... packet', d=packet)
+
+ encoded = slip.encode(packet)
+ sofar = sizequery()
+
+ self._log(DBG.QUEUE_CTRL,
+ 'process... (sofar=%d, max=%d) encoded' % (sofar, max_batch),
+ d=encoded)
+
+ if sofar > 0:
+ if sofar + len(slip.delimiter) + len(encoded) > max_batch:
+ self._log(DBG.QUEUE_CTRL, 'process... overflow')
+ break
+ moredata(slip.delimiter)
+
+ moredata(encoded)
+ self._pq.popleft()
+
+#---------- error handling ----------
+
+_crashing = False
+
+def crash(err):
+ global _crashing
+ _crashing = True
+ print('========== CRASH ==========', err,
+ '===========================', file=sys.stderr)
+ try: reactor.stop()
+ except twisted.internet.error.ReactorNotRunning: pass
+
+def crash_on_defer(defer):
+ defer.addErrback(lambda err: crash(err))
+
+def crash_on_critical(event):
+ if event.get('log_level') >= LogLevel.critical:
+ crash(twisted.logger.formatEvent(event))
+
+#---------- config processing ----------
+
+def _cfg_process_putatives():
+ servers = { }
+ clients = { }
+ # maps from abstract object to canonical name for cs's
+
+ def putative(cmap, abstract, canoncs):
+ try:
+ current_canoncs = cmap[abstract]
+ except KeyError:
+ pass
+ else:
+ assert(current_canoncs == canoncs)
+ cmap[abstract] = canoncs
+
+ server_pat = r'[-.0-9A-Za-z]+'
+ client_pat = r'[.:0-9a-f]+'
+ server_re = regexp.compile(server_pat)
+ serverclient_re = regexp.compile(server_pat + r' ' + client_pat)
+
+ for cs in cfg.sections():
+ if cs == 'LIMIT':
+ # plan A "[LIMIT]"
+ continue
+
+ try:
+ # plan B "[<client>]" part 1
+ ci = ipaddr(cs)
+ except AddressValueError:
+
+ if server_re.fullmatch(cs):
+ # plan C "[<servername>]"
+ putative(servers, cs, cs)
+ continue
+
+ if serverclient_re.fullmatch(cs):
+ # plan D "[<servername> <client>]" part 1
+ (pss,pcs) = cs.split(' ')
+
+ if pcs == 'LIMIT':
+ # plan E "[<servername> LIMIT]"
+ continue
+
+ try:
+ # plan D "[<servername> <client>]" part 2
+ ci = ipaddr(pc)
+ except AddressValueError:
+ # plan F "[<some thing we do not understand>]"
+ # well, we ignore this
+ print('warning: ignoring config section %s' % cs, file=sys.stderr)
+ continue
+
+ else: # no AddressValueError
+ # plan D "[<servername> <client]" part 3
+ putative(clients, ci, pcs)
+ putative(servers, pss, pss)
+ continue
+
+ else: # no AddressValueError
+ # plan B "[<client>" part 2
+ putative(clients, ci, cs)
+ continue
+
+ return (servers, clients)
+
+def cfg_process_common(ss):
+ c.mtu = cfg.getint(ss, 'mtu')
+
+def cfg_process_saddrs(c, ss):
+ class ServerAddr():
+ def __init__(self, port, addrspec):
+ self.port = port
+ # also self.addr
+ try:
+ self.addr = ipaddress.IPv4Address(addrspec)
+ self._endpointfactory = twisted.internet.endpoints.TCP4ServerEndpoint
+ self._inurl = b'%s'
+ except AddressValueError:
+ self.addr = ipaddress.IPv6Address(addrspec)
+ self._endpointfactory = twisted.internet.endpoints.TCP6ServerEndpoint
+ self._inurl = b'[%s]'
+ def make_endpoint(self):
+ return self._endpointfactory(reactor, self.port, self.addr)
+ def url(self):
+ url = b'http://' + (self._inurl % str(self.addr).encode('ascii'))
+ if self.port != 80: url += b':%d' % self.port
+ url += b'/'
+ return url
+
+ c.port = cfg.getint(ss,'port')
+ c.saddrs = [ ]
+ for addrspec in cfg.get(ss, 'addrs').split():
+ sa = ServerAddr(c.port, addrspec)
+ c.saddrs.append(sa)
+
+def cfg_process_vnetwork(c, ss):
+ c.vnetwork = ipnetwork(cfg.get(ss,'vnetwork'))
+ if c.vnetwork.num_addresses < 3 + 2:
+ raise ValueError('vnetwork needs at least 2^3 addresses')
+
+def cfg_process_vaddr(c, ss):
+ try:
+ c.vaddr = cfg.get(ss,'vaddr')
+ except NoOptionError:
+ cfg_process_vnetwork(c, ss)
+ c.vaddr = next(c.vnetwork.hosts())
+
+def cfg_search_section(key,sections):
+ for section in sections:
+ if cfg.has_option(section, key):
+ return section
+ raise NoOptionError(key, repr(sections))
+
+def cfg_search(getter,key,sections):
+ section = cfg_search_section(key,sections)
+ return getter(section, key)
+
+def cfg_process_client_limited(cc,ss,sections,key):
+ val = cfg_search(cfg.getint, key, sections)
+ lim = cfg_search(cfg.getint, key, ['%s LIMIT' % ss, 'LIMIT'])
+ cc.__dict__[key] = min(val,lim)
+
+def cfg_process_client_common(cc,ss,cs,ci):
+ # returns sections to search in, iff password is defined, otherwise None
+ cc.ci = ci
+
+ sections = ['%s %s' % (ss,cs),
+ cs,
+ ss,
+ 'DEFAULT']
+
+ try: pwsection = cfg_search_section('password', sections)
+ except NoOptionError: return None
+
+ pw = cfg.get(pwsection, 'password')
+ cc.password = pw.encode('utf-8')
+
+ cfg_process_client_limited(cc,ss,sections,'target_requests_outstanding')
+ cfg_process_client_limited(cc,ss,sections,'http_timeout')
+
+ return sections
+
+def cfg_process_ipif(c, sections, varmap):
+ for d, s in varmap:
+ try: v = getattr(c, s)
+ except AttributeError: continue
+ setattr(c, d, v)
+
+ #print('CFGIPIF',repr((varmap, sections, c.__dict__)),file=sys.stderr)
+
+ section = cfg_search_section('ipif', sections)
+ c.ipif_command = cfg.get(section,'ipif', vars=c.__dict__)
+
+#---------- startup ----------
+
+def common_startup(process_cfg):
+ # calls process_cfg(putative_clients, putative_servers)
+
+ # ConfigParser hates #-comments after values
+ trailingcomments_re = regexp.compile(r'#.*')
+ cfg.read_string(trailingcomments_re.sub('', defcfg))
+ need_defcfg = True
+
+ def readconfig(pathname, mandatory=True):
+ def log(m, p=pathname):
+ if not DBG.CONFIG in debug_set: return
+ print('DBG.CONFIG: %s: %s' % (m, pathname))
+
+ try:
+ files = os.listdir(pathname)
+
+ except FileNotFoundError:
+ if mandatory: raise
+ log('skipped')
+ return
+
+ except NotADirectoryError:
+ cfg.read(pathname)
+ log('read file')
+ return
+
+ # is a directory
+ log('directory')
+ re = regexp.compile('[^-A-Za-z0-9_]')
+ for f in os.listdir(cdir):
+ if re.search(f): continue
+ subpath = pathname + '/' + f
+ try:
+ os.stat(subpath)
+ except FileNotFoundError:
+ log('entry skipped', subpath)
+ continue
+ cfg.read(subpath)
+ log('entry read', subpath)
+
+ def oc_config(od,os, value, op):
+ nonlocal need_defcfg
+ need_defcfg = False
+ readconfig(value)
+
+ def dfs_less_detailed(dl):
+ return [df for df in DBG.iterconstants() if df <= dl]
+
+ def ds_default(od,os,dl,op):
+ global debug_set
+ debug_set = set(dfs_less_detailed(debug_def_detail))
+
+ def ds_select(od,os, spec, op):
+ for it in spec.split(','):
+
+ if it.startswith('-'):
+ mutator = debug_set.discard
+ it = it[1:]
+ else:
+ mutator = debug_set.add
+
+ if it == '+':
+ dfs = DBG.iterconstants()
+
+ else:
+ if it.endswith('+'):
+ mapper = dfs_less_detailed
+ it = it[0:len(it)-1]
+ else:
+ mapper = lambda x: [x]
+
+ try:
+ dfspec = DBG.lookupByName(it)
+ except ValueError:
+ optparser.error('unknown debug flag %s in --debug-select' % it)
+
+ dfs = mapper(dfspec)
+
+ for df in dfs:
+ mutator(df)
+
+ optparser.add_option('-D', '--debug',
+ nargs=0,
+ action='callback',
+ help='enable default debug (to stdout)',
+ callback= ds_default)
+
+ optparser.add_option('--debug-select',
+ nargs=1,
+ type='string',
+ metavar='[-]DFLAG[+]|[-]+,...',
+ help=
+'''enable (`-': disable) each specified DFLAG;
+`+': do same for all "more interesting" DFLAGSs;
+just `+': all DFLAGs.
+ DFLAGS: ''' + ' '.join([df.name for df in DBG.iterconstants()]),
+ action='callback',
+ callback= ds_select)
+
+ optparser.add_option('-c', '--config',
+ nargs=1,
+ type='string',
+ metavar='CONFIGFILE',
+ dest='configfile',
+ action='callback',
+ callback= oc_config)
+
+ (opts, args) = optparser.parse_args()
+ if len(args): optparser.error('no non-option arguments please')
+
+ if need_defcfg:
+ readconfig('/etc/hippotat/config', False)
+ readconfig('/etc/hippotat/config.d', False)
+
+ try:
+ (pss, pcs) = _cfg_process_putatives()
+ process_cfg(pss, pcs)
+ except (configparser.Error, ValueError):
+ traceback.print_exc(file=sys.stderr)
+ print('\nInvalid configuration, giving up.', file=sys.stderr)
+ sys.exit(12)
+
+ #print(repr(debug_set), file=sys.stderr)
+
+ log_formatter = twisted.logger.formatEventAsClassicLogText
+ stdout_obs = twisted.logger.FileLogObserver(sys.stdout, log_formatter)
+ stderr_obs = twisted.logger.FileLogObserver(sys.stderr, log_formatter)
+ pred = twisted.logger.LogLevelFilterPredicate(LogLevel.error)
+ stdsomething_obs = twisted.logger.FilteringLogObserver(
+ stderr_obs, [pred], stdout_obs
+ )
+ log_observer = twisted.logger.FilteringLogObserver(
+ stdsomething_obs, [LogNotBoringTwisted()]
+ )
+ #log_observer = stdsomething_obs
+ twisted.logger.globalLogBeginner.beginLoggingTo(
+ [ log_observer, crash_on_critical ]
+ )
+
+def common_run():
+ log_debug(DBG.INIT, 'entering reactor')
+ if not _crashing: reactor.run()
+ print('CRASHED (end)', file=sys.stderr)