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

Revision 1077, 15.1 kB (checked in by jalet, 21 years ago)

Configurable warning messages.
Poor man's treshold value added.

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