/usr/share/pyshared/archipelcore/utils.py is in archipel-core 0.6.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | # -*- coding: utf-8 -*-
#
# utils.py
#
# Copyright (C) 2010 Antoine Mercadal <antoine.mercadal@inframonde.eu>
# This file is part of ArchipelProject
# http://archipelproject.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
this module contains some functions that allow objects to use advanced logging
functionalities or others common stuffs
"""
import ConfigParser
import socket
import struct
import inspect
import logging
import logging.handlers
import os
import xmpp
# Namespaces
ARCHIPEL_NS_GENERIC_ERROR = "archipel:error:generic"
ARCHIPEL_LOG_LEVEL = 0
ARCHIPEL_LOG_DEBUG = 0
ARCHIPEL_LOG_INFO = 1
ARCHIPEL_LOG_WARNING = 2
ARCHIPEL_LOG_ERROR = 3
log = logging.getLogger('archipel')
class TNArchipelLogger:
"""
archipel logger implt
"""
def __init__(self, entity, pubsubnode=None, xmppconn=None):
self.xmppclient = xmppconn
self.entity = entity
self.pubSubNode = pubsubnode
def __log(self, level, msg):
log = logging.getLogger('archipel')
msg = "\033[33m%s.%s (%s)\033[0m::%s" % (self.entity.__class__.__name__, inspect.stack()[2][3], self.entity.jid, msg)
if level < ARCHIPEL_LOG_LEVEL:
return
elif level == ARCHIPEL_LOG_DEBUG:
log.debug(msg)
elif level == ARCHIPEL_LOG_INFO:
log.info(msg)
elif level == ARCHIPEL_LOG_WARNING:
log.warning(msg)
elif level == ARCHIPEL_LOG_ERROR:
log.error(msg)
# if self.xmppclient and self.pubSubNode:
# log = xmpp.Node(tag="log", attrs={"date": datetime.datetime.now(), "level": str(level)})
# log.setData(msg)
# self.pubSubNode.add_item(log)
def debug(self, msg):
self.__log(ARCHIPEL_LOG_DEBUG, msg)
def info(self, msg):
self.__log(ARCHIPEL_LOG_INFO, msg)
def warning(self, msg):
self.__log(ARCHIPEL_LOG_WARNING, msg)
def error(self, msg):
self.__log(ARCHIPEL_LOG_ERROR, msg)
class ColorFormatter (logging.Formatter):
"""
Archipel log formatter
"""
def format(self, record):
rec = logging.Formatter.format(self, record)
rec = rec.replace("DEBUG", "\033[35mDEBUG \033[0m")
rec = rec.replace("INFO", "\033[32mINFO \033[0m")
rec = rec.replace("WARNING", "\033[33mWARNING \033[0m")
rec = rec.replace("ERROR", "\033[31mERROR \033[0m")
rec = rec.replace("CRITICAL", "\033[31mCRITICAL\033[0m")
rec = rec.replace("$whiteColor", "\033[37m")
rec = rec.replace("$noColor", "\033[0m")
return rec
def init_conf(paths):
"""
This method initialize the configuration object (that will be passed to all
entities) from a given path.
@type path: List
@param paths: list of the paths of the config files to read
@return : the ConfigParser object containing the configuration
"""
import socket
conf = ConfigParser.ConfigParser()
conf.read(paths)
for section in conf.sections():
for option in conf.options(section):
value = conf.get(section, option, raw=True)
if (not value):
raise Exception("Missing value for option %s in section [%s]" %(option,section))
value = value.replace("@HOSTNAME@", socket.gethostname())
conf.set(section, "%s" % option, value)
return conf
def init_log(conf):
"""
Initialize the logger
@type conf: ConfigParser
@param conf: the configuration where to read log info
"""
logging_level = conf.get("LOGGING", "logging_level")
if logging_level == "debug":
level = logging.DEBUG
elif logging_level == "info":
level = logging.INFO
elif logging_level == "warning":
level = logging.WARNING
elif logging_level == "error":
level = logging.ERROR
elif logging_level == "critical":
level = logging.CRITICAL
log_file = conf.get("LOGGING", "logging_file_path")
if not os.path.exists(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
logger = globals()["log"]
max_bytes = conf.getint("LOGGING", "logging_max_bytes")
backup_count = conf.getint("LOGGING", "logging_backup_count")
handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
log_format = ColorFormatter(conf.get("LOGGING", "logging_formatter", raw=True), conf.get("LOGGING", "logging_date_format", raw=True))
handler.setFormatter(log_format)
logger.addHandler(handler)
logger.setLevel(level)
def build_error_iq(originclass, ex, iq, code=-1, ns=ARCHIPEL_NS_GENERIC_ERROR):
#traceback.print_exc(file=sys.stdout, limit=20)
caller = inspect.stack()[1][3]
log.error("%s.%s: exception raised is: '%s' triggered by stanza :\n%s" % (originclass, caller, ex, str(iq)))
try:
origin_namespace = iq.getTag("query").getNamespace()
origin_action = iq.getTag("query").getTag("archipel").getAttr("action")
text_message = "%s\n\n%s\n%s" % (str(ex), origin_namespace, origin_action)
except Exception as e:
log.error("The stanza is not a valid ACP: %s" % str(e))
text_message = str(ex)
reply = iq.buildReply('error')
reply.setQueryPayload(iq.getQueryPayload())
error = xmpp.Node("error", attrs={"code": code, "type": "cancel"})
error.addChild(name=ns.replace(":", "-"), namespace=ns)
error.addChild(name="text", payload=text_message)
reply.addChild(node=error)
return reply
def build_error_message(originclass, ex, msg):
caller = inspect.stack()[3][3]
log.error("%s: exception raised is: '%s' triggered by message:\n %s" % (caller, str(ex), str(msg)))
return str(ex)
def get_default_gateway_interface():
"""
Reads the ip address of default gateway interface
"""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
|