Projects
Kolab:16:TestingLinked
pykolab
Log In
Username
Password
We truncated the diff of some files because they were too big. If you want to see the full diff for every file,
click here
.
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
Expand all
Collapse all
Changes of Revision 51
View file
pykolab.spec
Changed
@@ -42,8 +42,6 @@ Source0: pykolab-%{version}.tar.gz Source1: pykolab.logrotate -Patch0001: 0001-Add-mysqlhost.patch - BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root BuildArch: noarch @@ -232,8 +230,6 @@ %prep %setup -q -%patch0001 -p1 - %build autoreconf -v || automake --add-missing && autoreconf -v %configure
View file
0001-Add-mysqlhost.patch
Deleted
@@ -1,203 +0,0 @@ -From 894df668e96af15b172eff9b0e4ffcb42aa76084 Mon Sep 17 00:00:00 2001 -From: "Jeroen van Meeuwen (Kolab Systems)" <vanmeeuwen@kolabsys.com> -Date: Wed, 25 Sep 2019 08:10:49 +0200 -Subject: PATCH Add --mysqlhost - ---- - pykolab/setup/setup_mysql.py | 105 +++++++++++++++++-------------- - pykolab/setup/setup_roundcube.py | 3 +- - pykolab/setup/setup_syncroton.py | 13 +++- - 3 files changed, 72 insertions(+), 49 deletions(-) - -diff --git a/pykolab/setup/setup_mysql.py b/pykolab/setup/setup_mysql.py -index 807bc7f..d5e62a0 100644 ---- a/pykolab/setup/setup_mysql.py -+++ b/pykolab/setup/setup_mysql.py -@@ -48,6 +48,14 @@ def cli_options(): - help=_("Specify whether to use an (existing) or (new) MySQL server.") - ) - -+ mysql_group.add_option( -+ "--mysqlhost", -+ dest="mysqlhost", -+ action="store", -+ default='127.0.0.1', -+ help=_("The MySQL host address.") -+ ) -+ - mysql_group.add_option( - "--mysqlrootpw", - dest="mysqlrootpw", -@@ -70,45 +78,46 @@ def execute(*args, **kw): # noqa: C901 - - - # on CentOS7, there is MariaDB instead of MySQL -- mysqlservice = 'mysqld.service' -- if os.path.isfile('/usr/lib/systemd/system/mariadb.service'): -- mysqlservice = 'mariadb.service' -- elif os.path.isfile('/usr/lib/systemd/system/mysql.service'): -- mysqlservice = 'mysql.service' -- if not os.path.isfile('/usr/lib/systemd/system/' + mysqlservice): -- # on Debian Jessie, systemctl restart mysql -- mysqlservice = 'mysql' -- -- if os.path.isfile('/bin/systemctl'): -- subprocess.call('/bin/systemctl', 'restart', mysqlservice) -- elif os.path.isfile('/sbin/service'): -- subprocess.call('/sbin/service', 'mysqld', 'restart') -- elif os.path.isfile('/usr/sbin/service'): -- subprocess.call('/usr/sbin/service', 'mysql', 'restart') -- else: -- log.error(_("Could not start the MySQL database service.")) -- -- if os.path.isfile('/bin/systemctl'): -- subprocess.call('/bin/systemctl', 'enable', mysqlservice) -- elif os.path.isfile('/sbin/chkconfig'): -- subprocess.call('/sbin/chkconfig', 'mysqld', 'on') -- elif os.path.isfile('/usr/sbin/update-rc.d'): -- subprocess.call('/usr/sbin/update-rc.d', 'mysql', 'defaults') -- else: -- log.error( -- _("Could not configure to start on boot, the MySQL database service.") -- ) -+ if conf.mysqlserver != 'existing': -+ mysqlservice = 'mysqld.service' -+ if os.path.isfile('/usr/lib/systemd/system/mariadb.service'): -+ mysqlservice = 'mariadb.service' -+ elif os.path.isfile('/usr/lib/systemd/system/mysql.service'): -+ mysqlservice = 'mysql.service' -+ if not os.path.isfile('/usr/lib/systemd/system/' + mysqlservice): -+ # on Debian Jessie, systemctl restart mysql -+ mysqlservice = 'mysql' -+ -+ if os.path.isfile('/bin/systemctl'): -+ subprocess.call('/bin/systemctl', 'restart', mysqlservice) -+ elif os.path.isfile('/sbin/service'): -+ subprocess.call('/sbin/service', 'mysqld', 'restart') -+ elif os.path.isfile('/usr/sbin/service'): -+ subprocess.call('/usr/sbin/service', 'mysql', 'restart') -+ else: -+ log.error(_("Could not start the MySQL database service.")) -+ -+ if os.path.isfile('/bin/systemctl'): -+ subprocess.call('/bin/systemctl', 'enable', mysqlservice) -+ elif os.path.isfile('/sbin/chkconfig'): -+ subprocess.call('/sbin/chkconfig', 'mysqld', 'on') -+ elif os.path.isfile('/usr/sbin/update-rc.d'): -+ subprocess.call('/usr/sbin/update-rc.d', 'mysql', 'defaults') -+ else: -+ log.error( -+ _("Could not configure to start on boot, the MySQL database service.") -+ ) - -- log.info(_("Waiting for at most 30 seconds for MySQL/MariaDB to settle...")) -- max_wait = 30 -- while max_wait > 0: -- for socket_path in socket_paths: -- if os.path.exists(socket_path): -- max_wait = 0 -+ log.info(_("Waiting for at most 30 seconds for MySQL/MariaDB to settle...")) -+ max_wait = 30 -+ while max_wait > 0: -+ for socket_path in socket_paths: -+ if os.path.exists(socket_path): -+ max_wait = 0 - -- if max_wait > 0: -- max_wait = max_wait - 1 -- time.sleep(1) -+ if max_wait > 0: -+ max_wait = max_wait - 1 -+ time.sleep(1) - - options = { - 1: "Existing MySQL server (with root password already set).", -@@ -116,14 +125,17 @@ def execute(*args, **kw): # noqa: C901 - } - - answer = 0 -- if len(x for x in socket_paths if os.path.exists(x)) > 0: -- if conf.mysqlserver: -- if conf.mysqlserver == 'existing': -- answer = 1 -- elif conf.mysqlserver == 'new': -- answer = 2 -- if answer == 0: -- answer = utils.ask_menu(_("What MySQL server are we setting up?"), options) -+ if conf.mysqlserver != 'existing': -+ if len(x for x in socket_paths if os.path.exists(x)) > 0: -+ if conf.mysqlserver: -+ if conf.mysqlserver == 'existing': -+ answer = 1 -+ elif conf.mysqlserver == 'new': -+ answer = 2 -+ if answer == 0: -+ answer = utils.ask_menu(_("What MySQL server are we setting up?"), options) -+ else: -+ answer = 1 - - if answer == "1" or answer == 1: - if not conf.mysqlrootpw: -@@ -214,7 +226,8 @@ def execute(*args, **kw): # noqa: C901 - mysql - user=root - password='%s' --""" % (mysql_root_password) -+host=%s -+""" % (mysql_root_password, conf.mysqlhost) - - fp = open('/tmp/kolab-setup-my.cnf', 'w') - os.chmod('/tmp/kolab-setup-my.cnf', 600) -diff --git a/pykolab/setup/setup_roundcube.py b/pykolab/setup/setup_roundcube.py -index 1be5cb6..36c7aa7 100644 ---- a/pykolab/setup/setup_roundcube.py -+++ b/pykolab/setup/setup_roundcube.py -@@ -232,7 +232,8 @@ def execute(*args, **kw): - mysql - user=root - password='%s' --""" % (mysql_root_password) -+host=%s -+""" % (mysql_root_password, conf.mysqlhost) - - fp = open('/tmp/kolab-setup-my.cnf', 'w') - os.chmod('/tmp/kolab-setup-my.cnf', 600) -diff --git a/pykolab/setup/setup_syncroton.py b/pykolab/setup/setup_syncroton.py -index 5b9f915..446577f 100644 ---- a/pykolab/setup/setup_syncroton.py -+++ b/pykolab/setup/setup_syncroton.py -@@ -33,12 +33,20 @@ from pykolab.translate import _ - log = pykolab.getLogger('pykolab.setup') - conf = pykolab.getConf() - -+ - def __init__(): -- components.register('syncroton', execute, description=description(), after='mysql','ldap','roundcube') -+ components.register( -+ 'syncroton', -+ execute, -+ description=description(), -+ after='mysql','ldap','roundcube' -+ ) -+ - - def description(): - return _("Setup Syncroton.") - -+ - def execute(*args, **kw): - schema_files = - for root, directories, filenames in os.walk('/usr/share/doc/'): -@@ -71,7 +79,8 @@ def execute(*args, **kw): - mysql - user=root - password='%s' --""" % (mysql_root_password) -+host=%s -+""" % (mysql_root_password, conf.mysqlhost) - - fp = open('/tmp/kolab-setup-my.cnf', 'w')
View file
debian.changelog
Changed
@@ -1,3 +1,9 @@ +pykolab (0.8.15-0~kolab2) unstable; urgency=low + + * Fix init scripts for kolab-saslauthd and wallace + + -- Daniel Hoffend <dh@dotlan.net> Fri, 15 Nov 2019 01:35:13 +0100 + pykolab (0.8.15-0~kolab1) unstable; urgency=low * Release of version 0.8.15
View file
debian.tar.gz/kolab-saslauthd.init
Changed
@@ -103,6 +103,7 @@ --stop \ --quiet \ --retry=TERM/30/KILL/5 \ + --user $USER \ --startas $DAEMON \ --pidfile $PIDFILE RETVAL="$?"
View file
debian.tar.gz/kolab-server.init
Changed
@@ -91,6 +91,7 @@ --retry=TERM/30/KILL/5 \ --user $USER \ --startas $DAEMON \ + --pidfile $PIDFILE \ --name $NAME RETVAL="$?" "$RETVAL" = 2 && return 2
View file
debian.tar.gz/wallace.init
Changed
@@ -89,6 +89,7 @@ --stop \ --quiet \ --retry=TERM/30/KILL/5 \ + --user $USER \ --startas $DAEMON \ --pidfile $PIDFILE \ --name $PROG_NAME @@ -100,7 +101,7 @@ # that waits for the process to drop all resources that could be # needed by services started subsequently. A last resort is to # sleep for some time. - start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --user $USER --exec $DAEMON + start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON "$?" = 2 && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE
View file
pykolab-0.8.15.tar.gz/.flake8 -> pykolab-0.8.16.tar.gz/.flake8
Changed
@@ -5,6 +5,8 @@ docs/source/conf.py ignore = + # "Too complex"? Sure, for people that eat Hawaii pizza... + C901, # 'something' imported but unused F401, # 'from module import *' used: unable to detect undefined names
View file
pykolab-0.8.15.tar.gz/.pylintrc -> pykolab-0.8.16.tar.gz/.pylintrc
Changed
@@ -1,11 +1,13 @@ MASTER disable= + broad-except, cyclic-import, duplicate-code, + logging-not-lazy, missing-docstring, unused-argument, unused-wildcard-import, wildcard-import function-rgx=a-z_a-z0-9_{2,90}$ -init-hook="import sys; sys.path.insert(0, './data/')" +init-hook="import sys; sys.path.insert(0, '.')"
View file
pykolab-0.8.15.tar.gz/conf/kolab.conf -> pykolab-0.8.16.tar.gz/conf/kolab.conf
Changed
@@ -167,6 +167,9 @@ ; The URI to LDAP ldap_uri = ldap://localhost:389 +; A timeout, in seconds, for regular searches such as authentication requests. +timeout = 10 + ; A list of integers containing supported controls, to increase the efficiency ; of individual short-lived connections with LDAP. supported_controls = 0,2,3
View file
pykolab-0.8.15.tar.gz/configure.ac -> pykolab-0.8.16.tar.gz/configure.ac
Changed
@@ -1,4 +1,4 @@ -AC_INIT(pykolab, 0.8.15) +AC_INIT(pykolab, 0.8.16) AC_SUBST(RELEASE, 1) AC_CONFIG_SRCDIR(pykolab/constants.py.in)
View file
pykolab-0.8.15.tar.gz/kolabd.py -> pykolab-0.8.16.tar.gz/kolabd.py
Changed
@@ -8,28 +8,33 @@ # it under the terms of the GNU 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 General Public License for more details. - +# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # +from __future__ import print_function + +import os import sys # For development purposes -sys.path = '.' + sys.path +if os.path.isdir(os.path.join(os.path.dirname(__file__), '.git')): + sys.path.insert(0, '.') from pykolab.translate import _ + try: from pykolab.constants import * -except ImportError, e: - print >> sys.stderr, _("Cannot load pykolab/constants.py:") - print >> sys.stderr, "%s" % e +except ImportError as errmsg: + print(_("Cannot load pykolab/constants.py:"), file=sys.stderr) + print("%s" % (errmsg), file=sys.stderr) sys.exit(1) import kolabd
View file
pykolab-0.8.15.tar.gz/kolabd/__init__.py -> pykolab-0.8.16.tar.gz/kolabd/__init__.py
Changed
@@ -20,6 +20,8 @@ The Kolab daemon. """ +from __future__ import print_function + import grp import os import pwd @@ -33,77 +35,77 @@ from pykolab.auth import Auth from pykolab import constants from pykolab import utils -from pykolab.translate import _ +from pykolab.translate import _ as _l -from process import KolabdProcess as Process +from .process import KolabdProcess as Process +# pylint: disable=invalid-name log = pykolab.getLogger('pykolab.daemon') conf = pykolab.getConf() -class KolabDaemon(object): +class KolabDaemon: def __init__(self): """ The main Kolab Groupware daemon process. """ - daemon_group = conf.add_cli_parser_option_group(_("Daemon Options")) + daemon_group = conf.add_cli_parser_option_group(_l("Daemon Options")) daemon_group.add_option( - "--fork", - dest = "fork_mode", - action = "store_true", - default = False, - help = _("Fork to the background.") - ) + "--fork", + dest="fork_mode", + action="store_true", + default=False, + help=_l("Fork to the background.") + ) daemon_group.add_option( - "-p", - "--pid-file", - dest = "pidfile", - action = "store", - default = "/var/run/kolabd/kolabd.pid", - help = _("Path to the PID file to use.") - ) + "-p", "--pid-file", + dest="pidfile", + action="store", + default="/var/run/kolabd/kolabd.pid", + help=_l("Path to the PID file to use.") + ) daemon_group.add_option( - "-u", - "--user", - dest = "process_username", - action = "store", - default = "kolab", - help = _("Run as user USERNAME"), - metavar = "USERNAME" - ) + "-u", "--user", + dest="process_username", + action="store", + default="kolab", + help=_l("Run as user USERNAME"), + metavar="USERNAME" + ) daemon_group.add_option( - "-g", - "--group", - dest = "process_groupname", - action = "store", - default = "kolab", - help = _("Run as group GROUPNAME"), - metavar = "GROUPNAME" - ) + "-g", "--group", + dest="process_groupname", + action="store", + default="kolab", + help=_l("Run as group GROUPNAME"), + metavar="GROUPNAME" + ) conf.finalize_conf() + # pylint: disable=too-many-branches + # pylint: disable=too-many-statements def run(self): """Run Forest, RUN!""" exitcode = 0 utils.ensure_directory( - os.path.dirname(conf.pidfile), - conf.process_username, - conf.process_groupname - ) + os.path.dirname(conf.pidfile), + conf.process_username, + conf.process_groupname + ) try: try: - (ruid, euid, suid) = os.getresuid() - (rgid, egid, sgid) = os.getresgid() - except AttributeError, errmsg: + (ruid, _, _) = os.getresuid() + (rgid, _, _) = os.getresgid() + except AttributeError: ruid = os.getuid() rgid = os.getgid() @@ -112,64 +114,47 @@ if rgid == 0: # Get group entry details try: - ( - group_name, - group_password, - group_gid, - group_members - ) = grp.getgrnam(conf.process_groupname) + (_, _, group_gid, _) = grp.getgrnam(conf.process_groupname) except KeyError: - print >> sys.stderr, _("Group %s does not exist") % ( - conf.process_groupname - ) + log.error( + _l("Group %s does not exist") % (conf.process_groupname) + ) sys.exit(1) # Set real and effective group if not the same as current. if not group_gid == rgid: log.debug( - _("Switching real and effective group id to %d") % ( - group_gid - ), - level=8 - ) + _l("Switching real and effective group id to %d") % (group_gid), + level=8 + ) os.setregid(group_gid, group_gid) if ruid == 0: # Means we haven't switched yet. try: - ( - user_name, - user_password, - user_uid, - user_gid, - user_gecos, - user_homedir, - user_shell - ) = pwd.getpwnam(conf.process_username) + (_, _, user_uid, _, _, _, _) = pwd.getpwnam(conf.process_username) except KeyError: - print >> sys.stderr, _("User %s does not exist") % ( - conf.process_username - ) + log.error( + _l("User %s does not exist") % (conf.process_username) + ) sys.exit(1) # Set real and effective user if not the same as current. if not user_uid == ruid: log.debug( - _("Switching real and effective user id to %d") % ( - user_uid - ), - level=8 - ) + _l("Switching real and effective user id to %d") % (user_uid), + level=8 + ) os.setreuid(user_uid, user_uid)
View file
pykolab-0.8.15.tar.gz/kolabd/process.py -> pykolab-0.8.16.tar.gz/kolabd/process.py
Changed
@@ -17,13 +17,13 @@ # import multiprocessing -import os import time import pykolab from pykolab.auth import Auth from pykolab.translate import _ +# pylint: disable=invalid-name log = pykolab.getLogger('pykolab.daemon') conf = pykolab.getConf() @@ -33,11 +33,11 @@ self.domain = domain log.debug(_("Process created for domain %s") % (domain), level=8) multiprocessing.Process.__init__( - self, - target=self.synchronize, - args=(domain,), - name="Kolab(%s)" % domain - ) + self, + target=self.synchronize, + args=(domain,), + name="Kolab(%s)" % domain + ) def synchronize(self, domain): log.debug(_("Synchronizing for domain %s") % (domain), level=8) @@ -56,7 +56,7 @@ time.sleep(sync_interval) except KeyboardInterrupt: break - except Exception, errmsg: + except Exception as errmsg: log.error(_("Error in process %r, terminating:\n\t%r") % (self.name, errmsg)) import traceback traceback.print_exc()
View file
pykolab-0.8.15.tar.gz/pykolab/auth/__init__.py -> pykolab-0.8.16.tar.gz/pykolab/auth/__init__.py
Changed
@@ -21,14 +21,17 @@ import time import pykolab -import pykolab.base +from pykolab.base import Base from pykolab.translate import _ +# pylint: disable=invalid-name log = pykolab.getLogger('pykolab.auth') conf = pykolab.getConf() -class Auth(pykolab.base.Base): + +# pylint: disable=too-many-public-methods +class Auth(Base): """ This is the Authentication and Authorization module for PyKolab. """ @@ -37,7 +40,7 @@ """ Initialize the authentication class. """ - pykolab.base.Base.__init__(self, domain=domain) + Base.__init__(self, domain=domain) self._auth = None @@ -103,59 +106,59 @@ section = domain log.debug( - _("Using section %s and domain %s") % (section,domain), - level=8 - ) + _("Using section %s and domain %s") % (section, domain), + level=8 + ) - if not self.domains == None and self.domains.has_key(domain): + if self.domains is not None and domain in self.domains: section = self.domainsdomain domain = self.domainsdomain log.debug( - _("Using section %s and domain %s") % (section,domain), - level=8 - ) + _("Using section %s and domain %s") % (section, domain), + level=8 + ) log.debug( - _("Connecting to Authentication backend for domain %s") % ( - domain - ), - level=8 - ) + _("Connecting to Authentication backend for domain %s") % ( + domain + ), + level=8 + ) if not conf.has_section(section): section = 'kolab' if not conf.has_option(section, 'auth_mechanism'): log.debug( - _("Section %s has no option 'auth_mechanism'") % (section), - level=8 - ) + _("Section %s has no option 'auth_mechanism'") % (section), + level=8 + ) section = 'kolab' else: log.debug( - _("Section %s has auth_mechanism: %r") % ( - section, - conf.get(section,'auth_mechanism') - ), - level=8 - ) + _("Section %s has auth_mechanism: %r") % ( + section, + conf.get(section, 'auth_mechanism') + ), + level=8 + ) # Get the actual authentication and authorization backend. if conf.get(section, 'auth_mechanism') == 'ldap': log.debug(_("Starting LDAP..."), level=8) - from pykolab.auth import ldap - self._auth = ldap.LDAP(self.domain) + from pykolab.auth.ldap import LDAP + self._auth = LDAP(self.domain) - elif conf.get(section, 'auth_mechanism') == 'sql': - from pykolab.auth import sql - self._auth = sql.SQL(self.domain) + # elif conf.get(section, 'auth_mechanism') == 'sql': + # from .sql import SQL + # self._auth = SQL(self.domain) else: log.debug(_("Starting LDAP..."), level=8) - from pykolab.auth import ldap - self._auth = ldap.LDAP(self.domain) + from pykolab.auth.ldap import LDAP + self._auth = LDAP(self.domain) self._auth.connect() @@ -165,13 +168,10 @@ back to the primary domain specified by the configuration. """ - if domain == None: - section = 'kolab' + if domain is None: domain = conf.get('kolab', 'primary_domain') - else: - section = domain - if not self._auth or self._auth == None: + if not self._auth: return self._auth._disconnect()
View file
pykolab-0.8.15.tar.gz/pykolab/auth/ldap/__init__.py -> pykolab-0.8.16.tar.gz/pykolab/auth/ldap/__init__.py
Changed
@@ -6,103 +6,57 @@ # it under the terms of the GNU 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 General Public License for more details. - +# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # +# pylint: disable=too-many-lines + +from __future__ import print_function import datetime -import _ldap -import ldap -import ldap.async -import ldap.controls -import ldap.filter +# Catch python-ldap-2.4 changes +from distutils import version import logging import time import traceback -import pykolab -import pykolab.base - -from pykolab import utils -from pykolab.constants import * -from pykolab.errors import * -from pykolab.translate import _ - -log = pykolab.getLogger('pykolab.auth') -conf = pykolab.getConf() - -import auth_cache -import cache - -# Catch python-ldap-2.4 changes -from distutils import version - -if version.StrictVersion('2.4.0') <= version.StrictVersion(ldap.__version__): - LDAP_CONTROL_PAGED_RESULTS = ldap.CONTROL_PAGEDRESULTS -else: - LDAP_CONTROL_PAGED_RESULTS = ldap.LDAP_CONTROL_PAGE_OID - +import ldap +import ldap.controls try: from ldap.controls import psearch -except: - log.warning(_("Python LDAP library does not support persistent search")) +except ImportError: + pass -class SimplePagedResultsControl(ldap.controls.SimplePagedResultsControl): - """ +from ldap.dn import explode_dn - Python LDAP 2.4 and later breaks the API. This is an abstraction class - so that we can handle either. - """ +import ldap.filter - def __init__(self, page_size=0, cookie=''): - if version.StrictVersion( - '2.4.0' - ) <= version.StrictVersion( - ldap.__version__ - ): +from six import string_types +import _ldap - ldap.controls.SimplePagedResultsControl.__init__( - self, - size=page_size, - cookie=cookie - ) - else: - ldap.controls.SimplePagedResultsControl.__init__( - self, - LDAP_CONTROL_PAGED_RESULTS, - True, - (page_size, '') - ) +import pykolab - def cookie(self): - if version.StrictVersion( - '2.4.0' - ) <= version.StrictVersion( - ldap.__version__ - ): +from pykolab import utils +from pykolab.base import Base +from pykolab.constants import SUPPORTED_LDAP_CONTROLS +from pykolab.errors import * +from pykolab.translate import _ as _l - return self.cookie - else: - return self.controlValue1 +import auth_cache +import cache - def size(self): - if version.StrictVersion( - '2.4.0' - ) <= version.StrictVersion( - ldap.__version__ - ): +# pylint: disable=invalid-name +log = pykolab.getLogger('pykolab.auth') +conf = pykolab.getConf() - return self.size - else: - return self.controlValue0 -class LDAP(pykolab.base.Base): +class LDAP(Base): """ Abstraction layer for the LDAP authentication / authorization backend, for use with Kolab. @@ -113,17 +67,21 @@ Initialize the LDAP object for domain. If no domain is specified, domain name space configured as 'kolab'.'primary_domain' is used. """ - pykolab.base.Base.__init__(self, domain=domain) + Base.__init__(self, domain=domain) self.ldap = None self.ldap_priv = None self.bind = None - if domain == None: + if domain is None: self.domain = conf.get('kolab', 'primary_domain') else: self.domain = domain + # pylint: disable=too-many-branches + # pylint: disable=too-many-locals + # pylint: disable=too-many-return-statements + # pylint: disable=too-many-statements def authenticate(self, login, realm): """ Find the entry corresponding to login, and attempt a bind. @@ -144,13 +102,14 @@ try: log.debug( - _("Attempting to authenticate user %s in realm %s") % ( - login0, - realm - ), - level=8 - ) - except: + _l("Attempting to authenticate user %s in realm %s") % ( + login0, + realm + ), + level=8 + ) + + except Exception: pass self.connect(immediate=True) @@ -161,31 +120,29 @@ try: base_dn = auth_cache.get_entry(self.domain) - except Exception, errmsg: - log.error(_("Authentication cache failed: %r") % (errmsg)) - pass + except Exception as errmsg: + log.error(_l("Authentication cache failed: %r") % (errmsg)) - if base_dn == None: + if base_dn is None: config_base_dn = self.config_get('base_dn') ldap_base_dn = self._kolab_domain_root_dn(self.domain) - if not ldap_base_dn == None and not ldap_base_dn == config_base_dn: + if ldap_base_dn is not None and not ldap_base_dn == config_base_dn: base_dn = ldap_base_dn else: base_dn = config_base_dn try: auth_cache.set_entry(self.domain, base_dn)
View file
pykolab-0.8.15.tar.gz/pykolab/auth/ldap/auth_cache.py -> pykolab-0.8.16.tar.gz/pykolab/auth/ldap/auth_cache.py
Changed
@@ -25,30 +25,18 @@ from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String -from sqlalchemy import Table from sqlalchemy import Text -from sqlalchemy import desc from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import mapper -try: - from sqlalchemy.orm import relationship -except: - from sqlalchemy.orm import relation as relationship - -try: - from sqlalchemy.orm import sessionmaker -except: - from sqlalchemy.orm import create_session +from sqlalchemy.orm import sessionmaker import pykolab -from pykolab import utils from pykolab.constants import KOLAB_LIB_PATH -from pykolab.translate import _ +# pylint: disable=invalid-name conf = pykolab.getConf() log = pykolab.getLogger('pykolab.auth_cache') @@ -56,12 +44,19 @@ db = None -## -## Classes -## +try: + unicode('') +except NameError: + unicode = str + +# +# Classes +# DeclarativeBase = declarative_base() + +# pylint: disable=too-few-public-methods class Entry(DeclarativeBase): __tablename__ = 'entries' @@ -78,39 +73,45 @@ else: self.value = value -## -## Functions -## +# +# Functions +# + def del_entry(key): + # pylint: disable=global-statement + global db + db = init_db() try: - _entries = db.query(Entry).filter_by(key=key).delete() - except sqlalchemy.exc.OperationalError, errmsg: + db.query(Entry).filter_by(key=key).delete() + except sqlalchemy.exc.OperationalError: db = init_db(reinit=True) - except sqlalchemy.exc.InvalidRequest, errmsg: + except sqlalchemy.exc.InvalidRequest: db = init_db(reinit=True) finally: - _entries = db.query(Entry).filter_by(key=key).delete() + db.query(Entry).filter_by(key=key).delete() db.commit() + def get_entry(key): + # pylint: disable=global-statement + global db + db = init_db() try: _entries = db.query(Entry).filter_by(key=key).all() - except sqlalchemy.exc.OperationalError, errmsg: + except sqlalchemy.exc.OperationalError: db = init_db(reinit=True) - except sqlalchemy.exc.InvalidRequest, errmsg: + except sqlalchemy.exc.InvalidRequest: db = init_db(reinit=True) finally: _entries = db.query(Entry).filter_by(key=key).all() - if len(_entries) == 0: - return None - if len(_entries) > 1: + if len(_entries) != 1: return None log.debug("Entry found: %r" % (_entries0.__dict__)) @@ -118,26 +119,23 @@ return _entries0.value.encode('utf-8', 'latin1') + def set_entry(key, value): db = init_db() + try: _entries = db.query(Entry).filter_by(key=key).all() - except sqlalchemy.exc.OperationalError, errmsg: + except sqlalchemy.exc.OperationalError: db = init_db(reinit=True) - except sqlalchemy.exc.InvalidRequest, errmsg: + except sqlalchemy.exc.InvalidRequest: db = init_db(reinit=True) finally: _entries = db.query(Entry).filter_by(key=key).all() - if len(_entries) == 0: - db.add( - Entry( - key, - value - ) - ) - + if not _entries: + db.add(Entry(key, value)) db.commit() + elif len(_entries) == 1: if not isinstance(value, unicode): value = unicode(value, 'utf-8') @@ -148,21 +146,28 @@ _entries0.last_change = datetime.datetime.now() db.commit() + def purge_entries(db): - db.query(Entry).filter(Entry.last_change <= (datetime.datetime.now() - datetime.timedelta(1))).delete() + db.query(Entry).filter( + Entry.last_change <= (datetime.datetime.now() - datetime.timedelta(1)) + ).delete() + db.commit() + def init_db(reinit=False): """ Returns a SQLAlchemy Session() instance. """ + # pylint: disable=global-statement global db - if not db == None and not reinit: + if db is not None and not reinit: return db db_uri = conf.get('ldap', 'auth_cache_uri') - if db_uri == None: + + if db_uri is None: db_uri = 'sqlite:///%s/auth_cache.db' % (KOLAB_LIB_PATH) if reinit:
View file
pykolab-0.8.15.tar.gz/pykolab/auth/ldap/cache.py -> pykolab-0.8.16.tar.gz/pykolab/auth/ldap/cache.py
Changed
@@ -18,6 +18,8 @@ import datetime +from uuid import UUID + import sqlalchemy from sqlalchemy import Column @@ -25,42 +27,44 @@ from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String -from sqlalchemy import Table from sqlalchemy import desc from sqlalchemy import create_engine -from sqlalchemy.orm import mapper - -from uuid import UUID +from sqlalchemy.ext.declarative import declarative_base -try: - from sqlalchemy.orm import relationship -except: - from sqlalchemy.orm import relation as relationship - -try: - from sqlalchemy.orm import sessionmaker -except: - from sqlalchemy.orm import create_session +from sqlalchemy.orm import sessionmaker import pykolab -from pykolab import utils from pykolab.constants import KOLAB_LIB_PATH from pykolab.translate import _ +# pylint: disable=invalid-name conf = pykolab.getConf() -log = pykolab.getLogger('pykolab.auth_cache') +log = pykolab.getLogger('pykolab.cache') metadata = MetaData() db = {} -## -## Classes -## +# +# Classes +# + +DeclarativeBase = declarative_base() + + +# pylint: disable=too-few-public-methods +class Entry(DeclarativeBase): + __tablename__ = 'entries' + + last_change = None + + id = Column(Integer, primary_key=True) + uniqueid = Column(String(128), nullable=False) + result_attribute = Column(String(128), nullable=False) + last_change = Column(DateTime, nullable=False, default=datetime.datetime.now()) -class Entry(object): def __init__(self, uniqueid, result_attr, last_change): self.uniqueid = uniqueid self.result_attribute = result_attr @@ -72,83 +76,64 @@ ).replace('%%', '%') self.last_change = datetime.datetime.strptime( - last_change, + last_change, modifytimestamp_format ) -## -## Tables -## - -entry_table = Table( - 'entry', metadata, - Column('id', Integer, primary_key=True), - Column('uniqueid', String(128), nullable=False), - Column('result_attribute', String(128), nullable=False), - Column('last_change', DateTime), - ) - -## -## Table <-> Class Mappers -## -mapper(Entry, entry_table) +# +# Functions +# -## -## Functions -## def delete_entry(domain, entry): - result_attribute = conf.get_raw('cyrus-sasl', 'result_attribute') + _db = init_db(domain) + _entry = _db.query(Entry).filter_by(uniqueid=entry'id').first() - db = init_db(domain) - _entry = db.query(Entry).filter_by(uniqueid=entry'id').first() + if _entry is not None: + _db.delete(_entry) + _db.commit() - if not _entry == None: - db.delete(_entry) - db.commit() def get_entry(domain, entry, update=True): result_attribute = conf.get_raw('cyrus-sasl', 'result_attribute') _entry = None - db = init_db(domain) + _db = init_db(domain) try: _uniqueid = str(UUID(bytes_le=entry'id')) - log.debug(_("Entry uniqueid was converted from binary form to string: %s") % _uniqueid, level=8) + log.debug( + _("Entry uniqueid was converted from binary form to string: %s") % _uniqueid, + level=8 + ) + except ValueError: _uniqueid = entry'id' try: - _entry = db.query(Entry).filter_by(uniqueid=_uniqueid).first() - except sqlalchemy.exc.OperationalError, errmsg: - db = init_db(domain,reinit=True) - except sqlalchemy.exc.InvalidRequestError, errmsg: - db = init_db(domain,reinit=True) + _entry = _db.query(Entry).filter_by(uniqueid=_uniqueid).first() + except sqlalchemy.exc.OperationalError: + _db = init_db(domain, reinit=True) + except sqlalchemy.exc.InvalidRequestError: + _db = init_db(domain, reinit=True) finally: - _entry = db.query(Entry).filter_by(uniqueid=_uniqueid).first() + _entry = _db.query(Entry).filter_by(uniqueid=_uniqueid).first() if not update: return _entry - if _entry == None: + if _entry is None: log.debug(_("Inserting cache entry %r") % (_uniqueid), level=8) - if not entry.has_key(result_attribute): + if result_attribute not in entry: entryresult_attribute = '' - db.add( - Entry( - _uniqueid, - entryresult_attribute, - entry'modifytimestamp' - ) - ) + _db.add(Entry(_uniqueid, entryresult_attribute, entry'modifytimestamp')) - db.commit() - _entry = db.query(Entry).filter_by(uniqueid=_uniqueid).first() + _db.commit() + _entry = _db.query(Entry).filter_by(uniqueid=_uniqueid).first() else: modifytimestamp_format = conf.get_raw( 'ldap', @@ -158,24 +143,30 @@ if not _entry.last_change.strftime(modifytimestamp_format) == entry'modifytimestamp': log.debug(_("Updating timestamp for cache entry %r") % (_uniqueid), level=8) - last_change = datetime.datetime.strptime(entry'modifytimestamp', modifytimestamp_format) + last_change = datetime.datetime.strptime( + entry'modifytimestamp', + modifytimestamp_format + ) + _entry.last_change = last_change - db.commit() - _entry = db.query(Entry).filter_by(uniqueid=_uniqueid).first() + _db.commit() + _entry = _db.query(Entry).filter_by(uniqueid=_uniqueid).first() - if entry.has_key(result_attribute):
View file
pykolab-0.8.15.tar.gz/pykolab/base.py -> pykolab-0.8.16.tar.gz/pykolab/base.py
Changed
@@ -19,14 +19,16 @@ import pykolab from pykolab.imap import IMAP +# pylint: disable=invalid-name conf = pykolab.getConf() -class Base(object): + +class Base: """ Abstraction class for functions commonly shared between auth, imap, etc. """ def __init__(self, *args, **kw): - if kw.has_key('domain') and not kw'domain' == None: + if 'domain' in kw and kw'domain' is not None: self.domain = kw'domain' else: self.domain = conf.get('kolab', 'primary_domain') @@ -38,9 +40,9 @@ self.imap = IMAP() self.domain_rootdns = {} - def config_get(self, key1, key2=None): - if not key2 == None: - return conf.get(key1, key2) + def config_get(self, key1, key2=None, default=None): + if key2 is not None: + return conf.get(key1, key2, default=default) if conf.has_option(self.domain, key1): return conf.get(self.domain, key1) @@ -55,11 +57,11 @@ if conf.has_option('kolab', key1): return conf.get('kolab', key1) - return None + return default - def config_get_list(self, key1, key2=None): - if not key2 == None: - return conf.get_list(key1, key2) + def config_get_list(self, key1, key2=None, default=None): + if key2 is not None: + return conf.get_list(key1, key2, default=default) if conf.has_option(self.domain, key1): return conf.get_list(self.domain, key1) @@ -74,11 +76,11 @@ if conf.has_option('kolab', key1): return conf.get_list('kolab', key1) - return None + return default - def config_get_raw(self, key1, key2=None): - if not key2 == None: - return conf.get_raw(key1, key2) + def config_get_raw(self, key1, key2=None, default=None): + if key2 is not None: + return conf.get_raw(key1, key2, default=default) if conf.has_option(self.domain, key1): return conf.get_raw(self.domain, key1) @@ -93,5 +95,4 @@ if conf.has_option('kolab', key1): return conf.get_raw('kolab', key1) - return None - + return default
View file
pykolab-0.8.15.tar.gz/pykolab/conf/__init__.py -> pykolab-0.8.16.tar.gz/pykolab/conf/__init__.py
Changed
@@ -16,6 +16,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # +from __future__ import print_function import logging import os @@ -33,6 +34,7 @@ log = pykolab.getLogger('pykolab.conf') + class Conf(object): def __init__(self): """ @@ -53,7 +55,7 @@ try: from pykolab.conf.entitlement import Entitlement entitlements = True - except: + except Exception: entitlements = False pass @@ -68,7 +70,7 @@ # Create the options self.create_options() - def finalize_conf(self,fatal=True): + def finalize_conf(self, fatal=True): self.create_options_from_plugins() self.parse_options(fatal=fatal) @@ -84,8 +86,15 @@ # But, they should be available in our class as well for option in self.defaults.__dict__.keys(): - log.debug(_("Setting %s to %r (from defaults)") % (option, self.defaults.__dict__option), level=8) - setattr(self,option,self.defaults.__dict__option) + log.debug( + _("Setting %s to %r (from defaults)") % ( + option, + self.defaults.__dict__option + ), + level=8 + ) + + setattr(self, option, self.defaults.__dict__option) # This is where we check our parser for the defaults being set there. self.set_defaults_from_cli_options() @@ -93,21 +102,41 @@ self.options_set_from_config() # Also set the cli options - if hasattr(self,'cli_keywords') and not self.cli_keywords == None: + if hasattr(self, 'cli_keywords') and self.cli_keywords is not None: for option in self.cli_keywords.__dict__.keys(): retval = False if hasattr(self, "check_setting_%s" % (option)): - exec("retval = self.check_setting_%s(%r)" % (option, self.cli_keywords.__dict__option)) - - # The warning, error or confirmation dialog is in the check_setting_%s() function + exec( + "retval = self.check_setting_%s(%r)" % ( + option, + self.cli_keywords.__dict__option + ) + ) + + # The warning, error or confirmation dialog is in the check_setting_%s() + # function if not retval: continue - log.debug(_("Setting %s to %r (from CLI, verified)") % (option, self.cli_keywords.__dict__option), level=8) - setattr(self,option,self.cli_keywords.__dict__option) + log.debug( + _("Setting %s to %r (from CLI, verified)") % ( + option, + self.cli_keywords.__dict__option + ), + level=8 + ) + + setattr(self, option, self.cli_keywords.__dict__option) else: - log.debug(_("Setting %s to %r (from CLI, not checked)") % (option, self.cli_keywords.__dict__option), level=8) - setattr(self,option,self.cli_keywords.__dict__option) + log.debug( + _("Setting %s to %r (from CLI, not checked)") % ( + option, + self.cli_keywords.__dict__option + ), + level=8 + ) + + setattr(self, option, self.cli_keywords.__dict__option) def load_config(self, config): """ @@ -128,18 +157,18 @@ continue if isinstance(self.defaults.__dict__sectionkey, int): - value = config.getint(section,key) + value = config.getint(section, key) elif isinstance(self.defaults.__dict__sectionkey, bool): - value = config.getboolean(section,key) + value = config.getboolean(section, key) elif isinstance(self.defaults.__dict__sectionkey, str): - value = config.get(section,key) + value = config.get(section, key) elif isinstance(self.defaults.__dict__sectionkey, list): - value = eval(config.get(section,key)) + value = eval(config.get(section, key)) elif isinstance(self.defaults.__dict__sectionkey, dict): - value = eval(config.get(section,key)) + value = eval(config.get(section, key)) - if hasattr(self,"check_setting_%s_%s" % (section,key)): - exec("retval = self.check_setting_%s_%s(%r)" % (section,key,value)) + if hasattr(self, "check_setting_%s_%s" % (section, key)): + exec("retval = self.check_setting_%s_%s(%r)" % (section, key, value)) if not retval: # We just don't set it, check_setting_%s should have # taken care of the error messages @@ -147,10 +176,25 @@ if not self.defaults.__dict__sectionkey == value: if key.count('password') >= 1: - log.debug(_("Setting %s_%s to '****' (from configuration file)") % (section,key), level=8) + log.debug( + _("Setting %s_%s to '****' (from configuration file)") % ( + section, + key + ), + level=8 + ) + else: - log.debug(_("Setting %s_%s to %r (from configuration file)") % (section,key,value), level=8) - setattr(self,"%s_%s" % (section,key),value) + log.debug( + _("Setting %s_%s to %r (from configuration file)") % ( + section, + key, + value + ), + level=8 + ) + + setattr(self, "%s_%s" % (section, key), value) def options_set_from_config(self): """ @@ -165,7 +209,7 @@ # Other then default? self.config_file = self.defaults.config_file - if hasattr(self,'cli_keywords') and not self.cli_keywords == None: + if hasattr(self, 'cli_keywords') and self.cli_keywords is not None: if not self.cli_keywords.config_file == self.defaults.config_file: self.config_file = self.cli_keywords.config_file @@ -185,28 +229,35 @@ retval = False if isinstance(self.defaults.__dict__'testing'key, int): - value = config.getint('testing',key) + value = config.getint('testing', key) elif isinstance(self.defaults.__dict__'testing'key, bool): - value = config.getboolean('testing',key) + value = config.getboolean('testing', key) elif isinstance(self.defaults.__dict__'testing'key, str): - value = config.get('testing',key) + value = config.get('testing', key) elif isinstance(self.defaults.__dict__'testing'key, list): - value = eval(config.get('testing',key)) + value = eval(config.get('testing', key)) elif isinstance(self.defaults.__dict__'testing'key, dict): - value = eval(config.get('testing',key)) + value = eval(config.get('testing', key)) - if hasattr(self,"check_setting_%s_%s" % ('testing',key)): - exec("retval = self.check_setting_%s_%s(%r)" % ('testing',key,value)) + if hasattr(self, "check_setting_%s_%s" % ('testing', key)): + exec("retval = self.check_setting_%s_%s(%r)" % ('testing', key, value)) if not retval: # We just don't set it, check_setting_%s should have # taken care of the error messages continue - setattr(self,"%s_%s" % ('testing',key),value) + setattr(self, "%s_%s" % ('testing', key), value) if key.count('password') >= 1: - log.debug(_("Setting %s_%s to '****' (from configuration file)") % ('testing',key), level=8) + log.debug( + _("Setting %s_%s to '****' (from configuration file)") % ('testing', key),
View file
pykolab-0.8.15.tar.gz/pykolab/conf/defaults.py -> pykolab-0.8.16.tar.gz/pykolab/conf/defaults.py
Changed
@@ -19,6 +19,7 @@ import logging + class Defaults(object): def __init__(self, plugins=None): self.loglevel = logging.CRITICAL @@ -33,10 +34,12 @@ self.mail_attributes = 'mail', 'alias' self.mailserver_attribute = 'mailhost' - # when you want a new domain to be added in a short time, you should reduce this value to 10 seconds + # when you want a new domain to be added in a short time, you should reduce this value to + # 10 seconds self.kolab_domain_sync_interval = 600 self.kolab_default_locale = 'en_US' + self.ldap_timeout = 10 self.ldap_unique_attribute = 'nsuniqueid' - self.wallace_resource_calendar_expire_days = 100 \ No newline at end of file + self.wallace_resource_calendar_expire_days = 100
View file
pykolab-0.8.15.tar.gz/pykolab/imap/__init__.py -> pykolab-0.8.16.tar.gz/pykolab/imap/__init__.py
Changed
@@ -54,20 +54,16 @@ if len(aci_subject.split('@')) > 1: lm_suffix = "@%s" % (aci_subject.split('@')1) - shared_folders = self.imap.lm( - "shared/*%s" % (lm_suffix) - ) + shared_folders = self.imap.lm("shared/*%s" % (lm_suffix)) - user_folders = self.imap.lm( - "user/*%s" % (lm_suffix) - ) + user_folders = self.imap.lm("user/*%s" % (lm_suffix)) log.debug( - _("Cleaning up ACL entries referring to identifier %s") % ( - aci_subject - ), - level=5 - ) + _("Cleaning up ACL entries referring to identifier %s") % ( + aci_subject + ), + level=5 + ) # For all folders (shared and user), ... folders = user_folders + shared_folders @@ -128,12 +124,12 @@ # deployment. backend = conf.get('kolab', 'imap_backend') - if not domain == None: + if domain is not None: self.domain = domain if conf.has_section(domain) and conf.has_option(domain, 'imap_backend'): backend = conf.get(domain, 'imap_backend') - if uri == None: + if uri is None: if conf.has_section(domain) and conf.has_option(domain, 'imap_uri'): uri = conf.get(domain, 'imap_uri') else: @@ -143,7 +139,7 @@ hostname = None port = None - if uri == None: + if uri is None: uri = conf.get(backend, 'uri') result = urlparse(uri) @@ -162,13 +158,13 @@ scheme = uri.split(':')0 (hostname, port) = uri.split('/')2.split(':') - if not server == None: + if server is not None: hostname = server - if scheme == None or scheme == "": + if scheme is None or scheme == "": scheme = 'imaps' - if port == None: + if port is None: if scheme == "imaps": port = 993 elif scheme == "imap": @@ -182,10 +178,10 @@ admin_login = conf.get(backend, 'admin_login') admin_password = conf.get(backend, 'admin_password') - if admin_password == None or admin_password == '': + if admin_password is None or admin_password == '': log.error(_("No administrator password is available.")) - if not self._imap.has_key(hostname): + if hostname not in self._imap: if backend == 'cyrus-imap': import cyrus self._imaphostname = cyrus.Cyrus(uri) @@ -216,19 +212,25 @@ else: if not login: self.disconnect(hostname) - self.connect(uri=uri,login=False) - elif login and not hasattr(self._imaphostname,'logged_in'): + self.connect(uri=uri, login=False) + elif login and not hasattr(self._imaphostname, 'logged_in'): self.disconnect(hostname) self.connect(uri=uri) else: try: if hasattr(self._imaphostname, 'm'): self._imaphostname.m.noop() - elif hasattr(self._imaphostname, 'noop') and callable(self._imaphostname.noop): + elif hasattr(self._imaphostname, 'noop') \ + and callable(self._imaphostname.noop): + self._imaphostname.noop() - log.debug(_("Reusing existing IMAP server connection to %s") % (hostname), level=8) - except: + log.debug( + _("Reusing existing IMAP server connection to %s") % (hostname), + level=8 + ) + + except Exception: log.debug(_("Reconnecting to IMAP server %s") % (hostname), level=8) self.disconnect(hostname) self.connect() @@ -243,7 +245,7 @@ self._set_socket_keepalive(self.imap.sock) def disconnect(self, server=None): - if server == None: + if server is None: # No server specified, but make sure self.imap is None anyways if hasattr(self, 'imap'): del self.imap @@ -253,33 +255,30 @@ del self._imapkey else: - if self._imap.has_key(server): + if server in self._imap: del self._imapserver else: - log.warning(_("Called imap.disconnect() on a server that we had no connection to.")) + log.warning( + _("Called imap.disconnect() on a server that we had no connection to.") + ) def create_folder(self, folder_path, server=None, partition=None): folder_path = self.folder_utf7(folder_path) - if not server == None: + if server is not None: self.connect(server=server) try: self._imapserver.cm(folder_path, partition=partition) return True - except: - log.error( - _("Could not create folder %r on server %r") % ( - folder_path, - server - ) - ) + except Exception: + log.error(_("Could not create folder %r on server %r") % (folder_path, server)) else: try: self.imap.cm(folder_path, partition=partition) return True - except: + except Exception: log.error(_("Could not create folder %r") % (folder_path)) return False @@ -290,9 +289,9 @@ if hasattr(self.imap.m, name): return getattr(self.imap.m, name) else: - raise AttributeError, _("%r has no attribute %s") % (self,name) + raise AttributeError(_("%r has no attribute %s") % (self, name)) else: - raise AttributeError, _("%r has no attribute %s") % (self,name) + raise AttributeError(_("%r has no attribute %s") % (self, name)) def folder_utf7(self, folder): from pykolab import imap_utf7 @@ -313,13 +312,13 @@ _metadata = self.imap.getannotation(self.folder_utf7(folder), '*') - for (k,v) in _metadata.items(): + for (k, v) in _metadata.items(): metadataself.folder_utf8(k) = v return metadata def get_separator(self): - if not hasattr(self, 'imap') or self.imap == None: + if not hasattr(self, 'imap') or self.imap is None: self.connect() if hasattr(self.imap, 'separator'): @@ -357,13 +356,13 @@ if len(_namespaces) >= 3: _shared = - _shared.append(' '.join(_namespaces2.replace('((','').replace('))','').split():-1).replace('"', '')) + _shared.append(' '.join(_namespaces2.replace('((', '').replace('))', '').split():-1).replace('"', '')) if len(_namespaces) >= 2:
View file
pykolab-0.8.15.tar.gz/pykolab/logger.py -> pykolab-0.8.16.tar.gz/pykolab/logger.py
Changed
@@ -16,6 +16,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # +from __future__ import print_function import grp import logging @@ -23,11 +24,9 @@ import os import pwd import sys -import time -from pykolab.translate import _ -class StderrToLogger(object): +class StderrToLogger: """ Fake file-like stream object that redirects writes to a logger instance. """ @@ -36,7 +35,7 @@ self.log_level = log_level self.linebuf = '' self.skip_next = False - + def write(self, buf): # ugly patch to make smtplib and smtpd debug logging records appear on one line in log file # smtplib uses "print>>stderr, var, var" statements for debug logging. These @@ -59,10 +58,11 @@ else: self.logger.log(self.log_level, '%s %s', self.linebuf, line.rstrip():150) self.linebuf = '' - - def flush(self): + + def flush(self): pass + class LoggerAdapter(logging.LoggerAdapter): """ Custom LoggingAdapter to log Wallace mail message Queue ID @@ -71,6 +71,7 @@ def process(self, msg, kwargs): return '%s %s' % (self.extra'qid', msg), kwargs + class Logger(logging.Logger): """ The PyKolab version of a logger. @@ -88,31 +89,31 @@ for arg in sys.argv: if debuglevel == -1: try: - debuglevel = int(arg) - except ValueError, errmsg: + debuglevel = (int)(arg) + except ValueError: continue loglevel = logging.DEBUG break - if '-d' == arg: + if arg == '-d': debuglevel = -1 continue - if '-l' == arg: + if arg == '-l': loglevel = -1 continue - if '--fork' == arg: + if arg == '--fork': fork = True if loglevel == -1: - if hasattr(logging,arg.upper()): - loglevel = getattr(logging,arg.upper()) + if hasattr(logging, arg.upper()): + loglevel = getattr(logging, arg.upper()) else: loglevel = logging.DEBUG - if '-u' == arg or '--user' == arg: + if arg in '-u', '--user': process_username = -1 continue @@ -122,7 +123,7 @@ if process_username == -1: process_username = arg - if '-g' == arg or '--group' == arg: + if arg in '-g', '--group': process_groupname = -1 continue @@ -132,8 +133,11 @@ if process_groupname == -1: process_groupname = arg + # pylint: disable=too-many-branches + # pylint: disable=too-many-locals + # pylint: disable=too-many-statements def __init__(self, *args, **kw): - if kw.has_key('name'): + if 'name' in kw: name = kw'name' elif len(args) == 1: name = args0 @@ -142,7 +146,9 @@ logging.Logger.__init__(self, name) - plaintextformatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(process)d %(message)s") + plaintextformatter = logging.Formatter( + "%(asctime)s %(name)s %(levelname)s %(process)d %(message)s" + ) if not self.fork: self.console_stdout = logging.StreamHandler(sys.stdout) @@ -150,7 +156,7 @@ self.addHandler(self.console_stdout) - if kw.has_key('logfile'): + if 'logfile' in kw: self.logfile = kw'logfile' else: self.logfile = '/var/log/kolab/pykolab.log' @@ -161,9 +167,9 @@ # Make sure (read: attempt to change) the permissions try: try: - (ruid, euid, suid) = os.getresuid() - (rgid, egid, sgid) = os.getresgid() - except AttributeError, errmsg: + (ruid, _, _) = os.getresuid() + (rgid, _, _) = os.getresgid() + except AttributeError: ruid = os.getuid() rgid = os.getgid() @@ -173,48 +179,52 @@ # Get group entry details try: ( - group_name, - group_password, - group_gid, - group_members - ) = grp.getgrnam(self.process_groupname) + _, + _, + group_gid, + _ + ) = grp.getgrnam(self.process_groupname) - except KeyError, errmsg: - group_name = False + except KeyError: + group_gid = False if ruid == 0: # Means we haven't switched yet. try: ( - user_name, - user_password, - user_uid, - user_gid, - user_gecos, - user_homedir, - user_shell - ) = pwd.getpwnam(self.process_username) - - except KeyError, errmsg: - user_name = False + _, + _, + user_uid, + _, + _, + _, + _ + ) = pwd.getpwnam(self.process_username) + + except KeyError: + user_uid = False if os.path.isfile(self.logfile): try: - if not user_uid == 0 or group_gid == 0: + if user_uid > 0 or group_gid > 0: os.chown( - self.logfile,
View file
pykolab-0.8.15.tar.gz/pykolab/plugins/__init__.py -> pykolab-0.8.16.tar.gz/pykolab/plugins/__init__.py
Changed
@@ -30,6 +30,7 @@ log = pykolab.getLogger('pykolab.plugins') conf = pykolab.getConf() + class KolabPlugins(object): """ Detects, loads and interfaces with plugins for different @@ -50,7 +51,7 @@ if os.path.isdir(plugin_path): for plugin in os.listdir(plugin_path): - if os.path.isdir('%s/%s/' % (plugin_path,plugin,)): + if os.path.isdir('%s/%s/' % (plugin_path, plugin, )): self.pluginsplugin = False self.check_plugins() @@ -67,11 +68,11 @@ self.pluginsplugin = True self.load_plugins(plugins=plugin) except ImportError, e: - log.error(_("ImportError for plugin %s: %s") % (plugin,e)) + log.error(_("ImportError for plugin %s: %s") % (plugin, e)) traceback.print_exc() self.pluginsplugin = False except RuntimeError, e: - log.error( _("RuntimeError for plugin %s: %s") % (plugin,e)) + log.error( _("RuntimeError for plugin %s: %s") % (plugin, e)) traceback.print_exc() self.pluginsplugin = False except Exception, e: @@ -91,7 +92,7 @@ for plugin in plugins: if self.pluginsplugin: try: - exec("self.%s = %s.Kolab%s()" % (plugin,plugin,plugin.capitalize())) + exec("self.%s = %s.Kolab%s()" % (plugin, plugin, plugin.capitalize())) except: # TODO: A little better verbosity please! traceback.print_exc() @@ -106,16 +107,16 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),"set_defaults"): + if hasattr(getattr(self, plugin), "set_defaults"): try: - getattr(self,plugin).set_defaults(defaults) + getattr(self, plugin).set_defaults(defaults) except TypeError, e: - log.error(_("Cannot set defaults for plugin %s: %s") % (plugin,e)) + log.error(_("Cannot set defaults for plugin %s: %s") % (plugin, e)) except RuntimeError, e: - log.error(_("Cannot set defaults for plugin %s: %s") % (plugin,e)) + log.error(_("Cannot set defaults for plugin %s: %s") % (plugin, e)) except: log.error(_("Cannot set defaults for plugin %s: Unknown Error") % (plugin)) @@ -132,14 +133,14 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),"set_runtime"): + if hasattr(getattr(self, plugin), "set_runtime"): try: - getattr(self,plugin).set_runtime(runtime) + getattr(self, plugin).set_runtime(runtime) except RuntimeError, e: - log.error(_("Cannot set runtime for plugin %s: %s") % (plugin,e)) + log.error(_("Cannot set runtime for plugin %s: %s") % (plugin, e)) else: log.debug(_("Not setting runtime for plugin %s: No function 'set_runtime()'") % (plugin), level=5) @@ -153,16 +154,16 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),"add_options"): + if hasattr(getattr(self, plugin), "add_options"): try: exec("self.%s.add_options(parser)" % plugin) except RuntimeError, e: - log.error(_("Cannot add options for plugin %s: %s") % (plugin,e)) + log.error(_("Cannot add options for plugin %s: %s") % (plugin, e)) except TypeError, e: - log.error(_("Cannot add options for plugin %s: %s") % (plugin,e)) + log.error(_("Cannot add options for plugin %s: %s") % (plugin, e)) else: log.debug(_("Not adding options for plugin %s: No function 'add_options()'") % plugin, level=5) @@ -177,14 +178,14 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),"check_options"): + if hasattr(getattr(self, plugin), "check_options"): try: exec("self.%s.check_options()" % plugin) except AttributeError, e: - log.error(_("Cannot check options for plugin %s: %s") % (plugin,e)) + log.error(_("Cannot check options for plugin %s: %s") % (plugin, e)) else: log.debug(_("Not checking options for plugin %s: No function 'check_options()'") % (plugin), level=5) @@ -199,11 +200,11 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),"%s_%s" % (func,option)): - exec("retval = getattr(self,plugin).%s_%s(val)" % (func,option)) + if hasattr(getattr(self, plugin), "%s_%s" % (func, option)): + exec("retval = getattr(self, plugin).%s_%s(val)" % (func, option)) return retval return False @@ -219,23 +220,34 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),hook): + if hasattr(getattr(self, plugin), hook): try: - log.debug(_("Executing hook %s for plugin %s") % (hook,plugin), level=8) - #print "retval = self.%s.%s(%r, %r)" % (plugin,hook, args, kw) - exec("retval = self.%s.%s(*args, **kw)" % (plugin,hook)) - except TypeError, e: - log.error(_("Cannot execute hook %s for plugin %s: %s") % (hook,plugin,e)) - except AttributeError, e: - log.error(_("Cannot execute hook %s for plugin %s: %s") % (hook,plugin,e)) + log.debug(_("Executing hook %s for plugin %s") % (hook, plugin), level=8) + func = getattr(getattr(self, plugin), hook) + retval = func(*args, **kw) + except TypeError as errmsg: + log.error( + _("Cannot execute hook %s for plugin %s: %s") % (hook, plugin, errmsg) + ) + + log.error(traceback.format_exc()) + except AttributeError as errmsg: + log.error( + _("Cannot execute hook %s for plugin %s: %s") % (hook, plugin, errmsg) + ) + + log.error(traceback.format_exc()) return retval def return_true_boolean_from_plugins(self, bool, plugins=): - """Given the name of a boolean, walks all specified plugins, or all available plugins, and returns True if a plugin has it set to true""" + """ + Given the name of a boolean, walks all specified plugins, or all available plugins, and + returns True if a plugin has it set to true + """ if len(plugins) < 1: plugins = self.plugins.keys() @@ -244,12 +256,12 @@ for plugin in plugins: if not self.pluginsplugin: continue - if not hasattr(self,plugin): + if not hasattr(self, plugin): continue - if hasattr(getattr(self,plugin),bool): + if hasattr(getattr(self, plugin), bool): try: - exec("boolval = self.%s.%s" % (plugin,bool)) + exec("boolval = self.%s.%s" % (plugin, bool)) except AttributeError, e: pass else:
View file
pykolab-0.8.15.tar.gz/pykolab/setup/setup_imap.py -> pykolab-0.8.16.tar.gz/pykolab/setup/setup_imap.py
Changed
@@ -49,6 +49,17 @@ Apply the necessary settings to /etc/imapd.conf """ + configdirectory = "/var/lib/imap/" + partition_default = "/var/spool/imap/" + sievedir = "/var/lib/imap/sieve/" + + if os.path.isdir("/var/lib/cyrus/"): + configdirectory = "/var/lib/cyrus/" + sievedir = "/var/lib/cyrus/sieve/" + + if os.path.isdir("/var/spool/cyrus/mail/"): + partition_default = "/var/spool/cyrus/mail/" + imapd_settings = { "ldap_servers": conf.get('ldap', 'ldap_uri'), "ldap_base": conf.get('ldap', 'base_dn'), @@ -64,6 +75,9 @@ "ldap_member_attribute": "nsrole", "admins": conf.get('cyrus-imap', 'admin_login'), "postuser": "shared", + "configdirectory": configdirectory, + "partition_default": partition_default, + "sievedir": sievedir } template_file = None
View file
pykolab-0.8.15.tar.gz/pykolab/setup/setup_mysql.py -> pykolab-0.8.16.tar.gz/pykolab/setup/setup_mysql.py
Changed
@@ -49,6 +49,14 @@ ) mysql_group.add_option( + "--mysqlhost", + dest="mysqlhost", + action="store", + default='127.0.0.1', + help=_("The MySQL host address.") + ) + + mysql_group.add_option( "--mysqlrootpw", dest="mysqlrootpw", action="store", @@ -70,45 +78,46 @@ # on CentOS7, there is MariaDB instead of MySQL - mysqlservice = 'mysqld.service' - if os.path.isfile('/usr/lib/systemd/system/mariadb.service'): - mysqlservice = 'mariadb.service' - elif os.path.isfile('/usr/lib/systemd/system/mysql.service'): - mysqlservice = 'mysql.service' - if not os.path.isfile('/usr/lib/systemd/system/' + mysqlservice): - # on Debian Jessie, systemctl restart mysql - mysqlservice = 'mysql' - - if os.path.isfile('/bin/systemctl'): - subprocess.call('/bin/systemctl', 'restart', mysqlservice) - elif os.path.isfile('/sbin/service'): - subprocess.call('/sbin/service', 'mysqld', 'restart') - elif os.path.isfile('/usr/sbin/service'): - subprocess.call('/usr/sbin/service', 'mysql', 'restart') - else: - log.error(_("Could not start the MySQL database service.")) - - if os.path.isfile('/bin/systemctl'): - subprocess.call('/bin/systemctl', 'enable', mysqlservice) - elif os.path.isfile('/sbin/chkconfig'): - subprocess.call('/sbin/chkconfig', 'mysqld', 'on') - elif os.path.isfile('/usr/sbin/update-rc.d'): - subprocess.call('/usr/sbin/update-rc.d', 'mysql', 'defaults') - else: - log.error( - _("Could not configure to start on boot, the MySQL database service.") - ) + if conf.mysqlserver != 'existing': + mysqlservice = 'mysqld.service' + if os.path.isfile('/usr/lib/systemd/system/mariadb.service'): + mysqlservice = 'mariadb.service' + elif os.path.isfile('/usr/lib/systemd/system/mysql.service'): + mysqlservice = 'mysql.service' + if not os.path.isfile('/usr/lib/systemd/system/' + mysqlservice): + # on Debian Jessie, systemctl restart mysql + mysqlservice = 'mysql' + + if os.path.isfile('/bin/systemctl'): + subprocess.call('/bin/systemctl', 'restart', mysqlservice) + elif os.path.isfile('/sbin/service'): + subprocess.call('/sbin/service', 'mysqld', 'restart') + elif os.path.isfile('/usr/sbin/service'): + subprocess.call('/usr/sbin/service', 'mysql', 'restart') + else: + log.error(_("Could not start the MySQL database service.")) + + if os.path.isfile('/bin/systemctl'): + subprocess.call('/bin/systemctl', 'enable', mysqlservice) + elif os.path.isfile('/sbin/chkconfig'): + subprocess.call('/sbin/chkconfig', 'mysqld', 'on') + elif os.path.isfile('/usr/sbin/update-rc.d'): + subprocess.call('/usr/sbin/update-rc.d', 'mysql', 'defaults') + else: + log.error( + _("Could not configure to start on boot, the MySQL database service.") + ) - log.info(_("Waiting for at most 30 seconds for MySQL/MariaDB to settle...")) - max_wait = 30 - while max_wait > 0: - for socket_path in socket_paths: - if os.path.exists(socket_path): - max_wait = 0 + log.info(_("Waiting for at most 30 seconds for MySQL/MariaDB to settle...")) + max_wait = 30 + while max_wait > 0: + for socket_path in socket_paths: + if os.path.exists(socket_path): + max_wait = 0 - if max_wait > 0: - max_wait = max_wait - 1 - time.sleep(1) + if max_wait > 0: + max_wait = max_wait - 1 + time.sleep(1) options = { 1: "Existing MySQL server (with root password already set).", @@ -116,14 +125,17 @@ } answer = 0 - if len(x for x in socket_paths if os.path.exists(x)) > 0: - if conf.mysqlserver: - if conf.mysqlserver == 'existing': - answer = 1 - elif conf.mysqlserver == 'new': - answer = 2 - if answer == 0: - answer = utils.ask_menu(_("What MySQL server are we setting up?"), options) + if conf.mysqlserver != 'existing': + if len(x for x in socket_paths if os.path.exists(x)) > 0: + if conf.mysqlserver: + if conf.mysqlserver == 'existing': + answer = 1 + elif conf.mysqlserver == 'new': + answer = 2 + if answer == 0: + answer = utils.ask_menu(_("What MySQL server are we setting up?"), options) + else: + answer = 1 if answer == "1" or answer == 1: if not conf.mysqlrootpw: @@ -214,7 +226,8 @@ mysql user=root password='%s' -""" % (mysql_root_password) +host=%s +""" % (mysql_root_password, conf.mysqlhost) fp = open('/tmp/kolab-setup-my.cnf', 'w') os.chmod('/tmp/kolab-setup-my.cnf', 600)
View file
pykolab-0.8.15.tar.gz/pykolab/setup/setup_roundcube.py -> pykolab-0.8.16.tar.gz/pykolab/setup/setup_roundcube.py
Changed
@@ -232,7 +232,8 @@ mysql user=root password='%s' -""" % (mysql_root_password) +host=%s +""" % (mysql_root_password, conf.mysqlhost) fp = open('/tmp/kolab-setup-my.cnf', 'w') os.chmod('/tmp/kolab-setup-my.cnf', 600)
View file
pykolab-0.8.15.tar.gz/pykolab/setup/setup_syncroton.py -> pykolab-0.8.16.tar.gz/pykolab/setup/setup_syncroton.py
Changed
@@ -33,12 +33,20 @@ log = pykolab.getLogger('pykolab.setup') conf = pykolab.getConf() + def __init__(): - components.register('syncroton', execute, description=description(), after='mysql','ldap','roundcube') + components.register( + 'syncroton', + execute, + description=description(), + after='mysql','ldap','roundcube' + ) + def description(): return _("Setup Syncroton.") + def execute(*args, **kw): schema_files = for root, directories, filenames in os.walk('/usr/share/doc/'): @@ -71,7 +79,8 @@ mysql user=root password='%s' -""" % (mysql_root_password) +host=%s +""" % (mysql_root_password, conf.mysqlhost) fp = open('/tmp/kolab-setup-my.cnf', 'w') os.chmod('/tmp/kolab-setup-my.cnf', 0600)
View file
pykolab-0.8.15.tar.gz/pykolab/utils.py -> pykolab-0.8.16.tar.gz/pykolab/utils.py
Changed
@@ -17,21 +17,38 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # +from __future__ import print_function + import base64 import getpass import grp import os import pwd +from six import string_types import struct import sys import pykolab from pykolab import constants -from pykolab.translate import _ +from pykolab.translate import _ as _l +# pylint: disable=invalid-name log = pykolab.getLogger('pykolab.utils') conf = pykolab.getConf() +try: + # pylint: disable=redefined-builtin + input = raw_input +except NameError: + pass + +try: + unicode('') +except NameError: + unicode = str + + +# pylint: disable=too-many-branches def ask_question(question, default="", password=False, confirm=False): """ Ask a question on stderr. @@ -43,56 +60,57 @@ Usage: pykolab.utils.ask_question("What is the server?", default="localhost") """ - - if not default == "" and not default == None and conf.cli_keywords.answer_default: + if default != "" and default is not None and conf.cli_keywords.answer_default: if not conf.cli_keywords.quiet: - print ("%s %s: " % (question, default)) + print("%s %s: " % (question, default)) return default if password: - if default == "" or default == None: + if default == "" or default is None: answer = getpass.getpass("%s: " % (question)) else: answer = getpass.getpass("%s %s: " % (question, default)) else: - if default == "" or default == None: - answer = raw_input("%s: " % (question)) + if default == "" or default is None: + answer = input("%s: " % (question)) else: - answer = raw_input("%s %s: " % (question, default)) + answer = input("%s %s: " % (question, default)) + # pylint: disable=too-many-nested-blocks if not answer == "": if confirm: answer_confirm = None answer_confirmed = False while not answer_confirmed: if password: - answer_confirm = getpass.getpass(_("Confirm %s: ") % (question)) + answer_confirm = getpass.getpass(_l("Confirm %s: ") % (question)) else: - answer_confirm = raw_input(_("Confirm %s: ") % (question)) + answer_confirm = input(_l("Confirm %s: ") % (question)) if not answer_confirm == answer: - print >> sys.stderr, _("Incorrect confirmation. " + \ - "Please try again.") + print(_l("Incorrect confirmation. Please try again."), file=sys.stderr) if password: - if default == "" or default == None: - answer = getpass.getpass(_("%s: ") % (question)) + if default == "" or default is None: + answer = getpass.getpass(_l("%s: ") % (question)) else: - answer = getpass.getpass(_("%s %s: ") % (question, default)) + answer = getpass.getpass(_l("%s %s: ") % (question, default)) else: - if default == "" or default == None: - answer = raw_input(_("%s: ") % (question)) + if default == "" or default is None: + answer = input(_l("%s: ") % (question)) else: - answer = raw_input(_("%s %s: ") % (question, default)) + answer = input(_l("%s %s: ") % (question, default)) else: answer_confirmed = True if answer == "": return default - else: - return answer + return answer + + +# pylint: disable=too-many-return-statements def ask_confirmation(question, default="y", all_inclusive_no=True): """ Create a confirmation dialog, including a default option (capitalized), @@ -101,11 +119,11 @@ """ default_answer = None - if default in "y", "Y" : + if default in "y", "Y": default_answer = True default_no = "n" default_yes = "Y" - elif default in "n", "N" : + elif default in "n", "N": default_answer = False default_no = "N" default_yes = "y" @@ -115,44 +133,50 @@ default_no = "'no'" default_yes = "Please type 'yes'" - if conf.cli_keywords.answer_yes or (conf.cli_keywords.answer_default and default_answer is not None): + if conf.cli_keywords.answer_yes \ + or (conf.cli_keywords.answer_default and default_answer is not None): + if not conf.cli_keywords.quiet: - print ("%s %s/%s: " % (question,default_yes,default_no)) + print("%s %s/%s: " % (question, default_yes, default_no)) if conf.cli_keywords.answer_yes: return True if conf.cli_keywords.answer_default: return default_answer answer = False - while answer == False: - answer = raw_input("%s %s/%s: " % (question,default_yes,default_no)) + while not answer: + answer = input("%s %s/%s: " % (question, default_yes, default_no)) # Parse answer and set back to False if not appropriate if all_inclusive_no: - if answer == "" and not default_answer == None: + if answer == "" and default_answer is not None: return default_answer - elif answer in "y", "Y", "yes" : + + if answer in "y", "Y", "yes": return True - elif answer in "n", "N", "no" : - return False - else: - answer = False - print >> sys.stderr, _("Please answer 'yes' or 'no'.") - else: - if not answer in "y", "Y", "yes" : + + if answer in "n", "N", "no": return False - else: - return True + answer = False + print(_l("Please answer 'yes' or 'no'."), file=sys.stderr) + + if answer not in "y", "Y", "yes": + return False + + return True + + +# pylint: disable=dangerous-default-value def ask_menu(question, options={}, default=''): - if not default == '' and conf.cli_keywords.answer_default: + if default != '' and conf.cli_keywords.answer_default: if not conf.cli_keywords.quiet: - print question + " " + default + ":" + print(question + " " + default + ":") return default - if not default == '': - print question + " " + default + ":" + if default != '': + print(question + " " + default + ":") else: - print question + print(question)
View file
pykolab-0.8.15.tar.gz/pykolab/xml/attendee.py -> pykolab-0.8.16.tar.gz/pykolab/xml/attendee.py
Changed
@@ -33,6 +33,8 @@ "INDIVIDUAL": kolabformat.CutypeIndividual, "RESOURCE": kolabformat.CutypeResource, "GROUP": kolabformat.CutypeGroup, + "ROOM": kolabformat.CutypeRoom, + "UNKNOWN": kolabformat.CutypeUnknown, } participant_status_map = {
View file
pykolab-0.8.15.tar.gz/share/templates/freshclam.conf.tpl -> pykolab-0.8.16.tar.gz/share/templates/freshclam.conf.tpl
Changed
@@ -10,7 +10,7 @@ # Path to the log file (make sure it has proper permissions) # Default: disabled -UpdateLogFile /var/log/clamav/freshclam.log +# UpdateLogFile /var/log/clamav/freshclam.log # Maximum size of the log file. # Value of 0 disables the limit.
View file
pykolab-0.8.15.tar.gz/share/templates/imapd.conf.tpl -> pykolab-0.8.16.tar.gz/share/templates/imapd.conf.tpl
Changed
@@ -1,7 +1,7 @@ -configdirectory: /var/lib/imap -partition-default: /var/spool/imap +configdirectory: $configdirectory +partition-default: $partition_default admins: $admins -sievedir: /var/lib/imap/sieve +sievedir: $sievedir sendmail: /usr/sbin/sendmail sasl_pwcheck_method: saslauthd sasl_mech_list: PLAIN LOGIN
View file
pykolab-0.8.15.tar.gz/tests/unit/test-002-attendee.py -> pykolab-0.8.16.tar.gz/tests/unit/test-002-attendee.py
Changed
@@ -4,6 +4,7 @@ from pykolab.xml import Attendee from pykolab.xml import participant_status_label +from pykolab.xml.attendee import InvalidAttendeeCutypeError class TestEventXML(unittest.TestCase): @@ -96,17 +97,21 @@ self.assertEqual(k for k, v in self.attendee.role_map.iteritems() if v == 30, "NON-PARTICIPANT") def test_015_cutype_map_length(self): - self.assertEqual(len(self.attendee.cutype_map.keys()), 3) + self.assertEqual(len(self.attendee.cutype_map.keys()), 5) def test_016_cutype_map_forward_lookup(self): - self.assertEqual(self.attendee.cutype_map"GROUP", 1) - self.assertEqual(self.attendee.cutype_map"INDIVIDUAL", 2) - self.assertEqual(self.attendee.cutype_map"RESOURCE", 3) + self.assertEqual(self.attendee.cutype_map"GROUP", kolabformat.CutypeGroup) + self.assertEqual(self.attendee.cutype_map"INDIVIDUAL", kolabformat.CutypeIndividual) + self.assertEqual(self.attendee.cutype_map"RESOURCE", kolabformat.CutypeResource) + self.assertEqual(self.attendee.cutype_map"ROOM", kolabformat.CutypeRoom) + self.assertEqual(self.attendee.cutype_map"UNKNOWN", kolabformat.CutypeUnknown) def test_017_cutype_map_reverse_lookup(self): - self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == 10, "GROUP") - self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == 20, "INDIVIDUAL") - self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == 30, "RESOURCE") + self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == kolabformat.CutypeGroup0, "GROUP") + self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == kolabformat.CutypeIndividual0, "INDIVIDUAL") + self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == kolabformat.CutypeResource0, "RESOURCE") + self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == kolabformat.CutypeRoom0, "ROOM") + self.assertEqual(k for k, v in self.attendee.cutype_map.iteritems() if v == kolabformat.CutypeUnknown0, "UNKNOWN") def test_018_partstat_label(self): self.assertEqual(participant_status_label('NEEDS-ACTION'), "Needs Action") @@ -133,5 +138,8 @@ self.assertEqual(data'email', 'jane@doe.org') self.assertTrue(data'rsvp') + def test_030_to_cutype_exception(self): + self.assertRaises(InvalidAttendeeCutypeError, self.attendee.set_cutype, "DUMMY") + if __name__ == '__main__': unittest.main()
View file
pykolab-0.8.15.tar.gz/tests/unit/test-003-event.py -> pykolab-0.8.16.tar.gz/tests/unit/test-003-event.py
Changed
@@ -41,7 +41,7 @@ CLASS:PUBLIC ATTENDEE;CN="Manager, Jane";PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT;CUTYP E=INDIVIDUAL;RSVP=TRUE:mailto:jane.manager@example.org -ATTENDEE;CUTYPE=RESOURCE;PARTSTAT=NEEDS-ACTION;ROLE=OPT-PARTICIPANT;RSVP=FA +ATTENDEE;CUTYPE=ROOM;PARTSTAT=NEEDS-ACTION;ROLE=OPT-PARTICIPANT;RSVP=FA LSE:MAILTO:max@imum.com ORGANIZER;CN=Doe\, John:mailto:john.doe@example.org URL:http://somelink.com/foo @@ -495,7 +495,7 @@ self.assertEqual(event.get_categories(), "Personal") self.assertEqual(event.get_priority(), '2') self.assertEqual(event.get_classification(), kolabformat.ClassPublic) - self.assertEqual(event.get_attendee_by_email("max@imum.com").get_cutype(), kolabformat.CutypeResource) + self.assertEqual(event.get_attendee_by_email("max@imum.com").get_cutype(), kolabformat.CutypeRoom) self.assertEqual(event.get_sequence(), 2) self.assertTrue(event.is_recurring()) self.assertIsInstance(event.get_duration(), datetime.timedelta)
View file
pykolab-0.8.15.tar.gz/tests/unit/test-009-parse_ldap_uri.py -> pykolab-0.8.16.tar.gz/tests/unit/test-009-parse_ldap_uri.py
Changed
@@ -8,9 +8,9 @@ def test_001_ldap_uri(self): ldap_uri = "ldap://localhost" result = utils.parse_ldap_uri(ldap_uri) - self.assertEqual(result, ("ldap", "localhost", "389", None, None, None, None)) + self.assertEqual(result, ("ldap", "localhost", "389", None, None, None, None)) def test_002_ldap_uri_port(self): ldap_uri = "ldap://localhost:389" result = utils.parse_ldap_uri(ldap_uri) - self.assertEqual(result, ("ldap", "localhost", "389", None, None, None, None)) + self.assertEqual(result, ("ldap", "localhost", "389", None, None, None, None))
View file
pykolab-0.8.15.tar.gz/wallace/__init__.py -> pykolab-0.8.16.tar.gz/wallace/__init__.py
Changed
@@ -36,13 +36,15 @@ import pykolab from pykolab import utils -from pykolab.translate import _ +from pykolab.logger import StderrToLogger +from pykolab.translate import _ as _l +import modules from modules import cb_action_ACCEPT # pylint: disable=invalid-name log = pykolab.getLogger('pykolab.wallace') -sys.stderr = pykolab.logger.StderrToLogger(log) +sys.stderr = StderrToLogger(log) conf = pykolab.getConf() @@ -54,7 +56,7 @@ # Cause the previous modules to be skipped wallace_modules = wallace_modules(wallace_modules.index(kwargs'module') + 1): - log.debug(_("Wallace modules: %r") % (wallace_modules), level=8) + log.debug(_l("Wallace modules: %r") % (wallace_modules), level=8) # Execute the module if 'stage' in kwargs: @@ -129,31 +131,39 @@ while True: while not self.finished.is_set(): self.finished.wait(self.interval) - log.debug(_("Timer looping function '%s' every %ss") % ( + log.debug(_l("Timer looping function '%s' every %ss") % ( self.function.__name__, self.interval ), level=8) self.function(*self.args, **self.kwargs) self.finished.set() - log.debug(_("Timer loop %s") % ('still active','finished')self.finished.is_set(), level=8) + log.debug( + _l("Timer loop %s") % ('still active', 'finished')self.finished.is_set(), + level=8 + ) + break + class WallaceDaemon: + heartbeat = None + timer = None + def __init__(self): self.current_connections = 0 self.max_connections = 24 self.parent_pid = None self.pool = None - daemon_group = conf.add_cli_parser_option_group(_("Daemon Options")) + daemon_group = conf.add_cli_parser_option_group(_l("Daemon Options")) daemon_group.add_option( "--fork", dest="fork_mode", action="store_true", default=False, - help=_("Fork to the background.") + help=_l("Fork to the background.") ) daemon_group.add_option( @@ -161,7 +171,7 @@ dest="wallace_bind_address", action="store", default="localhost", - help=_("Bind address for Wallace.") + help=_l("Bind address for Wallace.") ) daemon_group.add_option( @@ -169,7 +179,7 @@ dest="process_groupname", action="store", default="kolab", - help=_("Run as group GROUPNAME"), + help=_l("Run as group GROUPNAME"), metavar="GROUPNAME" ) @@ -179,16 +189,16 @@ action="store", default=4, type=int, - help=_("Number of threads to use.") + help=_l("Number of threads to use.") ) daemon_group.add_option( "--max-tasks", - dest = "max_tasks", - action = "store", - default = None, - type = int, - help = _("Number of tasks per process.") + dest="max_tasks", + action="store", + default=None, + type=int, + help=_l("Number of tasks per process.") ) daemon_group.add_option( @@ -196,7 +206,7 @@ dest="pidfile", action="store", default="/var/run/wallaced/wallaced.pid", - help=_("Path to the PID file to use.") + help=_l("Path to the PID file to use.") ) daemon_group.add_option( @@ -205,7 +215,7 @@ action="store", default=10026, type=int, - help=_("Port that Wallace is supposed to use.") + help=_l("Port that Wallace is supposed to use.") ) daemon_group.add_option( @@ -213,7 +223,7 @@ dest="process_username", action="store", default="kolab", - help=_("Run as user USERNAME"), + help=_l("Run as user USERNAME"), metavar="USERNAME" ) @@ -230,13 +240,14 @@ mp_logger.setLevel(multiprocessing.SUBDEBUG) mp_logger.debug('Python multi-processing logger started') - import modules - modules.__init__() + modules.initialize() self.modules = conf.get_list('wallace', 'modules') if not self.modules: self.modules = + # pylint: disable=too-many-branches + # pylint: disable=too-many-statements def do_wallace(self): self.parent_pid = os.getpid() @@ -264,7 +275,7 @@ # pylint: disable=broad-except except Exception: log.warning( - _("Could not bind to socket on port %d on bind address %s") % ( + _l("Could not bind to socket on port %d on bind address %s") % ( conf.wallace_port, conf.wallace_bind_address ) @@ -277,7 +288,7 @@ # pylint: disable=broad-except except Exception: - log.warning(_("Could not shut down socket")) + log.warning(_l("Could not shut down socket")) time.sleep(1) s.close() @@ -287,7 +298,10 @@ s.listen(5) self.timer = Timer(180, self.pickup_spool_messages, args=, kwargs={'sync': True}) + + # pylint: disable=attribute-defined-outside-init self.timer.daemon = True + self.timer.start() # start background process to run periodic jobs in active modules @@ -301,6 +315,7 @@ self.heartbeat.finished = multiprocessing.Event() self.heartbeat.daemon = True self.heartbeat.start() + except Exception as errmsg: log.error("Failed to start heartbeat daemon: %s" % (errmsg)) finally: @@ -312,11 +327,23 @@ try: while 1: while self.current_connections >= self.max_connections: - log.debug(_("Reached limit of max connections of: %s. Sleeping for 0.5s") % self.max_connections, level=6) + log.debug( + _l("Reached limit of max connections of: %s. Sleeping for 0.5s") % (
View file
pykolab-0.8.15.tar.gz/wallace/module_resources.py -> pykolab-0.8.16.tar.gz/wallace/module_resources.py
Changed
@@ -30,6 +30,7 @@ import random import re import signal +from six import string_types import time import uuid @@ -121,7 +122,7 @@ # pylint: disable=too-many-locals # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements -def execute(*args, **kw): # noqa: C901 +def execute(*args, **kw): global auth, imap, extra_log_params # TODO: Test for correct call. @@ -329,14 +330,17 @@ ) # pylint: disable=broad-except - except Exception as e: - log.error(_("Could not find envelope sender attendee: %r") % (e)) + except Exception as errmsg: + log.error(_("Could not find envelope sender attendee: %r") % (errmsg)) continue # compare sequence number to avoid outdated replies if not itip_event'sequence' == event.get_sequence(): log.info( - _("The iTip reply sequence (%r) doesn't match the referred event version (%r). Ignoring.") % ( + _( + "The iTip reply sequence (%r) doesn't match the " + + "referred event version (%r). Ignoring." + ) % ( itip_event'sequence', event.get_sequence() ) @@ -358,9 +362,14 @@ elif owner_reply == kolabformat.PartDeclined: decline_reservation_request(_itip_event, receiving_resource) else: - log.info(_("Invalid response (%r) received from resource owner for event %r") % ( - sender_attendee.get_participant_status(True), reference_uid - )) + log.info( + _( + "Invalid response (%r) received from resource owner for event %r" + ) % ( + sender_attendee.get_participant_status(True), + reference_uid + ) + ) else: log.info( _("Event referenced by this REPLY (%r) not found in resource calendar") % ( @@ -387,8 +396,8 @@ ) # pylint: disable=broad-except - except Exception as e: - log.error(_("Could not find envelope attendee: %r") % (e)) + except Exception as errmsg: + log.error(_("Could not find envelope attendee: %r") % (errmsg)) continue # ignore updates and cancellations to resource collections who already delegated the event @@ -484,7 +493,7 @@ # This must have been a resource collection originally. # We have inserted the reference to the original resource # record in 'memberof'. - if available_resource.has_key('memberof'): + if 'memberof' in available_resource: original_resource = resourcesavailable_resource'memberof' atts = a.get_email() for a in itip_event'xml'.get_attendees() @@ -591,14 +600,19 @@ for resource_dn in resource_dns: resource_attrs = auth.get_entry_attributes(None, resource_dn, 'kolabtargetfolder') - if resource_attrs.has_key('kolabtargetfolder'): + + if 'kolabtargetfolder' in resource_attrs: try: expunge_resource_calendar(resource_attrs'kolabtargetfolder') # pylint: disable=broad-except - except Exception as e: - log.error(_("Expunge resource calendar for %s (%s) failed: %r") % ( - resource_dn, resource_attrs'kolabtargetfolder', e - )) + except Exception as errmsg: + log.error( + _("Expunge resource calendar for %s (%s) failed: %r") % ( + resource_dn, + resource_attrs'kolabtargetfolder', + errmsg + ) + ) imap.disconnect() @@ -606,6 +620,7 @@ heartbeat._lastrun = now + heartbeat._lastrun = 0 @@ -626,7 +641,13 @@ # might raise an exception, let that bubble targetfolder = imap.folder_quote(mailbox) - imap.set_acl(targetfolder, conf.get(conf.get('kolab', 'imap_backend'), 'admin_login'), "lrswipkxtecda") + + imap.set_acl( + targetfolder, + conf.get(conf.get('kolab', 'imap_backend'), 'admin_login'), + "lrswipkxtecda" + ) + imap.imap.m.select(targetfolder) typ, data = imap.imap.m.search(None, 'UNDELETED') @@ -642,8 +663,8 @@ try: event = event_from_message(message_from_string(data01)) # pylint: disable=broad-except - except Exception as e: - log.error(_("Failed to parse event from message %s/%s: %r") % (mailbox, num, e)) + except Exception as errmsg: + log.error(_("Failed to parse event from message %s/%s: %r") % (mailbox, num, errmsg)) continue if event: @@ -658,7 +679,17 @@ if dt_end and dt_end < expire_date: age = now - dt_end - log.debug(_("Flag event %s from message %s/%s as deleted (age = %d days)") % (event.uid, mailbox, num, age.days), level=8) + + log.debug( + _("Flag event %s from message %s/%s as deleted (age = %d days)") % ( + event.uid, + mailbox, + num, + age.days + ), + level=8 + ) + imap.imap.m.store(num, '+FLAGS', '\\Deleted') imap.imap.m.expunge() @@ -676,7 +707,7 @@ for resource in resources.keys(): # skip this for resource collections - if not resourcesresource.has_key('kolabtargetfolder'): + if 'kolabtargetfolder' not in resourcesresource: continue # sets the 'conflicting' flag and adds a list of conflicting events found @@ -688,28 +719,42 @@ end = time.time() - log.debug(_("start: %r, end: %r, total: %r, messages: %d") % (start, end, (end-start), num_messages), level=8) - + log.debug( + _("start: %r, end: %r, total: %r, messages: %d") % ( + start, + end, + (end - start), + num_messages + ), + level=8 + ) # For each resource (collections are first!) # check conflicts and either accept or decline the reservation request for resource in resource_dns: log.debug(_("Polling for resource %r") % (resource), level=8) - if not resources.has_key(resource): + if resource not in resources: log.debug(_("Resource %r has been popped from the list") % (resource), level=8) continue - if not resourcesresource.has_key('conflicting_events'): + if 'conflicting_events' not in resourcesresource: log.debug(_("Resource is a collection"), level=8) # check if there are non-conflicting collection members - conflicting_members = x for x in resourcesresource'uniquemember' if resourcesx'conflict' + conflicting_members = + x for x in resourcesresource'uniquemember' + if resourcesx'conflict' +
View file
pykolab-0.8.15.tar.gz/wallace/modules.py -> pykolab-0.8.16.tar.gz/wallace/modules.py
Changed
@@ -51,7 +51,7 @@ modules = {} -def __init__(): +def initialize(): # We only want the base path modules_base_path = os.path.dirname(__file__)
View file
pykolab.dsc
Changed
@@ -2,7 +2,7 @@ Source: pykolab Binary: pykolab, kolab-cli, kolab-conf, kolab-saslauthd, kolab-server, kolab-telemetry, kolab-xml, wallace Architecture: all -Version: 0.8.15-0~kolab1 +Version: 0.8.15-0~kolab2 Maintainer: Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen@kolabsys.com> Uploaders: Paul Klos <kolab@klos2day.nl> Homepage: http://www.kolab.org
Locations
Projects
Search
Status Monitor
Help
Open Build Service
OBS Manuals
API Documentation
OBS Portal
Reporting a Bug
Contact
Mailing List
Forums
Chat (IRC)
Twitter
Open Build Service (OBS)
is an
openSUSE project
.