X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ian/git?p=hippotat.git;a=blobdiff_plain;f=hippotat%2F__init__.py;h=60b779f1dcb3253bbe4b9011a1c671004c7d6483;hp=43f4a49b157329312e64e1a0ee5e559190d15aa4;hb=82302bac58d04aa04390ed0d8baebb15bf79829f;hpb=0accf0d39d4758f5f9ccb960101771f8f666d9ff diff --git a/hippotat/__init__.py b/hippotat/__init__.py index 43f4a49..60b779f 100644 --- a/hippotat/__init__.py +++ b/hippotat/__init__.py @@ -4,6 +4,9 @@ import signal signal.signal(signal.SIGINT, signal.SIG_DFL) import sys +import os + +from zope.interface import implementer import twisted from twisted.internet import reactor @@ -17,9 +20,12 @@ import ipaddress from ipaddress import AddressValueError from optparse import OptionParser +import configparser from configparser import ConfigParser from configparser import NoOptionError +from functools import partial + import collections import time import codecs @@ -30,42 +36,75 @@ import re as regexp import hippotat.slip as slip class DBG(twisted.python.constants.Names): + INIT = NamedConstant() + CONFIG = NamedConstant() ROUTE = NamedConstant() DROP = NamedConstant() FLOW = NamedConstant() HTTP = NamedConstant() - HTTP_CTRL = NamedConstant() - INIT = NamedConstant() + TWISTED = NamedConstant() QUEUE = NamedConstant() + HTTP_CTRL = NamedConstant() QUEUE_CTRL = NamedConstant() HTTP_FULL = NamedConstant() - SLIP_FULL = NamedConstant() CTRL_DUMP = NamedConstant() + SLIP_FULL = NamedConstant() + DATA_COMPLETE = NamedConstant() _hex_codec = codecs.getencoder('hex_codec') +#---------- logging ---------- + +org_stderr = sys.stderr + log = twisted.logger.Logger() +debug_set = set() +debug_def_detail = DBG.HTTP + def log_debug(dflag, msg, idof=None, d=None): + if dflag not in debug_set: return #print('---------------->',repr((dflag, msg, idof, d)), file=sys.stderr) if idof is not None: - msg = '[%d] %s' % (id(idof), msg) + msg = '[%#x] %s' % (id(idof), msg) if d is not None: - d = d[0:64] + trunc = '' + if not DBG.DATA_COMPLETE in debug_set: + if len(d) > 64: + d = d[0:64] + trunc = '...' d = _hex_codec(d)[0].decode('ascii') - msg += ' ' + d + msg += ' ' + d + trunc log.info('{dflag} {msgcore}', dflag=dflag, msgcore=msg) +@implementer(twisted.logger.ILogFilterPredicate) +class LogNotBoringTwisted: + def __call__(self, event): + yes = twisted.logger.PredicateResult.yes + no = twisted.logger.PredicateResult.no + try: + if event.get('log_level') != LogLevel.info: + return yes + dflag = event.get('dflag') + if dflag in debug_set: return yes + if dflag is None and DBG.TWISTED in debug_set: return yes + return no + except Exception: + print(traceback.format_exc(), file=org_stderr) + return yes + +#---------- default config ---------- + defcfg = ''' [DEFAULT] #[] overrides max_batch_down = 65536 # used by server, subject to [limits] max_queue_time = 10 # used by server, subject to [limits] -max_request_time = 54 # used by server, subject to [limits] target_requests_outstanding = 3 # must match; subject to [limits] on server +http_timeout = 30 # used by both } must be +http_timeout_grace = 5 # used by both } compatible max_requests_outstanding = 4 # used by client max_batch_up = 4000 # used by client -http_timeout = 30 # used by client http_retry = 5 # used by client #[server] or [] overrides @@ -94,12 +133,12 @@ port = 80 # used by server [limits] max_batch_down = 262144 # used by server max_queue_time = 121 # used by server -max_request_time = 121 # used by server +http_timeout = 121 # used by server target_requests_outstanding = 10 # used by server ''' # these need to be defined here so that they can be imported by import * -cfg = ConfigParser() +cfg = ConfigParser(strict=False) optparser = OptionParser() _mimetrans = bytes.maketrans(b'-'+slip.esc, slip.esc+b'-') @@ -169,9 +208,8 @@ class SlipStreamDecoder(): def inputdata(self, data): self._log('inputdata', d=data) - data = self._buffer + data - self._buffer = b'' packets = slip.decode(data) + packets[0] = self._buffer + packets[0] self._buffer = packets.pop() for packet in packets: self._maybe_packet(packet) @@ -286,7 +324,8 @@ _crashing = False def crash(err): global _crashing _crashing = True - print('CRASH ', err, file=sys.stderr) + print('========== CRASH ==========', err, + '===========================', file=sys.stderr) try: reactor.stop() except twisted.internet.error.ReactorNotRunning: pass @@ -365,21 +404,140 @@ def process_cfg_clients(constructor): #---------- startup ---------- -def common_startup(): - log_formatter = twisted.logger.formatEventAsClassicLogText - log_observer = twisted.logger.FileLogObserver(sys.stderr, log_formatter) - twisted.logger.globalLogBeginner.beginLoggingTo( - [ log_observer, crash_on_critical ] - ) +def common_startup(process_cfg): + # ConfigParser hates #-comments after values + trailingcomments_re = regexp.compile('#.*') + 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) - optparser.add_option('-c', '--config', dest='configfile', - default='/etc/hippotat/config') (opts, args) = optparser.parse_args() if len(args): optparser.error('no non-option arguments please') - re = regexp.compile('#.*') - cfg.read_string(re.sub('', defcfg)) - cfg.read(opts.configfile) + if need_defcfg: + readconfig('/etc/hippotat/config', False) + readconfig('/etc/hippotat/config.d', False) + + try: process_cfg() + 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')