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
dbc0727869 2012-07-10 111: record.msg = record.msg.encode('utf-8')
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
2654b86697 2012-07-09 120: while not self._tail.empty():
2654b86697 2012-07-09 121: logging.handlers.SysLogHandler.emit(self, self._tail.get())
67e8b3309d 2012-07-09 122: self._worker = None
2654b86697 2012-07-09 123:
2654b86697 2012-07-09 124: def close(self):
67e8b3309d 2012-07-09 125: if self._worker != None:
67e8b3309d 2012-07-09 126: gevent.kill(self._worker)
2654b86697 2012-07-09 127: logging.handlers.SysLogHandler.close(self)
2654b86697 2012-07-09 128:
fad48b740c 2012-07-07 129: logger = logging.getLogger('squidTag')
fad48b740c 2012-07-07 130: logger.setLevel(logging.INFO)
2654b86697 2012-07-09 131: handler = SysLogHandlerQueue()
fad48b740c 2012-07-07 132: handler.setFormatter(logging.Formatter(str('squidTag[%(process)s]: %(message)s')))
fad48b740c 2012-07-07 133: logger.addHandler(handler)
39b97ced92 2011-06-05 134:
39b97ced92 2011-06-05 135: # tiny wrapper around a file to make reads from it geventable
39b97ced92 2011-06-05 136: # or should i move this somewhere?
39b97ced92 2011-06-05 137:
39b97ced92 2011-06-05 138: class FReadlineQueue(gevent.queue.Queue):
39b97ced92 2011-06-05 139: # storing file descriptor, leftover
67e8b3309d 2012-07-09 140: __slots__ = frozenset(['_io', '_fileno', '_tail'])
39b97ced92 2011-06-05 141:
67e8b3309d 2012-07-09 142: def __init__(self, fd, closefd = True):
67e8b3309d 2012-07-09 143: import io
39b97ced92 2011-06-05 144: # initialising class
39b97ced92 2011-06-05 145: gevent.queue.Queue.__init__(self)
39b97ced92 2011-06-05 146: # storing file descriptor
67e8b3309d 2012-07-09 147: self._fileno = fd.fileno()
67e8b3309d 2012-07-09 148: self._io = io.FileIO(self._fileno, 'r', closefd)
39b97ced92 2011-06-05 149: # using empty tail
39b97ced92 2011-06-05 150: self._tail = ''
39b97ced92 2011-06-05 151: # setting up event
39b97ced92 2011-06-05 152: self._install_wait()
39b97ced92 2011-06-05 153:
39b97ced92 2011-06-05 154: def _install_wait(self):
39b97ced92 2011-06-05 155: # putting file to nonblocking mode
67e8b3309d 2012-07-09 156: fcntl.fcntl(self._fileno, fcntl.F_SETFL, fcntl.fcntl(self._fileno, fcntl.F_GETFL) | os.O_NONBLOCK)
39b97ced92 2011-06-05 157: # installing event handler
67e8b3309d 2012-07-09 158: gevent.core.read_event(self._fileno, self._wait_helper)
39b97ced92 2011-06-05 159:
39b97ced92 2011-06-05 160: def _wait_helper(self, ev, evtype):
39b97ced92 2011-06-05 161: # reading one buffer from stream
67e8b3309d 2012-07-09 162: buf = self._io.read(4096)
39b97ced92 2011-06-05 163: # splitting stream by line ends
39b97ced92 2011-06-05 164: rows = buf.decode('l1').split('\n')
39b97ced92 2011-06-05 165: # adding tail to the first element if there is some tail
39b97ced92 2011-06-05 166: if len(self._tail) > 0:
39b97ced92 2011-06-05 167: rows[0] = self._tail + rows[0]
39b97ced92 2011-06-05 168: # popping out last (incomplete) element
39b97ced92 2011-06-05 169: self._tail = rows.pop(-1)
39b97ced92 2011-06-05 170: # dropping all complete elements to the queue
39b97ced92 2011-06-05 171: for row in rows:
39b97ced92 2011-06-05 172: self.put_nowait(row)
2654b86697 2012-07-09 173: logger.info('< ' + row)
39b97ced92 2011-06-05 174: if len(buf) > 0:
39b97ced92 2011-06-05 175: # no EOF, reinstalling event handler
67e8b3309d 2012-07-09 176: gevent.core.read_event(self._fileno, self._wait_helper)
39b97ced92 2011-06-05 177: else:
39b97ced92 2011-06-05 178: # EOF found, sending EOF to queue
39b97ced92 2011-06-05 179: self.put_nowait(None)
39b97ced92 2011-06-05 180:
67e8b3309d 2012-07-09 181: stdin = FReadlineQueue(sys.stdin, False)
2654b86697 2012-07-09 182:
2654b86697 2012-07-09 183: # wrapper against file handler that makes possible to queue some writes without stalling
d823fa83dd 2012-07-07 184:
d823fa83dd 2012-07-07 185: class FWritelineQueue(gevent.queue.JoinableQueue):
d823fa83dd 2012-07-07 186: # storing fileno, io interface, leftover
d823fa83dd 2012-07-07 187: __slots__ = frozenset(['_fileno', '_io', '_tail'])
d823fa83dd 2012-07-07 188:
d823fa83dd 2012-07-07 189: def __init__(self, fd, closefd = True):
d823fa83dd 2012-07-07 190: import io
d823fa83dd 2012-07-07 191: # initialising class
d823fa83dd 2012-07-07 192: gevent.queue.JoinableQueue.__init__(self)
d823fa83dd 2012-07-07 193: # storing fileno
d823fa83dd 2012-07-07 194: self._fileno = fd.fileno()
d823fa83dd 2012-07-07 195: # creating interface
d823fa83dd 2012-07-07 196: self._io = io.FileIO(self._fileno, 'w', closefd)
d823fa83dd 2012-07-07 197: # using empty tail
d823fa83dd 2012-07-07 198: self._tail = None
d823fa83dd 2012-07-07 199: # putting file to nonblocking mode
d823fa83dd 2012-07-07 200: fcntl.fcntl(self._fileno, fcntl.F_SETFL, fcntl.fcntl(self._fileno, fcntl.F_GETFL) | os.O_NONBLOCK)
d823fa83dd 2012-07-07 201:
d823fa83dd 2012-07-07 202: def __del__(self):
d823fa83dd 2012-07-07 203: # purge queue before deleting
d823fa83dd 2012-07-07 204: if not self.empty():
d823fa83dd 2012-07-07 205: self.join()
d823fa83dd 2012-07-07 206:
d823fa83dd 2012-07-07 207: def put(self, item, block=True, timeout=None):
d823fa83dd 2012-07-07 208: # calling real put
d823fa83dd 2012-07-07 209: gevent.queue.JoinableQueue.put(self, item, block, timeout)
d823fa83dd 2012-07-07 210: # installing event handler
d823fa83dd 2012-07-07 211: gevent.core.write_event(self._fileno, self._wait_helper)
d823fa83dd 2012-07-07 212:
d823fa83dd 2012-07-07 213: def _wait_helper(self, ev, evtype):
d823fa83dd 2012-07-07 214: # XXX ev, evtype checking?
d823fa83dd 2012-07-07 215: # checking leftover
d823fa83dd 2012-07-07 216: while True:
d823fa83dd 2012-07-07 217: if self._tail == None:
d823fa83dd 2012-07-07 218: try:
d823fa83dd 2012-07-07 219: self._tail = str(self.get_nowait()).encode('utf-8') + '\n'
d823fa83dd 2012-07-07 220: except gevent.queue.Empty:
d823fa83dd 2012-07-07 221: self._tail = None
d823fa83dd 2012-07-07 222: return
d823fa83dd 2012-07-07 223: # writing tail
d823fa83dd 2012-07-07 224: written = self._io.write(self._tail)
d823fa83dd 2012-07-07 225: length = len(self._tail)
d823fa83dd 2012-07-07 226: if written == length:
d823fa83dd 2012-07-07 227: self._tail = None
d823fa83dd 2012-07-07 228: elif written < length:
d823fa83dd 2012-07-07 229: self._tail = self._tail[written:]
d823fa83dd 2012-07-07 230: break
d823fa83dd 2012-07-07 231: else:
d823fa83dd 2012-07-07 232: break
d823fa83dd 2012-07-07 233: # reinstalling event handler
d823fa83dd 2012-07-07 234: gevent.core.write_event(self._fileno, self._wait_helper)
39b97ced92 2011-06-05 235:
39b97ced92 2011-06-05 236: # wrapper around database
39b97ced92 2011-06-05 237: class tagDB(object):
39b97ced92 2011-06-05 238: __slots__ = frozenset(['_cursor', '_db'])
39b97ced92 2011-06-05 239:
39b97ced92 2011-06-05 240: def __init__(self):
39b97ced92 2011-06-05 241: config.section('database')
d2c7ba18a4 2011-09-14 242: if config['host'] == None:
d2c7ba18a4 2011-09-14 243: self._db = psycopg2.connect(
d2c7ba18a4 2011-09-14 244: database = config['database'],
d2c7ba18a4 2011-09-14 245: user = config['user'],
d2c7ba18a4 2011-09-14 246: password = config['password']
d2c7ba18a4 2011-09-14 247: )
d2c7ba18a4 2011-09-14 248: else:
d2c7ba18a4 2011-09-14 249: self._db = psycopg2.connect(
d2c7ba18a4 2011-09-14 250: database = config['database'],
d2c7ba18a4 2011-09-14 251: host = config['host'],
d2c7ba18a4 2011-09-14 252: user = config['user'],
d2c7ba18a4 2011-09-14 253: password = config['password']
d2c7ba18a4 2011-09-14 254: )
39b97ced92 2011-06-05 255: self._cursor = self._db.cursor()
39b97ced92 2011-06-05 256:
39b97ced92 2011-06-05 257: def _field_names(self):
39b97ced92 2011-06-05 258: names = []
39b97ced92 2011-06-05 259: for record in self._cursor.description:
39b97ced92 2011-06-05 260: names.append(record.name)
39b97ced92 2011-06-05 261: return(names)
39b97ced92 2011-06-05 262:
39b97ced92 2011-06-05 263: def check(self, site, ip_address):
39b97ced92 2011-06-05 264: 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 265: return(self._cursor.fetchall())
39b97ced92 2011-06-05 266:
39b97ced92 2011-06-05 267: def dump(self):
39b97ced92 2011-06-05 268: self._cursor.execute("select untrip(site) as site, tag::text, regexp from urls order by site, tag")
39b97ced92 2011-06-05 269: return(self._field_names(), self._cursor.fetchall())
39b97ced92 2011-06-05 270:
39b97ced92 2011-06-05 271: def load(self, data):
39b97ced92 2011-06-05 272: if config.options.flush_db:
39b97ced92 2011-06-05 273: self._cursor.execute('delete from urls;')
39b97ced92 2011-06-05 274: bundle = []
39b97ced92 2011-06-05 275: for row in data:
39b97ced92 2011-06-05 276: if len(row) == 2:
39b97ced92 2011-06-05 277: bundle.append([row[0], row[1], None])
39b97ced92 2011-06-05 278: else:
39b97ced92 2011-06-05 279: bundle.append([row[0], row[1], row[2]])
39b97ced92 2011-06-05 280: self._cursor.executemany("insert into urls (site, tag, regexp) values (tripdomain(%s), %s, %s)", bundle)
39b97ced92 2011-06-05 281: self._cursor.execute("update urls set regexp = NULL where regexp = ''")
39b97ced92 2011-06-05 282: self._db.commit()
39b97ced92 2011-06-05 283:
39b97ced92 2011-06-05 284: def load_conf(self, csv_data):
39b97ced92 2011-06-05 285: self._cursor.execute('delete from rules;')
39b97ced92 2011-06-05 286: bundle = []
39b97ced92 2011-06-05 287: for row in csv_data:
39b97ced92 2011-06-05 288: bundle.append([row[0], row[1], int(row[2]), int(row[3]), row[4], row[5], row[6]])
39b97ced92 2011-06-05 289: 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 290: self._db.commit()
39b97ced92 2011-06-05 291:
39b97ced92 2011-06-05 292: def dump_conf(self):
39b97ced92 2011-06-05 293: self._cursor.execute("select netmask, redirect_url, from_weekday, to_weekday, from_time, to_time, tag::text from rules")
39b97ced92 2011-06-05 294: return(self._field_names(), self._cursor.fetchall())
39b97ced92 2011-06-05 295:
39b97ced92 2011-06-05 296: # abstract class with basic checking functionality
39b97ced92 2011-06-05 297: class Checker(object):
d823fa83dd 2012-07-07 298: __slots__ = frozenset(['_db', '_log', '_queue', '_request', '_stdout'])
39b97ced92 2011-06-05 299:
39b97ced92 2011-06-05 300: def __init__(self, queue, logger):
39b97ced92 2011-06-05 301: self._db = tagDB()
39b97ced92 2011-06-05 302: self._log = logger
2654b86697 2012-07-09 303: self._log.info('started')
39b97ced92 2011-06-05 304: self._request = re.compile('^([0-9]+)\ (http|ftp):\/\/([-\w.:]+)\/([^ ]*)\ ([0-9.]+)\/(-|[\w\.]+)\ (-|\w+)\ (-|GET|HEAD|POST).*$')
39b97ced92 2011-06-05 305: self._queue = queue
d823fa83dd 2012-07-07 306: self._stdout = FWritelineQueue(sys.stdout, False)
39b97ced92 2011-06-05 307:
39b97ced92 2011-06-05 308: def process(self, id, site, ip_address, url_path, line = None):
2654b86697 2012-07-09 309: #self._log.info('trying {}'.format(site))
39b97ced92 2011-06-05 310: result = self._db.check(site, ip_address)
39b97ced92 2011-06-05 311: reply = None
2654b86697 2012-07-09 312: #self._log.info('got {} lines from database'.format(len(result)))
39b97ced92 2011-06-05 313: for row in result:
39b97ced92 2011-06-05 314: if row != None and row[0] != None:
39b97ced92 2011-06-05 315: if row[1] != None:
2654b86697 2012-07-09 316: self._log.info('trying regexp "{}" versus "{}"'.format(row[1], url_path))
39b97ced92 2011-06-05 317: try:
39b97ced92 2011-06-05 318: if re.compile(row[1]).match(url_path):
39b97ced92 2011-06-05 319: reply = row[0].format(url_path)
39b97ced92 2011-06-05 320: else:
39b97ced92 2011-06-05 321: continue
39b97ced92 2011-06-05 322: except:
2654b86697 2012-07-09 323: self._log.info("can't compile regexp")
39b97ced92 2011-06-05 324: else:
39b97ced92 2011-06-05 325: reply = row[0].format(url_path)
39b97ced92 2011-06-05 326: if reply != None:
d823fa83dd 2012-07-07 327: self.writeline('{} {}'.format(id, reply))
39b97ced92 2011-06-05 328: return(True)
d823fa83dd 2012-07-07 329: self.writeline('{}'.format(id))
39b97ced92 2011-06-05 330:
2654b86697 2012-07-09 331: def loop(self):
39b97ced92 2011-06-05 332: while True:
39b97ced92 2011-06-05 333: line = self._queue.get()
39b97ced92 2011-06-05 334: if line == None:
39b97ced92 2011-06-05 335: break
2654b86697 2012-07-09 336: #self._log.info('request: ' + line)
39b97ced92 2011-06-05 337: request = self._request.match(line)
39b97ced92 2011-06-05 338: if request:
39b97ced92 2011-06-05 339: id = request.group(1)
39b97ced92 2011-06-05 340: #proto = request.group(2)
39b97ced92 2011-06-05 341: site = request.group(3)
39b97ced92 2011-06-05 342: url_path = request.group(4)
39b97ced92 2011-06-05 343: ip_address = request.group(5)
39b97ced92 2011-06-05 344: self.process(id, site, ip_address, url_path, line)
39b97ced92 2011-06-05 345: else:
2654b86697 2012-07-09 346: self._log.info('bad request')
d823fa83dd 2012-07-07 347: self.writeline(line)
39b97ced92 2011-06-05 348:
39b97ced92 2011-06-05 349: def writeline(self, string):
2654b86697 2012-07-09 350: self._log.info('> ' + string)
d823fa83dd 2012-07-07 351: self._stdout.put(string)
39b97ced92 2011-06-05 352:
d301d9adc6 2010-08-13 353: if config.options.dump or config.options.load or config.options.dump_conf or config.options.load_conf:
d301d9adc6 2010-08-13 354: import csv
d301d9adc6 2010-08-13 355:
d301d9adc6 2010-08-13 356: tagdb = tagDB()
bde51dc0c7 2010-08-26 357: data_fields = ['site', 'tag', 'regexp']
d301d9adc6 2010-08-13 358: conf_fields = ['netmask', 'redirect_url', 'from_weekday', 'to_weekday', 'from_time', 'to_time', 'tag']
d301d9adc6 2010-08-13 359:
d301d9adc6 2010-08-13 360: if config.options.dump or config.options.dump_conf:
0ef24b1937 2011-04-06 361: csv_writer = csv.writer(sys.stdout)
d301d9adc6 2010-08-13 362: if config.options.dump:
bde51dc0c7 2010-08-26 363: dump = tagdb.dump()
bde51dc0c7 2010-08-26 364: elif config.options.dump_conf:
bde51dc0c7 2010-08-26 365: dump = tagdb.dump_conf()
bde51dc0c7 2010-08-26 366:
0ef24b1937 2011-04-06 367: csv_writer.writerow(dump[0])
0ef24b1937 2011-04-06 368: for line in dump[1]:
0ef24b1937 2011-04-06 369: csv_writer.writerow(line)
d301d9adc6 2010-08-13 370:
d301d9adc6 2010-08-13 371: elif config.options.load or config.options.load_conf:
d301d9adc6 2010-08-13 372: csv_reader = csv.reader(sys.stdin)
d301d9adc6 2010-08-13 373: first_row = next(csv_reader)
d301d9adc6 2010-08-13 374:
d301d9adc6 2010-08-13 375: if config.options.load:
bde51dc0c7 2010-08-26 376: fields = data_fields
bde51dc0c7 2010-08-26 377: load = tagdb.load
bde51dc0c7 2010-08-26 378: elif config.options.load_conf:
bde51dc0c7 2010-08-26 379: fields = conf_fields
bde51dc0c7 2010-08-26 380: load = tagdb.load_conf
bde51dc0c7 2010-08-26 381:
bde51dc0c7 2010-08-26 382: assert first_row == fields, 'File must contain csv data with theese columns: ' + repr(fields)
bde51dc0c7 2010-08-26 383: load(csv_reader)
d301d9adc6 2010-08-13 384:
d301d9adc6 2010-08-13 385: else:
d301d9adc6 2010-08-13 386: # main loop
39b97ced92 2011-06-05 387: Checker(stdin, logger).loop()