* 'vmm.cfg.5'
* 'vmm.1'
- Reworded some parts.
* 'vmm'
- Added function _getOrder() for a (hopefully) better structured output from
the domaininfo, userinfo and getuser subcommands.
#!/usr/bin/env python# -*- coding: UTF-8 -*-# Copyright 2007-2008 VEB IT# See COPYING for distribution information.# $Id$"""Virtual Mail Manager's Domain class to manage e-mail domains."""fromconstants.VERSIONimportVERSION__author__='Pascal Volk <p.volk@veb-it.de>'__version__=VERSION__revision__='rev '+'$Rev$'.split()[1]__date__='$Date$'.split()[1]fromrandomimportchoicefromExceptionsimportVMMDomainExceptionimportconstants.ERRORasERRfromTransportimportTransportMAILDIR_CHARS='0123456789abcdefghijklmnopqrstuvwxyz'classDomain:"""Class to manage e-mail domains."""def__init__(self,dbh,domainname,basedir=None,transport=None):"""Creates a new Domain instance. Keyword arguments: dbh -- a pyPgSQL.PgSQL.connection domainname -- name of the domain (str) transport -- default vmm.cfg/misc/transport (str) """self._dbh=dbhself._name=domainnameself._basedir=basediriftransportisnotNone:self._transport=Transport(self._dbh,transport=transport)else:self._transport=transportself._id=0self._domaindir=Noneself._exists()def_exists(self):"""Checks if the domain already exists. If the domain exists _id will be set and returns True, otherwise False will be returned. """dbc=self._dbh.cursor()dbc.execute("SELECT gid,tid,domaindir FROM domains WHERE domainname=%s",self._name)result=dbc.fetchone()dbc.close()ifresultisnotNone:self._id,self._domaindir=result[0],result[2]self._transport=Transport(self._dbh,tid=result[1])returnTrueelse:returnFalsedef_setID(self):"""Sets the ID of the domain."""dbc=self._dbh.cursor()dbc.execute("SELECT nextval('domains_gid')")self._id=dbc.fetchone()[0]dbc.close()def_prepare(self):self._setID()self._domaindir="%s/%s/%i"%(self._basedir,choice(MAILDIR_CHARS),self._id)def_has(self,what):"""Checks if aliases or accounts are assigned to the domain. If there are assigned accounts or aliases True will be returned, otherwise False will be returned. Keyword arguments: what -- 'alias' or 'users' (strings) """ifwhatnotin['alias','users']:returnFalsedbc=self._dbh.cursor()ifwhat=='users':dbc.execute("SELECT count(gid) FROM users WHERE gid=%s",self._id)else:dbc.execute("SELECT count(gid) FROM alias WHERE gid=%s",self._id)count=dbc.fetchone()dbc.close()ifcount[0]>0:returnTrueelse:returnFalsedef_chkDelete(self,delUser,delAlias):"""Checks dependencies for deletion. Keyword arguments: delUser -- ignore available accounts (bool) delAlias -- ignore available aliases (bool) """ifnotdelUser:hasUser=self._has('users')else:hasUser=FalseifnotdelAlias:hasAlias=self._has('alias')else:hasAlias=FalseifhasUserandhasAlias:raiseVMMDomainException(('There are accounts and aliases.',ERR.ACCOUNT_AND_ALIAS_PRESENT))elifhasUser:raiseVMMDomainException(('There are accounts.',ERR.ACCOUNT_PRESENT))elifhasAlias:raiseVMMDomainException(('There are aliases.',ERR.ALIAS_PRESENT))defsave(self):"""Stores the new domain in the database."""ifself._id<1:self._prepare()dbc=self._dbh.cursor()dbc.execute("INSERT INTO domains (gid, domainname, tid, domaindir)\ VALUES (%s, %s, %s, %s)",self._id,self._name,self._transport.getID(),self._domaindir)self._dbh.commit()dbc.close()else:raiseVMMDomainException(('Domain already exists.',ERR.DOMAIN_EXISTS))defdelete(self,delUser=False,delAlias=False):"""Deletes the domain. Keyword arguments: delUser -- force deletion of available accounts (bool) delAlias -- force deletion of available aliases (bool) """ifself._id>0:self._chkDelete(delUser,delAlias)dbc=self._dbh.cursor()dbc.execute('DELETE FROM alias WHERE gid=%s',self._id)dbc.execute('DELETE FROM users WHERE gid=%s',self._id)dbc.execute('DELETE FROM relocated WHERE gid=%s',self._id)dbc.execute('DELETE FROM domains WHERE gid=%s',self._id)self._dbh.commit()dbc.close()else:raiseVMMDomainException(("Domain doesn't exist yet.",ERR.NO_SUCH_DOMAIN))defupdateTransport(self,transport,force=False):"""Sets a new transport for the domain. Keyword arguments: transport -- the new transport (str) force -- True/False force new transport for all accounts (bool) """ifself._id>0:trsp=Transport(self._dbh,transport=transport)dbc=self._dbh.cursor()dbc.execute("UPDATE domains SET tid=%s WHERE gid=%s",trsp.getID(),self._id)ifdbc.rowcount>0:self._dbh.commit()ifforce:dbc.execute("UPDATE users SET tid=%s WHERE gid=%s",trsp.getID(),self._id)ifdbc.rowcount>0:self._dbh.commit()dbc.close()else:raiseVMMDomainException(("Domain doesn't exist yet.",ERR.NO_SUCH_DOMAIN))defgetID(self):"""Returns the ID of the domain."""returnself._iddefgetDir(self):"""Returns the directory of the domain."""returnself._domaindirdefgetTransport(self):"""Returns domain's transport."""returnself._transport.getTransport()defgetTransportID(self):"""Returns the ID from the domain's transport."""returnself._transport.getID()defgetInfo(self):"""Returns a dictionary with information about the domain."""sql="""\SELECT gid, domainname, transport, domaindir, accounts, aliases FROM vmm_domain_info WHERE gid = %i"""%self._iddbc=self._dbh.cursor()dbc.execute(sql)info=dbc.fetchone()dbc.close()ifinfoisNone:raiseVMMDomainException(("Domain doesn't exist yet.",ERR.NO_SUCH_DOMAIN))else:keys=['gid','domainname','transport','domaindir','accounts','aliases']returndict(zip(keys,info))defgetAccounts(self):"""Returns a list with all accounts from the domain."""dbc=self._dbh.cursor()dbc.execute("SELECT userid AS users FROM dovecot_user WHERE gid = %s\ ORDER BY users",self._id)users=dbc.fetchall()dbc.close()accounts=[]iflen(users)>0:foraccountinusers:accounts.append(account[0])returnaccountsdefgetAliases(self):"""Returns a list with all aliases from the domain."""dbc=self._dbh.cursor()dbc.execute("SELECT DISTINCT address FROM postfix_alias WHERE gid=%s\ ORDER BY address",self._id)addresses=dbc.fetchall()dbc.close()aliases=[]iflen(addresses)>0:foraliasinaddresses:aliases.append(alias[0])returnaliases