Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011-2013 Cesnet z.s.p.o
# Use of this source is governed by a 3-clause BSD-style license, see LICENSE file.
import json, httplib, ssl, socket, logging, logging.handlers
from urlparse import urlparse
from urllib import urlencode
from sys import stderr, exc_info
from pprint import pformat
from traceback import format_tb
from os import path
class HTTPSConnection(httplib.HTTPSConnection):
'''
Overridden to allow peer certificate validation, configuration
of SSL/ TLS version and cipher selection. See:
http://hg.python.org/cpython/file/c1c45755397b/Lib/httplib.py#l1144
and `ssl.wrap_socket()`
'''
def __init__(self, host, **kwargs):
self.ciphers = kwargs.pop('ciphers',None)
self.ca_certs = kwargs.pop('ca_certs',None)
self.ssl_version = kwargs.pop('ssl_version',ssl.PROTOCOL_SSLv23)
httplib.HTTPSConnection.__init__(self,host,**kwargs)
def connect(self):
sock = socket.create_connection( (self.host, self.port), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
self.sock = ssl.wrap_socket(
sock,
keyfile = self.key_file,
certfile = self.cert_file,
ca_certs = self.ca_certs,
cert_reqs = ssl.CERT_REQUIRED if self.ca_certs else ssl.CERT_NONE,
ssl_version = self.ssl_version)
class Error(Exception):
""" Object for returning error messages to calling application.
Caller can test whether it received data or error by checking
isinstance(res, Error).
However if he does not want to deal with errors altogether,
this error object also returns False value if used in Bool
context (e.g. in "if res: print res" print is not evaluated),
and also acts as empty iterator (e.g. in "for e in res: print e"
print is also not evaluated).
Also, it can be raised as an exception.
"""

Pavel Kácha
committed
def __init__(self, logger=None, prio=logging.ERROR, method=None, req_id=None,
exc=None, errors=None, **kwargs):
self.errors = []
if errors:
self.extend(method, req_id, errors)
if kwargs:
self.append(method, req_id, **kwargs)

Pavel Kácha
committed
log(logger, prio)
def append(self, method=None, req_id=None, **kwargs):
# We shift method and req_id into each and every error, because
# we want to be able to simply merge more Error arrays (for
# returning errors from more Warden calls at once
if method and not "method" in kwargs:
kwargs["method"] = method
if req_id and not "req_id" in kwargs:
kwargs["req_id"] = req_id
self.errors.append(kwargs)
def extend(self, method=None, req_id=None, iterable=[]):
for e in iterable:
self.append(method, req_id, **e)
def __len__ (self):
""" In list or iterable context we're empty """
return 0
def __iter__(self):
""" We are the iterator """
return self
def next(self):
""" In list or iterable context we're empty """
raise StopIteration
def __bool__(self):
""" In boolean context we're never True """
return False
def __str__(self):

Pavel Kácha
committed
return "\n".join(self.str_err(e) for e in self.errors)
def log(self, logger, prio=logging.ERROR):
for e in self.errors:
logger.log(prio, self.str_err(e))
info = self.str_info(e)
if info:
logger.info(info)
debug = self.str_debug(e)
if debug:
logger.debug(debug)
def str_preamble(self, e):
return "%08x/%s" % (e.get("req_id", 0), e.get("method", "?"))
def str_err(self, e):

Pavel Kácha
committed
out.append(self.str_preamble(e))
out.append(" Error(%s) %s " % (e.get("error", 0), e.get("message", "Unknown error")))
if "exc" in e and e["exc"]:
out.append("(cause was %s: %s)" % (e["exc"][0].__name__, str(e["exc"][1])))

Pavel Kácha
committed
def str_info(self, e):
ecopy = dict(e) # shallow copy
ecopy.pop("req_id", None)
ecopy.pop("method", None)
ecopy.pop("error", None)
ecopy.pop("message", None)
ecopy.pop("exc", None)
if ecopy:
out = "%s Detail: %s" % (self.str_preamble(e), json.dumps(ecopy, default=lambda v: str(v)))
else:
out = ""
return out

Pavel Kácha
committed
def str_debug(self, e):

Pavel Kácha
committed
out.append(self.str_preamble(e))
if not "exc" in e or not e["exc"]:
return ""
exc_tb = e["exc"][2]
if exc_tb:
out.append("Traceback:\n")
out.extend(format_tb(exc_tb))
return "".join(out)
class Client(object):
def __init__(self,
url,
certfile=None,
keyfile=None,
cafile=None,
timeout=60,
recv_events_limit=6000,
errlog={"level": "debug"},
syslog=None,
filelog=None,
idstore=None,
name="warden_client",
secret=None):
self.secret = secret
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# Init logging as soon as possible and make sure we don't
# spit out exceptions but just log or return Error objects
self.init_log(errlog, syslog, filelog)
self.url = urlparse(url, allow_fragments=False)
self.conn = None
base = path.join(path.dirname(__file__))
self.certfile = path.join(base, certfile or "cert.pem")
self.keyfile = path.join(base, keyfile or "key.pem")
self.cafile = path.join(base, cafile or "ca.pem")
self.timeout = int(timeout)
self.recv_events_limit = int(recv_events_limit)
self.idstore = path.join(base, idstore) if idstore is not None else None
self.ciphers = 'TLS_RSA_WITH_AES_256_CBC_SHA'
self.sslversion = ssl.PROTOCOL_TLSv1
def init_log(self, errlog, syslog, filelog):
def loglevel(lev):
try:
return int(getattr(logging, lev.upper()))
except (AttributeError, ValueError):
self.logger.warning("Unknown loglevel \"%s\", using \"debug\"" % lev)
return logging.DEBUG
def facility(fac):
try:
return int(getattr(logging.handlers.SysLogHandler, "LOG_" + fac.upper()))
except (AttributeError, ValueError):
self.logger.warning("Unknown syslog facility \"%s\", using \"local7\"" % fac)
return logging.handlers.SysLogHandler.LOG_LOCAL7

Pavel Kácha
committed
form = "%(filename)s[%(process)d]: %(name)s (%(levelname)s) %(message)s"
format_notime = logging.Formatter(form)
format_time = logging.Formatter('%(asctime)s ' + form)
self.logger = logging.getLogger(self.name)
self.logger.propagate = False # Don't bubble up to root logger
self.logger.setLevel(logging.DEBUG)
if errlog is not None:
el = logging.StreamHandler(stderr)
el.setFormatter(format_time)

Pavel Kácha
committed
el.setLevel(loglevel(errlog.get("level", "info")))
self.logger.addHandler(el)
if filelog is not None:
try:
fl = logging.FileHandler(
filename=path.join(
path.dirname(__file__),
filelog.get("file", "%s.log" % self.name)))

Pavel Kácha
committed
fl.setLevel(loglevel(filelog.get("level", "debug")))
fl.setFormatter(format_time)
self.logger.addHandler(fl)
except Exception as e:

Pavel Kácha
committed
Error(self.logger, message="Unable to setup file logging", exc=exc_info())
if syslog is not None:
try:
sl = logging.handlers.SysLogHandler(
address=syslog.get("socket", "/dev/log"),
facility=facility(syslog.get("facility", "local7")))

Pavel Kácha
committed
sl.setLevel(loglevel(syslog.get("level", "debug")))
sl.setFormatter(format_notime)
self.logger.addHandler(sl)
except Exception as e:

Pavel Kácha
committed
Error(self.logger, message="Unable to setup syslog logging", exc=exc_info())
if not (errlog or filelog or syslog):

Pavel Kácha
committed
# User wants explicitly no logging, so let him shoot his socks off.
# This silences complaining of logging module about no suitable
# handler.
self.logger.addHandler(logging.NullHandler())
def connect(self):
try:
if self.url.scheme=="https":
conn = HTTPSConnection(
strict = False,
key_file = self.keyfile,
cert_file = self.certfile,
timeout = self.timeout,
ciphers = self.ciphers,
ca_certs = self.cafile,
ssl_version = self.sslversion)
elif self.url.scheme=="http":
conn = httplib.HTTPConnection(
strict = False,
timeout = self.timeout)
else:

Pavel Kácha
committed
return Error(self.logger, message="Don't know how to connect to \"%s\"" % self.url.scheme,
detail={"url": self.url.geturl()})
except Exception:

Pavel Kácha
committed
return Error(self.logger, message="HTTPS connection failed", exc=exc_info(),
detail={
"url": self.url.geturl(),
"timeout": self.timeout,
"key_file": self.keyfile,
"cert_file": self.certfile,
"cafile": self.cafile,
"ciphers": self.ciphers,
"ssl_version": self.sslversion})
return conn
def sendRequest(self, func="", payload=None, **kwargs):
if self.secret is None:
kwargs["client"] = self.name
else:
kwargs["secret"] = self.secret

Pavel Kácha
committed
if kwargs:
for k in kwargs.keys():
if kwargs[k] is None:
del kwargs[k]
argurl = "?" + urlencode(kwargs, doseq=True)
else:
argurl = ""
try:
if payload is None:
data = ""
else:
data = json.dumps(payload)
except:

Pavel Kácha
committed
return Error(self.logger, message="Serialization to JSON failed",
exc=exc_info(), method=func, detail=payload)
self.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Content-Length": str(len(data))
}
# HTTP(S)Connection is oneshot object (and we don't speak "pipelining")
conn = self.connect()
if not conn:
return conn # either False of Error instance
loc = '%s/%s%s' % (self.url.path, func, argurl)
try:
conn.request("POST", loc, data, self.headers)
conn.close()

Pavel Kácha
committed
return Error(self.logger, message="Sending of request to server failed",
exc=exc_info(), method=func, detail={
"loc": loc,
"headers": self.headers,
"data": data})
try:
res = conn.getresponse()
conn.close()

Pavel Kácha
committed
return Error(self.logger, method=func, message="HTTP reply failed", exc=exc_info(), detail={
"loc": loc,
"headers": self.headers,
"data": data})
try:
response_data = res.read()
except:
conn.close()

Pavel Kácha
committed
return Error(self.logger, method=func, message="Fetching HTTP data from server failed", exc=exc_info(), detail={
"loc": loc,
"headers": self.headers,
"data": data})
conn.close()
if res.status==httplib.OK:
try:
data = json.loads(response_data)
except:

Pavel Kácha
committed
data = Error(self.logger, message="JSON message parsing failed",
exc=exc_info(), method=func, detail={"response": response_data})
else:
try:
data = json.loads(response_data)

Pavel Kácha
committed
data["errors"] # trigger exception if not dict or no error key

Pavel Kácha
committed
data = Error(self.logger, message="Generic server HTTP error",
method=func,
error=res.status,
exc=exc_info(),
detail={"response": response_data})
else:

Pavel Kácha
committed
data = Error(self.logger,
method=data.get("method", None),
req_id=data.get("req_id", None),

Pavel Kácha
committed
errors=data.get("errors", []))
return data
def _saveID(self, id, idstore=None):
idf = idstore or self.idstore
if not idf:
return False
try:
with open(idf, "w+") as f:
f.write(str(id))
except (ValueError, IOError) as e:
# Use Error instance just for proper logging

Pavel Kácha
committed
Error(self.logger, message="Writing id file \"%s\" failed" % idf,
prio=logging.INFO, exc=exc_info(), detail={"idstore": idf})
return id
def _loadID(self, idstore=None):
idf = idstore or self.idstore
if not idf:
return None
try:
with open(idf, "r") as f:
id = int(f.read())
except (ValueError, IOError) as e:

Pavel Kácha
committed
Error(self.logger, prio=logging.INFO,
message="Reading id file \"%s\" failed, relying on server" % idf,
exc=exc_info(), detail={"idstore": idf})
id = None
return id
def getDebug(self):
return self.sendRequest("getDebug")
def getInfo(self):
return self.sendRequest("getInfo")
def sendEvents(self, events=[]):
res = self.sendRequest(
"sendEvents", payload=events)
return res
def getEvents(self, id=None, idstore=None, count=None,
cat=None, nocat=None,
tag=None, notag=None,
group=None, nogroup=None):
if not id:
id = self._loadID(idstore)
res = self.sendRequest(
"getEvents", id=id, count=count or self.recv_events_limit, cat=cat,
nocat=nocat, tag=tag, notag=notag, group=group, nogroup=nogroup)
if not res:
return res # Should be Error instance
try:
events = res["events"]
newid = res["lastid"]
except KeyError:

Pavel Kácha
committed
return Error(self.logger, message="Server returned bogus reply",
method="getEvents", exc=exc_info(), detail={"response": res})
self._saveID(newid)
return events
def close(self):
if hasattr(self, "conn") and hasattr(self.conn, "close"):
self.conn.close()
__del__ = close
def read_cfg(cfgfile):
abspath = path.join(path.dirname(__file__), cfgfile)
with open(abspath, "r") as f:
stripcomments = "\n".join((l for l in f if not l.lstrip().startswith(("#", "//"))))
return json.loads(stripcomments)