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

Revision 1068, 13.6 kB (checked in by jalet, 21 years ago)

Lots of small fixes with the help of PyChecker?

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