root / pykota / trunk / pykota / config.py @ 1029

Revision 1029, 13.4 kB (checked in by jalet, 21 years ago)

More work on LDAP storage backend.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[695]1# PyKota
2#
[952]3# PyKota : Print Quotas for CUPS and LPRng
[695]4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
[873]6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
[695]10#
[873]11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
[695]19#
20# $Id$
21#
22# $Log$
[1029]23# Revision 1.29  2003/06/14 22:44:21  jalet
24# More work on LDAP storage backend.
25#
[1021]26# Revision 1.28  2003/06/10 16:37:54  jalet
27# Deletion of the second user which is not needed anymore.
28# Added a debug configuration field in /etc/pykota.conf
29# All queries can now be sent to the logger in debug mode, this will
30# greatly help improve performance when time for this will come.
31#
[1000]32# Revision 1.27  2003/05/27 23:00:21  jalet
33# Big rewrite of external accounting methods.
34# Should work well now.
35#
[980]36# Revision 1.26  2003/04/30 19:53:58  jalet
37# 1.05
38#
[976]39# Revision 1.25  2003/04/30 13:36:40  jalet
40# Stupid accounting method was added.
41#
[973]42# Revision 1.24  2003/04/29 18:37:54  jalet
43# Pluggable accounting methods (actually doesn't support external scripts)
44#
[956]45# Revision 1.23  2003/04/24 11:53:48  jalet
46# Default policy for unknown users/groups is to DENY printing instead
47# of the previous default to ALLOW printing. This is to solve an accuracy
48# problem. If you set the policy to ALLOW, jobs printed by in nexistant user
49# (from PyKota's POV) will be charged to the next user who prints on the
50# same printer.
51#
[952]52# Revision 1.22  2003/04/23 22:13:57  jalet
53# Preliminary support for LPRng added BUT STILL UNTESTED.
54#
[873]55# Revision 1.21  2003/03/29 13:45:27  jalet
56# GPL paragraphs were incorrectly (from memory) copied into the sources.
57# Two README files were added.
58# Upgrade script for PostgreSQL pre 1.01 schema was added.
59#
[872]60# Revision 1.20  2003/03/29 13:08:28  jalet
61# Configuration is now expected to be found in /etc/pykota.conf instead of
62# in /etc/cups/pykota.conf
63# Installation script can move old config files to the new location if needed.
64# Better error handling if configuration file is absent.
65#
[854]66# Revision 1.19  2003/03/16 09:56:52  jalet
67# Mailto option now accepts some additional values which all mean that
68# nobody will receive any email message.
69# Mailto option now works. Version 1.01 is now officially out.
70#
[853]71# Revision 1.18  2003/03/16 08:00:50  jalet
72# Default hard coded options are now used if they are not set in the
73# configuration file.
74#
[852]75# Revision 1.17  2003/03/15 23:01:28  jalet
76# New mailto option in configuration file added.
77# No time to test this tonight (although it should work).
78#
[804]79# Revision 1.16  2003/02/17 23:01:56  jalet
80# Typos
81#
[802]82# Revision 1.15  2003/02/17 22:55:01  jalet
83# More options can now be set per printer or globally :
84#
[804]85#       admin
86#       adminmail
87#       gracedelay
88#       requester
[802]89#
90# the printer option has priority when both are defined.
91#
[800]92# Revision 1.14  2003/02/17 22:05:50  jalet
93# Storage backend now supports admin and user passwords (untested)
94#
[789]95# Revision 1.13  2003/02/10 11:47:39  jalet
96# Moved some code down into the requesters
97#
[786]98# Revision 1.12  2003/02/10 10:36:33  jalet
99# Small problem wrt external requester
100#
[785]101# Revision 1.11  2003/02/10 08:50:45  jalet
102# External requester seems to be finally ok now
103#
[783]104# Revision 1.10  2003/02/10 08:19:57  jalet
105# tell ConfigParser to return raw data, this allows our own strings
106# interpolations in the requester
107#
[781]108# Revision 1.9  2003/02/10 00:44:38  jalet
109# Typos
110#
[780]111# Revision 1.8  2003/02/10 00:42:17  jalet
112# External requester should be ok (untested)
113# New syntax for configuration file wrt requesters
114#
[773]115# Revision 1.7  2003/02/09 13:05:43  jalet
116# Internationalization continues...
117#
[747]118# Revision 1.6  2003/02/07 22:00:09  jalet
119# Bad cut&paste
120#
[731]121# Revision 1.5  2003/02/06 23:58:05  jalet
122# repykota should be ok
123#
[713]124# Revision 1.4  2003/02/06 09:19:02  jalet
125# More robust behavior (hopefully) when the user or printer is not managed
126# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
127# printer and/or user not 'yet?' in storage.
128#
[708]129# Revision 1.3  2003/02/05 23:26:22  jalet
130# Incorrect handling of grace delay
131#
[707]132# Revision 1.2  2003/02/05 23:09:20  jalet
133# Name conflict
134#
[695]135# Revision 1.1  2003/02/05 21:28:17  jalet
136# Initial import into CVS
137#
138#
139#
140
141import sys
142import os
143import ConfigParser
144
145class PyKotaConfigError(Exception):
146    """An exception for PyKota config related stuff."""
147    def __init__(self, message = ""):
148        self.message = message
149        Exception.__init__(self, message)
150    def __repr__(self):
151        return self.message
152    __str__ = __repr__
153   
154class PyKotaConfig :
155    """A class to deal with PyKota's configuration."""
156    def __init__(self, directory) :
157        """Reads and checks the configuration file."""
158        self.filename = os.path.join(directory, "pykota.conf")
[872]159        if not os.path.isfile(self.filename) :
160            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
[695]161        self.config = ConfigParser.ConfigParser()
162        self.config.read([self.filename])
163                       
164    def getPrinterNames(self) :   
165        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
166        return [pname for pname in self.config.sections() if pname != "global"]
167       
[802]168    def getGlobalOption(self, option, ignore=0) :   
169        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
170        try :
171            return self.config.get("global", option, raw=1)
172        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
173            if ignore :
174                return
175            else :
176                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
177               
178    def getPrinterOption(self, printer, option) :   
179        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
180        globaloption = self.getGlobalOption(option, ignore=1)
181        try :
182            return self.config.get(printer, option, raw=1)
183        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
184            if globaloption is not None :
185                return globaloption
186            else :
187                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printer, self.filename)
188       
[695]189    def getStorageBackend(self) :   
[800]190        """Returns the storage backend information as a Python mapping."""       
191        backendinfo = {}
[695]192        for option in [ "storagebackend", "storageserver", \
193                        "storagename", "storageadmin", \
194                      ] :
[804]195            backendinfo[option] = self.getGlobalOption(option)
[1021]196        backendinfo["storageadminpw"] = self.getGlobalOption("storageadminpw", ignore=1)
[800]197        return backendinfo
[695]198       
[1029]199    def getLDAPInfo(self) :   
200        """Returns some hints for the LDAP backend."""       
201        ldapinfo = {}
202        for option in [ "userbase", "userrdn", \
203                        "groupbase", "grouprdn", "groupmembers", \
204                        "printerbase", "printerrdn", \
205                        "userquotabase", "groupquotabase", \
206                        "jobbase", "lastjobbase", \
207                      ] :
208            ldapinfo[option] = self.getGlobalOption(option)
209        return ldapinfo
210       
[695]211    def getLoggingBackend(self) :   
212        """Returns the logging backend information."""
[802]213        validloggers = [ "stderr", "system" ] 
[853]214        try :
215            logger = self.getGlobalOption("logger").lower()
216        except PyKotaConfigError :   
217            logger = "system"
[802]218        if logger not in validloggers :             
219            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
220        return logger   
[695]221       
[973]222    def getAccounterBackend(self, printer) :   
223        """Returns the accounter backend to use for a given printer.
224       
225           if it is not set, it defaults to 'querying' which means ask printer
226           for its internal lifetime page counter.
227        """   
[980]228        validaccounters = [ "querying", "stupid", "external" ]     
[973]229        try :
[1000]230            fullaccounter = self.getPrinterOption(printer, "accounter").strip()
[973]231        except PyKotaConfigError :   
[980]232            fullaccounter = "querying"
[1000]233        if fullaccounter.lower().startswith("external") :   
[980]234            try :
235                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
236            except ValueError :   
237                raise PyKotaConfigError, _("Invalid external accounter %s for printer %s") % (fullaccounter, printer)
238            if args.endswith(')') :
239                args = args[:-1]
240            if not args :
241                raise PyKotaConfigError, _("Invalid external accounter %s for printer %s") % (fullaccounter, printer)
[1000]242            return (accounter.lower(), args)   
243        elif fullaccounter.lower() not in validaccounters :
[973]244            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printer, str(validaccounters))
[980]245        else :   
[1000]246            return (fullaccounter.lower(), None)
[973]247       
[695]248    def getRequesterBackend(self, printer) :   
[780]249        """Returns the requester backend to use for a given printer, with its arguments."""
[802]250        try :
[973]251            fullrequester = self.getPrinterOption(printer, "requester")
252        except PyKotaConfigError :   
253            # No requester defined, maybe it is not needed if accounting method
254            # is not set to 'querying', but if we are called, then the accounting
255            # method really IS 'querying', and so there's a big problem.
256            raise PyKotaConfigError, _("Option requester for printer %s was not set") % printer
257        else :   
258            try :
259                (requester, args) = [x.strip() for x in fullrequester.split('(', 1)]
260            except ValueError :   
261                raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer)
262            if args.endswith(')') :
263                args = args[:-1]
264            if not args :
265                raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer)
266            validrequesters = [ "snmp", "external" ] # TODO : add more requesters
[1000]267            requester = requester.lower()
[973]268            if requester not in validrequesters :
269                raise PyKotaConfigError, _("Option requester for printer %s only supports values in %s") % (printer, str(validrequesters))
270            return (requester, args)
[695]271       
272    def getPrinterPolicy(self, printer) :   
273        """Returns the default policy for the current printer."""
[802]274        validpolicies = [ "ALLOW", "DENY" ]     
[853]275        try :
276            policy = self.getPrinterOption(printer, "policy").upper()
277        except PyKotaConfigError :   
[956]278            policy = "DENY"
[802]279        if policy not in validpolicies :
280            raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printer, str(validpolicies))
281        return policy
[695]282       
283    def getSMTPServer(self) :   
284        """Returns the SMTP server to use to send messages to users."""
[853]285        try :
286            return self.getGlobalOption("smtpserver")
287        except PyKotaConfigError :   
288            return "localhost"
[695]289       
[802]290    def getAdminMail(self, printer) :   
[695]291        """Returns the Email address of the Print Quota Administrator."""
[853]292        try :
293            return self.getPrinterOption(printer, "adminmail")
294        except PyKotaConfigError :   
295            return "root@localhost"
[695]296       
[802]297    def getAdmin(self, printer) :   
[695]298        """Returns the full name of the Print Quota Administrator."""
[853]299        try :
300            return self.getPrinterOption(printer, "admin")
301        except PyKotaConfigError :   
302            return "root"
[708]303       
[852]304    def getMailTo(self, printer) :   
305        """Returns the recipient of email messages."""
[854]306        validmailtos = [ "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
[853]307        try :
308            mailto = self.getPrinterOption(printer, "mailto").upper()
309        except PyKotaConfigError :   
310            mailto = "BOTH"
[852]311        if mailto not in validmailtos :
312            raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printer, str(validmailtos))
313        return mailto   
314       
[804]315    def getGraceDelay(self, printer) :   
[708]316        """Returns the grace delay in days."""
[731]317        try :
[853]318            gd = self.getPrinterOption(printer, "gracedelay")
319        except PyKotaConfigError :   
320            gd = 7
321        try :
[731]322            return int(gd)
323        except ValueError :   
[773]324            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
[1021]325           
326    def getDebug(self) :         
327        """Returns 1 if debugging is activated, else 0."""
328        debug = self.getGlobalOption("debug", ignore=1)
329        if (debug is not None) and (debug.upper().strip() in ['Y', 'YES', '1', 'ON', 'O']) :
330            return 1
331        else :   
332            return 0
Note: See TracBrowser for help on using the browser.