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

Revision 1111, 16.6 kB (checked in by jalet, 21 years ago)

Added configurable LDAP mail attribute support

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