0ef24b1937 2011-04-06 1: #!/usr/bin/env python
0ef24b1937 2011-04-06 2:
0ef24b1937 2011-04-06 3: from __future__ import division, print_function, unicode_literals
0ef24b1937 2011-04-06 4:
0ef24b1937 2011-04-06 5: import gevent.monkey
0ef24b1937 2011-04-06 6: gevent.monkey.patch_all()
0ef24b1937 2011-04-06 7:
0ef24b1937 2011-04-06 8: import fcntl, gevent.core, gevent.pool, gevent.queue, gevent.socket, os, psycopg2, re, sys
0ef24b1937 2011-04-06 9:
0ef24b1937 2011-04-06 10: # //inclusion start
0ef24b1937 2011-04-06 11: # Copyright (C) 2010 Daniele Varrazzo <daniele.varrazzo@gmail.com>
0ef24b1937 2011-04-06 12: # and licensed under the MIT license:
0ef24b1937 2011-04-06 13:
0ef24b1937 2011-04-06 14: def gevent_wait_callback(conn, timeout=None):
0ef24b1937 2011-04-06 15: """A wait callback useful to allow gevent to work with Psycopg."""
0ef24b1937 2011-04-06 16: while 1:
0ef24b1937 2011-04-06 17: state = conn.poll()
0ef24b1937 2011-04-06 18: if state == psycopg2.extensions.POLL_OK:
0ef24b1937 2011-04-06 19: break
0ef24b1937 2011-04-06 20: elif state == psycopg2.extensions.POLL_READ:
0ef24b1937 2011-04-06 21: gevent.socket.wait_read(conn.fileno(), timeout=timeout)
0ef24b1937 2011-04-06 22: elif state == psycopg2.extensions.POLL_WRITE:
0ef24b1937 2011-04-06 23: gevent.socket.wait_write(conn.fileno(), timeout=timeout)
0ef24b1937 2011-04-06 24: else:
0ef24b1937 2011-04-06 25: raise psycopg2.OperationalError("Bad result from poll: %r" % state)
0ef24b1937 2011-04-06 26:
0ef24b1937 2011-04-06 27: if not hasattr(psycopg2.extensions, 'set_wait_callback'):
0ef24b1937 2011-04-06 28: raise ImportError("support for coroutines not available in this Psycopg version (%s)" % psycopg2.__version__)
0ef24b1937 2011-04-06 29: psycopg2.extensions.set_wait_callback(gevent_wait_callback)
0ef24b1937 2011-04-06 30:
0ef24b1937 2011-04-06 31: # //inclusion end
fc934cead1 2009-10-13 32:
fc934cead1 2009-10-13 33: # this classes processes config file and substitutes default values
fc934cead1 2009-10-13 34: class Config:
ae30851739 2010-08-12 35: __slots__ = frozenset(['_config', '_default', '_section', 'options'])
b93dc49210 2009-10-13 36: _default = {
fc934cead1 2009-10-13 37: 'log': {
fc934cead1 2009-10-13 38: 'silent': 'no',
fc934cead1 2009-10-13 39: },
fc934cead1 2009-10-13 40: 'database': {
fc934cead1 2009-10-13 41: 'database': 'squidTag',
fc934cead1 2009-10-13 42: },}
fc934cead1 2009-10-13 43:
fc934cead1 2009-10-13 44: # function to read in config file
fc934cead1 2009-10-13 45: def __init__(self):
0ef24b1937 2011-04-06 46: import ConfigParser, optparse, os
ae30851739 2010-08-12 47:
d500448801 2009-10-05 48: parser = optparse.OptionParser()
d500448801 2009-10-05 49: parser.add_option('-c', '--config', dest = 'config',
d500448801 2009-10-05 50: help = 'config file location', metavar = 'FILE',
d500448801 2009-10-05 51: default = '/usr/local/etc/squid-tagger.conf')
ae30851739 2010-08-12 52: parser.add_option('-d', '--dump', dest = 'dump',
ae30851739 2010-08-12 53: help = 'dump database', action = 'store_true', metavar = 'bool',
ae30851739 2010-08-12 54: default = False)
31e69c4237 2010-08-12 55: parser.add_option('-f', '--flush-database', dest = 'flush_db',
31e69c4237 2010-08-12 56: help = 'flush previous database on load', default = False,
31e69c4237 2010-08-12 57: action = 'store_true', metavar = 'bool')
31e69c4237 2010-08-12 58: parser.add_option('-l', '--load', dest = 'load',
31e69c4237 2010-08-12 59: help = 'load database', action = 'store_true', metavar = 'bool',
31e69c4237 2010-08-12 60: default = False)
d301d9adc6 2010-08-13 61: parser.add_option('-D', '--dump-conf', dest = 'dump_conf',
d301d9adc6 2010-08-13 62: help = 'dump filtering rules', default = False, metavar = 'bool',
d301d9adc6 2010-08-13 63: action = 'store_true')
d301d9adc6 2010-08-13 64: parser.add_option('-L', '--load-conf', dest = 'load_conf',
d301d9adc6 2010-08-13 65: help = 'load filtering rules', default = False, metavar = 'bool',
d301d9adc6 2010-08-13 66: action = 'store_true')
7c13294e9f 2010-08-07 67:
ae30851739 2010-08-12 68: (self.options, args) = parser.parse_args()
7c13294e9f 2010-08-07 69:
ae30851739 2010-08-12 70: assert os.access(self.options.config, os.R_OK), "Fatal error: can't read {}".format(self.options.config)
7c13294e9f 2010-08-07 71:
0ef24b1937 2011-04-06 72: self._config = ConfigParser.ConfigParser()
ae30851739 2010-08-12 73: self._config.readfp(open(self.options.config))
fc934cead1 2009-10-13 74:
fc934cead1 2009-10-13 75: # function to select config file section or create one
d500448801 2009-10-05 76: def section(self, section):
fc934cead1 2009-10-13 77: if not self._config.has_section(section):
fc934cead1 2009-10-13 78: self._config.add_section(section)
d500448801 2009-10-05 79: self._section = section
d500448801 2009-10-05 80:
fc934cead1 2009-10-13 81: # function to get config parameter, if parameter doesn't exists the default
fc934cead1 2009-10-13 82: # value or None is substituted
d500448801 2009-10-05 83: def __getitem__(self, name):
fc934cead1 2009-10-13 84: if not self._config.has_option(self._section, name):
b93dc49210 2009-10-13 85: if self._section in self._default:
b93dc49210 2009-10-13 86: if name in self._default[self._section]:
fc934cead1 2009-10-13 87: self._config.set(self._section, name, self._default[self._section][name])
fc934cead1 2009-10-13 88: else:
fc934cead1 2009-10-13 89: self._config.set(self._section, name, None)
fc934cead1 2009-10-13 90: else:
fc934cead1 2009-10-13 91: self._config.set(self._section, name, None)
b93dc49210 2009-10-13 92: return(self._config.get(self._section, name))
d500448801 2009-10-05 93:
fc934cead1 2009-10-13 94: # initializing and reading in config file
d500448801 2009-10-05 95: config = Config()
d500448801 2009-10-05 96:
fad48b740c 2012-07-07 97: import logging, logging.handlers
2654b86697 2012-07-09 98:
2654b86697 2012-07-09 99: # wrapper around logging handler to make it queue records and don't stall when sending them
2654b86697 2012-07-09 100:
2654b86697 2012-07-09 101: class SysLogHandlerQueue(logging.handlers.SysLogHandler):
67e8b3309d 2012-07-09 102: __slots__ = frozenset(['_running', '_tail', '_worker'])
2654b86697 2012-07-09 103:
2654b86697 2012-07-09 104: def __init__(self):
2654b86697 2012-07-09 105: logging.handlers.SysLogHandler.__init__(self, '/dev/log')
2654b86697 2012-07-09 106: self._tail = gevent.queue.Queue()
67e8b3309d 2012-07-09 107: self._worker = None
2654b86697 2012-07-09 108:
2654b86697 2012-07-09 109: def emit(self, record):
2654b86697 2012-07-09 110: # my syslog is broken and cannot into UTF-8 BOM
2654b86697 2012-07-09 111: record.msg = str(record.msg)
2654b86697 2012-07-09 112: self._tail.put(record)
67e8b3309d 2012-07-09 113: if self._worker == None:
2654b86697 2012-07-09 114: # in case queue is empty we will spawn new worker
2654b86697 2012-07-09 115: # all workers are logged so we can kill them on close()
67e8b3309d 2012-07-09 116: self._worker = gevent.spawn(self._writer)
2654b86697 2012-07-09 117:
2654b86697 2012-07-09 118: def _writer(self):
2654b86697 2012-07-09 119: # here we are locking the queue so we can be sure we are the only one
67e8b3309d 2012-07-09 120: print('syslog start')
2654b86697 2012-07-09 121: while not self._tail.empty():
2654b86697 2012-07-09 122: logging.handlers.SysLogHandler.emit(self, self._tail.get())
67e8b3309d 2012-07-09 123: self._worker = None
67e8b3309d 2012-07-09 124: print('syslog end')
2654b86697 2012-07-09 125:
2654b86697 2012-07-09 126: def close(self):
67e8b3309d 2012-07-09 127: if self._worker != None:
67e8b3309d 2012-07-09 128: gevent.kill(self._worker)
2654b86697 2012-07-09 129: logging.handlers.SysLogHandler.close(self)
2654b86697 2012-07-09 130:
fad48b740c 2012-07-07 131: logger = logging.getLogger('squidTag')
fad48b740c 2012-07-07 132: logger.setLevel(logging.INFO)
2654b86697 2012-07-09 133: handler = SysLogHandlerQueue()
fad48b740c 2012-07-07 134: handler.setFormatter(logging.Formatter(str('squidTag[%(process)s]: %(message)s')))
fad48b740c 2012-07-07 135: logger.addHandler(handler)
39b97ced92 2011-06-05 136:
39b97ced92 2011-06-05 137: # tiny wrapper around a file to make reads from it geventable
39b97ced92 2011-06-05 138: # or should i move this somewhere?
39b97ced92 2011-06-05 139:
39b97ced92 2011-06-05 140: class FReadlineQueue(gevent.queue.Queue):
39b97ced92 2011-06-05 141: # storing file descriptor, leftover
67e8b3309d 2012-07-09 142: __slots__ = frozenset(['_io', '_fileno', '_tail'])
39b97ced92 2011-06-05 143:
67e8b3309d 2012-07-09 144: def __init__(self, fd, closefd = True):
67e8b3309d 2012-07-09 145: import io
39b97ced92 2011-06-05 146: # initialising class
39b97ced92 2011-06-05 147: gevent.queue.Queue.__init__(self)
39b97ced92 2011-06-05 148: # storing file descriptor
67e8b3309d 2012-07-09 149: self._fileno = fd.fileno()
67e8b3309d 2012-07-09 150: self._io = io.FileIO(self._fileno, 'r', closefd)
39b97ced92 2011-06-05 151: # using empty tail
39b97ced92 2011-06-05 152: self._tail = ''
39b97ced92 2011-06-05 153: # setting up event
39b97ced92 2011-06-05 154: self._install_wait()
39b97ced92 2011-06-05 155:
39b97ced92 2011-06-05 156: def _install_wait(self):
39b97ced92 2011-06-05 157: # putting file to nonblocking mode
67e8b3309d 2012-07-09 158: fcntl.fcntl(self._fileno, fcntl.F_SETFL, fcntl.fcntl(self._fileno, fcntl.F_GETFL) | os.O_NONBLOCK)
39b97ced92 2011-06-05 159: # installing event handler
67e8b3309d 2012-07-09 160: gevent.core.read_event(self._fileno, self._wait_helper)
39b97ced92 2011-06-05 161:
39b97ced92 2011-06-05 162: def _wait_helper(self, ev, evtype):
39b97ced92 2011-06-05 163: # reading one buffer from stream
67e8b3309d 2012-07-09 164: buf = self._io.read(4096)
39b97ced92 2011-06-05 165: # splitting stream by line ends
39b97ced92 2011-06-05 166: rows = buf.decode('l1').split('\n')
39b97ced92 2011-06-05 167: # adding tail to the first element if there is some tail
39b97ced92 2011-06-05 168: if len(self._tail) > 0:
39b97ced92 2011-06-05 169: rows[0] = self._tail + rows[0]
39b97ced92 2011-06-05 170: # popping out last (incomplete) element
39b97ced92 2011-06-05 171: self._tail = rows.pop(-1)
39b97ced92 2011-06-05 172: # dropping all complete elements to the queue
39b97ced92 2011-06-05 173: for row in rows:
39b97ced92 2011-06-05 174: self.put_nowait(row)
2654b86697 2012-07-09 175: logger.info('< ' + row)
39b97ced92 2011-06-05 176: if len(buf) > 0:
39b97ced92 2011-06-05 177: # no EOF, reinstalling event handler
67e8b3309d 2012-07-09 178: gevent.core.read_event(self._fileno, self._wait_helper)
39b97ced92 2011-06-05 179: else:
39b97ced92 2011-06-05 180: # EOF found, sending EOF to queue
39b97ced92 2011-06-05 181: self.put_nowait(None)
39b97ced92 2011-06-05 182:
67e8b3309d 2012-07-09 183: stdin = FReadlineQueue(sys.stdin, False)
2654b86697 2012-07-09 184:
2654b86697 2012-07-09 185: # wrapper against file handler that makes possible to queue some writes without stalling
d823fa83dd 2012-07-07 186:
d823fa83dd 2012-07-07 187: class FWritelineQueue(gevent.queue.JoinableQueue):
d823fa83dd 2012-07-07 188: # storing fileno, io interface, leftover
d823fa83dd 2012-07-07 189: __slots__ = frozenset(['_fileno', '_io', '_tail'])
d823fa83dd 2012-07-07 190:
d823fa83dd 2012-07-07 191: def __init__(self, fd, closefd = True):
d823fa83dd 2012-07-07 192: import io
d823fa83dd 2012-07-07 193: # initialising class
d823fa83dd 2012-07-07 194: gevent.queue.JoinableQueue.__init__(self)
d823fa83dd 2012-07-07 195: # storing fileno
d823fa83dd 2012-07-07 196: self._fileno = fd.fileno()
d823fa83dd 2012-07-07 197: # creating interface
d823fa83dd 2012-07-07 198: self._io = io.FileIO(self._fileno, 'w', closefd)
d823fa83dd 2012-07-07 199: # using empty tail
d823fa83dd 2012-07-07 200: self._tail = None
d823fa83dd 2012-07-07 201: # putting file to nonblocking mode
d823fa83dd 2012-07-07 202: fcntl.fcntl(self._fileno, fcntl.F_SETFL, fcntl.fcntl(self._fileno, fcntl.F_GETFL) | os.O_NONBLOCK)
d823fa83dd 2012-07-07 203:
d823fa83dd 2012-07-07 204: def __del__(self):
d823fa83dd 2012-07-07 205: # purge queue before deleting
d823fa83dd 2012-07-07 206: if not self.empty():
d823fa83dd 2012-07-07 207: self.join()
d823fa83dd 2012-07-07 208:
d823fa83dd 2012-07-07 209: def put(self, item, block=True, timeout=None):
d823fa83dd 2012-07-07 210: # calling real put
d823fa83dd 2012-07-07 211: gevent.queue.JoinableQueue.put(self, item, block, timeout)
d823fa83dd 2012-07-07 212: # installing event handler
d823fa83dd 2012-07-07 213: gevent.core.write_event(self._fileno, self._wait_helper)
d823fa83dd 2012-07-07 214:
d823fa83dd 2012-07-07 215: def _wait_helper(self, ev, evtype):
d823fa83dd 2012-07-07 216: # XXX ev, evtype checking?
d823fa83dd 2012-07-07 217: # checking leftover
d823fa83dd 2012-07-07 218: while True:
d823fa83dd 2012-07-07 219: if self._tail == None:
d823fa83dd 2012-07-07 220: try:
d823fa83dd 2012-07-07 221: self._tail = str(self.get_nowait()).encode('utf-8') + '\n'
d823fa83dd 2012-07-07 222: except gevent.queue.Empty:
d823fa83dd 2012-07-07 223: self._tail = None
d823fa83dd 2012-07-07 224: return
d823fa83dd 2012-07-07 225: # writing tail
d823fa83dd 2012-07-07 226: written = self._io.write(self._tail)
d823fa83dd 2012-07-07 227: length = len(self._tail)
d823fa83dd 2012-07-07 228: if written == length:
d823fa83dd 2012-07-07 229: self._tail = None
d823fa83dd 2012-07-07 230: elif written < length:
d823fa83dd 2012-07-07 231: self._tail = self._tail[written:]
d823fa83dd 2012-07-07 232: break
d823fa83dd 2012-07-07 233: else:
d823fa83dd 2012-07-07 234: break
d823fa83dd 2012-07-07 235: # reinstalling event handler
d823fa83dd 2012-07-07 236: gevent.core.write_event(self._fileno, self._wait_helper)
39b97ced92 2011-06-05 237:
39b97ced92 2011-06-05 238: # wrapper around database
39b97ced92 2011-06-05 239: class tagDB(object):
39b97ced92 2011-06-05 240: __slots__ = frozenset(['_cursor', '_db'])
39b97ced92 2011-06-05 241:
39b97ced92 2011-06-05 242: def __init__(self):
39b97ced92 2011-06-05 243: config.section('database')
d2c7ba18a4 2011-09-14 244: if config['host'] == None:
d2c7ba18a4 2011-09-14 245: self._db = psycopg2.connect(
d2c7ba18a4 2011-09-14 246: database = config['database'],
d2c7ba18a4 2011-09-14 247: user = config['user'],
d2c7ba18a4 2011-09-14 248: password = config['password']
d2c7ba18a4 2011-09-14 249: )
d2c7ba18a4 2011-09-14 250: else:
d2c7ba18a4 2011-09-14 251: self._db = psycopg2.connect(
d2c7ba18a4 2011-09-14 252: database = config['database'],
d2c7ba18a4 2011-09-14 253: host = config['host'],
d2c7ba18a4 2011-09-14 254: user = config['user'],
d2c7ba18a4 2011-09-14 255: password = config['password']
d2c7ba18a4 2011-09-14 256: )
39b97ced92 2011-06-05 257: self._cursor = self._db.cursor()
39b97ced92 2011-06-05 258:
39b97ced92 2011-06-05 259: def _field_names(self):
39b97ced92 2011-06-05 260: names = []
39b97ced92 2011-06-05 261: for record in self._cursor.description:
39b97ced92 2011-06-05 262: names.append(record.name)
39b97ced92 2011-06-05 263: return(names)
39b97ced92 2011-06-05 264:
39b97ced92 2011-06-05 265: def check(self, site, ip_address):
39b97ced92 2011-06-05 266: self._cursor.execute("select * from (select redirect_url, regexp from site_rule where site <@ tripdomain(%s) and netmask >>= %s order by array_length(site, 1) desc) a group by redirect_url, regexp", [site, ip_address])
39b97ced92 2011-06-05 267: return(self._cursor.fetchall())
39b97ced92 2011-06-05 268:
39b97ced92 2011-06-05 269: def dump(self):
39b97ced92 2011-06-05 270: self._cursor.execute("select untrip(site) as site, tag::text, regexp from urls order by site, tag")
39b97ced92 2011-06-05 271: return(self._field_names(), self._cursor.fetchall())
39b97ced92 2011-06-05 272:
39b97ced92 2011-06-05 273: def load(self, data):
39b97ced92 2011-06-05 274: if config.options.flush_db:
39b97ced92 2011-06-05 275: self._cursor.execute('delete from urls;')
39b97ced92 2011-06-05 276: bundle = []
39b97ced92 2011-06-05 277: for row in data:
39b97ced92 2011-06-05 278: if len(row) == 2:
39b97ced92 2011-06-05 279: bundle.append([row[0], row[1], None])
39b97ced92 2011-06-05 280: else:
39b97ced92 2011-06-05 281: bundle.append([row[0], row[1], row[2]])
39b97ced92 2011-06-05 282: self._cursor.executemany("insert into urls (site, tag, regexp) values (tripdomain(%s), %s, %s)", bundle)
39b97ced92 2011-06-05 283: self._cursor.execute("update urls set regexp = NULL where regexp = ''")
39b97ced92 2011-06-05 284: self._db.commit()
39b97ced92 2011-06-05 285:
39b97ced92 2011-06-05 286: def load_conf(self, csv_data):
39b97ced92 2011-06-05 287: self._cursor.execute('delete from rules;')
39b97ced92 2011-06-05 288: bundle = []
39b97ced92 2011-06-05 289: for row in csv_data:
39b97ced92 2011-06-05 290: bundle.append([row[0], row[1], int(row[2]), int(row[3]), row[4], row[5], row[6]])
39b97ced92 2011-06-05 291: self._cursor.executemany("insert into rules (netmask, redirect_url, from_weekday, to_weekday, from_time, to_time, tag) values (%s::text::cidr, %s, %s, %s, %s::text::time, %s::text::time, %s::text::text[])", bundle)
39b97ced92 2011-06-05 292: self._db.commit()
39b97ced92 2011-06-05 293:
39b97ced92 2011-06-05 294: def dump_conf(self):
39b97ced92 2011-06-05 295: self._cursor.execute("select netmask, redirect_url, from_weekday, to_weekday, from_time, to_time, tag::text from rules")
39b97ced92 2011-06-05 296: return(self._field_names(), self._cursor.fetchall())
39b97ced92 2011-06-05 297:
39b97ced92 2011-06-05 298: # abstract class with basic checking functionality
39b97ced92 2011-06-05 299: class Checker(object):
d823fa83dd 2012-07-07 300: __slots__ = frozenset(['_db', '_log', '_queue', '_request', '_stdout'])
39b97ced92 2011-06-05 301:
39b97ced92 2011-06-05 302: def __init__(self, queue, logger):
39b97ced92 2011-06-05 303: self._db = tagDB()
39b97ced92 2011-06-05 304: self._log = logger
2654b86697 2012-07-09 305: self._log.info('started')
39b97ced92 2011-06-05 306: self._request = re.compile('^([0-9]+)\ (http|ftp):\/\/([-\w.:]+)\/([^ ]*)\ ([0-9.]+)\/(-|[\w\.]+)\ (-|\w+)\ (-|GET|HEAD|POST).*$')
39b97ced92 2011-06-05 307: self._queue = queue
d823fa83dd 2012-07-07 308: self._stdout = FWritelineQueue(sys.stdout, False)
39b97ced92 2011-06-05 309:
39b97ced92 2011-06-05 310: def process(self, id, site, ip_address, url_path, line = None):
2654b86697 2012-07-09 311: #self._log.info('trying {}'.format(site))
39b97ced92 2011-06-05 312: result = self._db.check(site, ip_address)
39b97ced92 2011-06-05 313: reply = None
2654b86697 2012-07-09 314: #self._log.info('got {} lines from database'.format(len(result)))
39b97ced92 2011-06-05 315: for row in result:
39b97ced92 2011-06-05 316: if row != None and row[0] != None:
39b97ced92 2011-06-05 317: if row[1] != None:
2654b86697 2012-07-09 318: self._log.info('trying regexp "{}" versus "{}"'.format(row[1], url_path))
39b97ced92 2011-06-05 319: try:
39b97ced92 2011-06-05 320: if re.compile(row[1]).match(url_path):
39b97ced92 2011-06-05 321: reply = row[0].format(url_path)
39b97ced92 2011-06-05 322: else:
39b97ced92 2011-06-05 323: continue
39b97ced92 2011-06-05 324: except:
2654b86697 2012-07-09 325: self._log.info("can't compile regexp")
39b97ced92 2011-06-05 326: else:
39b97ced92 2011-06-05 327: reply = row[0].format(url_path)
39b97ced92 2011-06-05 328: if reply != None:
d823fa83dd 2012-07-07 329: self.writeline('{} {}'.format(id, reply))
39b97ced92 2011-06-05 330: return(True)
d823fa83dd 2012-07-07 331: self.writeline('{}'.format(id))
39b97ced92 2011-06-05 332:
2654b86697 2012-07-09 333: def loop(self):
39b97ced92 2011-06-05 334: while True:
39b97ced92 2011-06-05 335: line = self._queue.get()
39b97ced92 2011-06-05 336: if line == None:
39b97ced92 2011-06-05 337: break
2654b86697 2012-07-09 338: #self._log.info('request: ' + line)
39b97ced92 2011-06-05 339: request = self._request.match(line)
39b97ced92 2011-06-05 340: if request:
39b97ced92 2011-06-05 341: id = request.group(1)
39b97ced92 2011-06-05 342: #proto = request.group(2)
39b97ced92 2011-06-05 343: site = request.group(3)
39b97ced92 2011-06-05 344: url_path = request.group(4)
39b97ced92 2011-06-05 345: ip_address = request.group(5)
39b97ced92 2011-06-05 346: self.process(id, site, ip_address, url_path, line)
39b97ced92 2011-06-05 347: else:
2654b86697 2012-07-09 348: self._log.info('bad request')
d823fa83dd 2012-07-07 349: self.writeline(line)
39b97ced92 2011-06-05 350:
39b97ced92 2011-06-05 351: def writeline(self, string):
2654b86697 2012-07-09 352: self._log.info('> ' + string)
d823fa83dd 2012-07-07 353: self._stdout.put(string)
39b97ced92 2011-06-05 354:
d301d9adc6 2010-08-13 355: if config.options.dump or config.options.load or config.options.dump_conf or config.options.load_conf:
d301d9adc6 2010-08-13 356: import csv
d301d9adc6 2010-08-13 357:
d301d9adc6 2010-08-13 358: tagdb = tagDB()
bde51dc0c7 2010-08-26 359: data_fields = ['site', 'tag', 'regexp']
d301d9adc6 2010-08-13 360: conf_fields = ['netmask', 'redirect_url', 'from_weekday', 'to_weekday', 'from_time', 'to_time', 'tag']
d301d9adc6 2010-08-13 361:
d301d9adc6 2010-08-13 362: if config.options.dump or config.options.dump_conf:
0ef24b1937 2011-04-06 363: csv_writer = csv.writer(sys.stdout)
d301d9adc6 2010-08-13 364: if config.options.dump:
bde51dc0c7 2010-08-26 365: dump = tagdb.dump()
bde51dc0c7 2010-08-26 366: elif config.options.dump_conf:
bde51dc0c7 2010-08-26 367: dump = tagdb.dump_conf()
bde51dc0c7 2010-08-26 368:
0ef24b1937 2011-04-06 369: csv_writer.writerow(dump[0])
0ef24b1937 2011-04-06 370: for line in dump[1]:
0ef24b1937 2011-04-06 371: csv_writer.writerow(line)
d301d9adc6 2010-08-13 372:
d301d9adc6 2010-08-13 373: elif config.options.load or config.options.load_conf:
d301d9adc6 2010-08-13 374: csv_reader = csv.reader(sys.stdin)
d301d9adc6 2010-08-13 375: first_row = next(csv_reader)
d301d9adc6 2010-08-13 376:
d301d9adc6 2010-08-13 377: if config.options.load:
bde51dc0c7 2010-08-26 378: fields = data_fields
bde51dc0c7 2010-08-26 379: load = tagdb.load
bde51dc0c7 2010-08-26 380: elif config.options.load_conf:
bde51dc0c7 2010-08-26 381: fields = conf_fields
bde51dc0c7 2010-08-26 382: load = tagdb.load_conf
bde51dc0c7 2010-08-26 383:
bde51dc0c7 2010-08-26 384: assert first_row == fields, 'File must contain csv data with theese columns: ' + repr(fields)
bde51dc0c7 2010-08-26 385: load(csv_reader)
d301d9adc6 2010-08-13 386:
d301d9adc6 2010-08-13 387: else:
d301d9adc6 2010-08-13 388: # main loop
39b97ced92 2011-06-05 389: Checker(stdin, logger).loop()