core: use of the new core.log module:

/!\ this is a massive refactoring and was largely automated, it probably did bring some bugs /!\
This commit is contained in:
Goffi 2014-04-19 19:19:19 +02:00
commit 501bc92528
2 changed files with 707 additions and 941 deletions

View file

@ -25,20 +25,18 @@ from twisted.words.xish import domish
from twisted.internet import reactor
from wokkel.xmppim import RosterItem
from sat.bridge.DBus import DBusBridge
import logging
from logging import debug, info, warning, error
import sys
import os.path
from sat.core import xmpp
from sat.core import exceptions
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core.constants import Const as C
from sat.memory.memory import Memory
from sat.tools.misc import TriggerManager
from sat.stdui import ui_contact_list
from glob import glob
from uuid import uuid4
import sys
import os.path
try:
from collections import OrderedDict # only available from python 2.7
@ -93,7 +91,7 @@ class SAT(service.Service):
try:
self.bridge = DBusBridge()
except exceptions.BridgeInitError:
print (u"Bridge can't be initialised, can't start SàT core") # reactor is not launched yet, so we can't use error log
log.error(u"Bridge can't be initialised, can't start SàT core")
sys.exit(1)
self.bridge.register("getVersion", lambda: C.APP_VERSION)
self.bridge.register("getProfileName", self.memory.getProfileName)
@ -140,7 +138,7 @@ class SAT(service.Service):
def _postMemoryInit(self, ignore):
"""Method called after memory initialization is done"""
info(_("Memory initialised"))
log.info(_("Memory initialised"))
self._import_plugins()
ui_contact_list.ContactList(self)
@ -169,25 +167,25 @@ class SAT(service.Service):
"""
if import_name in self.plugins:
debug('Plugin [%s] already imported, passing' % import_name)
log.debug('Plugin [%s] already imported, passing' % import_name)
return
if not import_name:
import_name, (plugin_path, mod, plugin_info) = plugins_to_import.popitem()
else:
if not import_name in plugins_to_import:
if optional:
warning(_("Recommended plugin not found: %s") % import_name)
log.warning(_("Recommended plugin not found: %s") % import_name)
return
error(_("Dependency not found: %s") % import_name)
log.error(_("Dependency not found: %s") % import_name)
raise ImportError(_('Dependency plugin not found: [%s]') % import_name)
plugin_path, mod, plugin_info = plugins_to_import.pop(import_name)
dependencies = plugin_info.setdefault("dependencies", [])
recommendations = plugin_info.setdefault("recommendations", [])
for to_import in dependencies + recommendations:
if to_import not in self.plugins:
debug('Recursively import dependency of [%s]: [%s]' % (import_name, to_import))
log.debug('Recursively import dependency of [%s]: [%s]' % (import_name, to_import))
self._import_plugins_from_dict(plugins_to_import, to_import, to_import not in dependencies)
info(_("importing plugin: %s"), plugin_info['name'])
log.info(_("importing plugin: %s") % plugin_info['name'])
self.plugins[import_name] = getattr(mod, plugin_info['main'])(self)
if 'handler' in plugin_info and plugin_info['handler'] == 'yes':
self.plugins[import_name].is_handler = True
@ -205,11 +203,11 @@ class SAT(service.Service):
"""
profile = self.memory.getProfileName(profile_key)
if not profile:
error(_('Trying to connect a non-exsitant profile'))
log.error(_('Trying to connect a non-exsitant profile'))
raise exceptions.ProfileUnknownError(profile_key)
if self.isConnected(profile):
info(_("already connected !"))
log.info(_("already connected !"))
return defer.succeed("None")
def afterMemoryInit(ignore):
@ -217,7 +215,7 @@ class SAT(service.Service):
try:
port = int(self.memory.getParamA("Port", "Connection", profile_key=profile))
except ValueError:
error(_("Can't parse port value, using default value"))
log.error(_("Can't parse port value, using default value"))
port = 5222
current = self.profiles[profile] = xmpp.SatXMPPClient(
self, profile,
@ -245,7 +243,7 @@ class SAT(service.Service):
current.identityHandler = xmpp.SatIdentityHandler()
current.identityHandler.setHandlerParent(current)
debug(_("setting plugins parents"))
log.debug(_("setting plugins parents"))
plugin_conn_cb = []
for plugin in self.plugins.iteritems():
@ -270,10 +268,10 @@ class SAT(service.Service):
def logPluginResults(results):
all_succeed = all([success for success, result in results])
if not all_succeed:
error(_("Plugins initialisation error"))
log.error(_("Plugins initialisation error"))
for idx, (success, result) in enumerate(results):
if not success:
error("Error (plugin %(name)s): %(failure)s" % {'name': plugin_conn_cb[idx][0],
log.error("error (plugin %(name)s): %(failure)s" % {'name': plugin_conn_cb[idx][0],
'failure': result})
list_d.addCallback(logPluginResults)
@ -289,10 +287,10 @@ class SAT(service.Service):
def disconnect(self, profile_key):
"""disconnect from jabber server"""
if not self.isConnected(profile_key):
info(_("not connected !"))
log.info(_("not connected !"))
return
profile = self.memory.getProfileName(profile_key)
info(_("Disconnecting..."))
log.info(_("Disconnecting..."))
self.profiles[profile].stopService()
for plugin in self.plugins.iteritems():
disconnected_cb = getattr(plugin[1], "profileDisconnected", None)
@ -318,23 +316,23 @@ class SAT(service.Service):
try:
del self.profiles[profile]
except KeyError:
error(_("Trying to remove reference to a client not referenced"))
log.error(_("Trying to remove reference to a client not referenced"))
self.memory.purgeProfileSession(profile)
def startService(self):
info("Salut à toi ô mon frère !")
log.info(u"Salut à toi ô mon frère !")
#TODO: manage autoconnect
#self.connect()
def stopService(self):
info("Salut aussi à Rantanplan")
log.info("Salut aussi à Rantanplan")
def run(self):
debug(_("running app"))
log.debug(_("running app"))
reactor.run()
def stop(self):
debug(_("stopping app"))
log.debug(_("stopping app"))
reactor.stop()
## Misc methods ##
@ -415,7 +413,7 @@ class SAT(service.Service):
def setParam(self, name, value, category, security_limit, profile_key):
"""set wanted paramater and notice observers"""
info(_("setting param: %(name)s=%(value)s in category %(category)s") % {'name': name, 'value': value, 'category': category})
log.info(_("setting param: %(name)s=%(value)s in category %(category)s") % {'name': name, 'value': value, 'category': category})
self.memory.setParam(name, value, category, security_limit, profile_key)
def isConnected(self, profile_key):
@ -425,7 +423,7 @@ class SAT(service.Service):
"""
profile = self.memory.getProfileName(profile_key)
if not profile:
error(_('asking connection status for a non-existant profile'))
log.error(_('asking connection status for a non-existant profile'))
return
if profile not in self.profiles:
return False
@ -490,7 +488,7 @@ class SAT(service.Service):
if not self.trigger.point("sendMessage", mess_data, pre_xml_treatments, post_xml_treatments, profile):
return defer.succeed(None)
debug(_("Sending jabber message of type [%(type)s] to %(to)s...") % {"type": mess_data["type"], "to": to_jid.full()})
log.debug(_("Sending jabber message of type [%(type)s] to %(to)s...") % {"type": mess_data["type"], "to": to_jid.full()})
def generateXML(mess_data):
mess_data['xml'] = domish.Element((None, 'message'))
@ -507,12 +505,12 @@ class SAT(service.Service):
def sendErrback(e):
text = '%s: %s' % (e.value.__class__.__name__, e.getErrorMessage())
if e.check(MessageSentAndStored):
debug(text)
log.debug(text)
elif e.check(AbortSendMessage):
warning(text)
log.warning(text)
return e
else:
error("Unmanaged exception: %s" % text)
log.error("Unmanaged exception: %s" % text)
return e
pre_xml_treatments.addCallback(generateXML)
pre_xml_treatments.chainDeferred(post_xml_treatments)
@ -532,7 +530,7 @@ class SAT(service.Service):
try:
client = self.profiles[profile]
except KeyError:
error(_("Trying to send a message with no profile"))
log.error(_("Trying to send a message with no profile"))
return
current_jid = client.jid
if not skip_send:
@ -580,7 +578,7 @@ class SAT(service.Service):
profile = self.memory.getProfileName(profile_key)
assert(profile)
to_jid = jid.JID(raw_jid)
debug(_('subsciption request [%(subs_type)s] for %(jid)s') % {'subs_type': subs_type, 'jid': to_jid.full()})
log.debug(_('subsciption request [%(subs_type)s] for %(jid)s') % {'subs_type': subs_type, 'jid': to_jid.full()})
if subs_type == "subscribe":
self.profiles[profile].presence.subscribe(to_jid)
elif subs_type == "subscribed":
@ -664,7 +662,7 @@ class SAT(service.Service):
@param data: dictionary of dictionaries
"""
if action_type != "DICT_DICT":
error(_("action_type for actionResultExt must be DICT_DICT, fixing it"))
log.error(_("action_type for actionResultExt must be DICT_DICT, fixing it"))
action_type = "DICT_DICT"
self.bridge.actionResultExt(action_type, action_id, data, profile)
@ -678,7 +676,7 @@ class SAT(service.Service):
# FIXME: use XMLUI and *callback methods for dialog
client = self.getClient(profile)
if conf_id in client._waiting_conf:
error(_("Attempt to register two callbacks for the same confirmation"))
log.error(_("Attempt to register two callbacks for the same confirmation"))
else:
client._waiting_conf[conf_id] = (conf_type, data, cb)
self.bridge.askConfirmation(conf_id, conf_type, data, profile)
@ -686,9 +684,9 @@ class SAT(service.Service):
def confirmationAnswer(self, conf_id, accepted, data, profile):
"""Called by frontends to answer confirmation requests"""
client = self.getClient(profile)
debug(_("Received confirmation answer for conf_id [%(conf_id)s]: %(success)s") % {'conf_id': conf_id, 'success': _("accepted") if accepted else _("refused")})
log.debug(_("Received confirmation answer for conf_id [%(conf_id)s]: %(success)s") % {'conf_id': conf_id, 'success': _("accepted") if accepted else _("refused")})
if conf_id not in client._waiting_conf:
error(_("Received an unknown confirmation (%(id)s for %(profile)s)") % {'id': conf_id, 'profile': profile})
log.error(_("Received an unknown confirmation (%(id)s for %(profile)s)") % {'id': conf_id, 'profile': profile})
else:
cb = client._waiting_conf[conf_id][-1]
del client._waiting_conf[conf_id]
@ -703,7 +701,7 @@ class SAT(service.Service):
"""Remove a progress callback"""
client = self.getClient(profile)
if progress_id not in client._progress_cb_map:
error(_("Trying to remove an unknow progress callback"))
log.error(_("Trying to remove an unknow progress callback"))
else:
del client._progress_cb_map[progress_id]
@ -718,7 +716,7 @@ class SAT(service.Service):
client._progress_cb_map[progress_id](progress_id, data, profile)
except KeyError:
pass
#debug("Requested progress for unknown progress_id")
#log.debug("Requested progress for unknown progress_id")
return data
def registerCallback(self, callback, *args, **kwargs):
@ -750,7 +748,7 @@ class SAT(service.Service):
def removeCallback(self, callback_id):
""" Remove a previously registered callback
@param callback_id: id returned by [registerCallback] """
debug("Removing callback [%s]" % callback_id)
log.debug("Removing callback [%s]" % callback_id)
del self._cb_map[callback_id]
def launchCallback(self, callback_id, data=None, profile_key=C.PROF_KEY_NONE):

View file

@ -22,7 +22,8 @@ from sat.core.constants import Const as C
from twisted.internet import task, defer
from twisted.words.protocols.jabber import jid, xmlstream
from wokkel import client, disco, xmppim, generic, compat, delay, iwokkel
from logging import debug, info, warning, error
from sat.core.log import getLogger
log = getLogger(__name__)
from sat.core import exceptions
from calendar import timegm
from zope.interface import implements
@ -54,13 +55,13 @@ class SatXMPPClient(client.XMPPClient):
return
client.XMPPClient._authd(self, xmlstream)
self.__connected = True
info(_("********** [%s] CONNECTED **********") % self.profile)
log.info(_("********** [%s] CONNECTED **********") % self.profile)
self.streamInitialized()
self.host_app.bridge.connected(self.profile) # we send the signal to the clients
def streamInitialized(self):
"""Called after _authd"""
debug(_("XML stream is initialized"))
log.debug(_("XML stream is initialized"))
self.keep_alife = task.LoopingCall(self.xmlstream.send, " ") # Needed to avoid disconnection (specially with openfire)
self.keep_alife.start(180)
@ -81,7 +82,7 @@ class SatXMPPClient(client.XMPPClient):
disco_d.addCallback(finish_connection)
def initializationFailed(self, reason):
error(_("ERROR: XMPP connection failed for profile '%(profile)s': %(reason)s" % {'profile': self.profile, 'reason': reason}))
log.error(_("ERROR: XMPP connection failed for profile '%(profile)s': %(reason)s" % {'profile': self.profile, 'reason': reason}))
self.host_app.bridge.connectionError("AUTH_ERROR", self.profile)
try:
client.XMPPClient.initializationFailed(self, reason)
@ -95,11 +96,11 @@ class SatXMPPClient(client.XMPPClient):
def connectionLost(self, connector, unused_reason):
self.__connected = False
info(_("********** [%s] DISCONNECTED **********") % self.profile)
log.info(_("********** [%s] DISCONNECTED **********") % self.profile)
try:
self.keep_alife.stop()
except AttributeError:
debug(_("No keep_alife"))
log.debug(_("No keep_alife"))
self.host_app.bridge.disconnected(self.profile) # we send the signal to the clients
self.host_app.purgeClient(self.profile) # and we remove references to this client
@ -111,7 +112,7 @@ class SatMessageProtocol(xmppim.MessageProtocol):
self.host = host
def onMessage(self, message):
debug(_(u"got message from: %s"), message["from"])
log.debug(_(u"got message from: %s") % message["from"])
post_treat = defer.Deferred() # XXX: plugin can add their treatments to this deferred
if not self.host.trigger.point("MessageReceived", message, post_treat, profile=self.parent.profile):
@ -163,7 +164,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
def requestRoster(self):
""" ask the server for Roster list """
debug("requestRoster")
log.debug("requestRoster")
d = self.getRoster().addCallback(self.rosterCb)
d.chainDeferred(self.got_roster)
@ -217,11 +218,11 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
# may change in the future
self.removeItem(item.jid)
return
info(_("new contact in roster list: %s"), item.jid.full())
log.info(_("new contact in roster list: %s") % item.jid.full())
if not item.subscriptionTo:
warning(_("You are not subscribed to this contact !"))
log.warning(_("You are not subscribed to this contact !"))
if not item.subscriptionFrom:
warning(_("This contact is not subscribed to you !"))
log.warning(_("This contact is not subscribed to you !"))
#self.host.memory.addContact(item.jid, item_attr, item.groups, self.parent.profile)
bare_jid = item.jid.userhostJID()
@ -239,7 +240,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
try:
item = self._jids.pop(bare_jid)
except KeyError:
warning("Received a roster remove event for an item not in cache")
log.warning("Received a roster remove event for an item not in cache")
return
for group in item.groups:
try:
@ -248,7 +249,7 @@ class SatRosterProtocol(xmppim.RosterClientProtocol):
if not jids_set:
del self._groups[group]
except KeyError:
warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" %
log.warning("there is not cache for the group [%(groups)s] of the removed roster item [%(jid)s]" %
{"group": group, "jid": bare_jid})
# then we send the bridge signal
@ -295,7 +296,7 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
super(SatPresenceProtocol, self).send(obj)
def availableReceived(self, entity, show=None, statuses=None, priority=0):
debug(_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity': entity, 'show': show, 'statuses': statuses, 'priority': priority})
log.debug(_("presence update for [%(entity)s] (available, show=%(show)s statuses=%(statuses)s priority=%(priority)d)") % {'entity': entity, 'show': show, 'statuses': statuses, 'priority': priority})
if not statuses:
statuses = {}
@ -314,7 +315,7 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
self.parent.profile)
def unavailableReceived(self, entity, statuses=None):
debug(_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity': entity, 'statuses': statuses})
log.debug(_("presence update for [%(entity)s] (unavailable, statuses=%(statuses)s)") % {'entity': entity, 'statuses': statuses})
if not statuses:
statuses = {}
@ -358,7 +359,7 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
self.host.memory.delWaitingSub(entity.userhost(), self.parent.profile)
item = self.parent.roster.getItem(entity)
if not item or not item.subscriptionTo: # we automatically subscribe to 'to' presence
debug(_('sending automatic "from" subscription request'))
log.debug(_('sending automatic "from" subscription request'))
self.subscribe(entity)
def unsubscribed(self, entity):
@ -366,29 +367,29 @@ class SatPresenceProtocol(xmppim.PresenceClientProtocol):
self.host.memory.delWaitingSub(entity.userhost(), self.parent.profile)
def subscribedReceived(self, entity):
debug(_("subscription approved for [%s]") % entity.userhost())
log.debug(_("subscription approved for [%s]") % entity.userhost())
self.host.bridge.subscribe('subscribed', entity.userhost(), self.parent.profile)
def unsubscribedReceived(self, entity):
debug(_("unsubscription confirmed for [%s]") % entity.userhost())
log.debug(_("unsubscription confirmed for [%s]") % entity.userhost())
self.host.bridge.subscribe('unsubscribed', entity.userhost(), self.parent.profile)
def subscribeReceived(self, entity):
debug(_("subscription request from [%s]") % entity.userhost())
log.debug(_("subscription request from [%s]") % entity.userhost())
item = self.parent.roster.getItem(entity)
if item and item.subscriptionTo:
# We automatically accept subscription if we are already subscribed to contact presence
debug(_('sending automatic subscription acceptance'))
log.debug(_('sending automatic subscription acceptance'))
self.subscribed(entity)
else:
self.host.memory.addWaitingSub('subscribe', entity.userhost(), self.parent.profile)
self.host.bridge.subscribe('subscribe', entity.userhost(), self.parent.profile)
def unsubscribeReceived(self, entity):
debug(_("unsubscription asked for [%s]") % entity.userhost())
log.debug(_("unsubscription asked for [%s]") % entity.userhost())
item = self.parent.roster.getItem(entity)
if item and item.subscriptionFrom: # we automatically remove contact
debug(_('automatic contact deletion'))
log.debug(_('automatic contact deletion'))
self.host.delContact(entity, self.parent.profile)
self.host.bridge.subscribe('unsubscribe', entity.userhost(), self.parent.profile)
@ -405,7 +406,7 @@ class SatFallbackHandler(generic.FallbackHandler):
def iqFallback(self, iq):
if iq.handled is True:
return
debug(u"iqFallback: xml = [%s]" % (iq.toXml()))
log.debug(u"iqFallback: xml = [%s]" % (iq.toXml()))
generic.FallbackHandler.iqFallback(self, iq)
@ -441,14 +442,14 @@ class RegisteringAuthenticator(xmlstream.ConnectAuthenticator):
iq.send(self.jabber_host).addCallbacks(self.registrationAnswer, self.registrationFailure)
def registrationAnswer(self, answer):
debug(_("registration answer: %s") % answer.toXml())
log.debug(_("registration answer: %s") % answer.toXml())
answer_type = "SUCCESS"
answer_data = {"message": _("Registration successfull")}
self.host.bridge.actionResult(answer_type, self.answer_id, answer_data, self.profile)
self.xmlstream.sendFooter()
def registrationFailure(self, failure):
info(_("Registration failure: %s") % str(failure.value))
log.info(_("Registration failure: %s") % str(failure.value))
answer_type = "ERROR"
answer_data = {}
if failure.value.condition == 'conflict':