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

Revision 1475, 20.9 kB (checked in by jalet, 20 years ago)

Code simplifications

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.46  2004/05/13 13:59:28  jalet
25# Code simplifications
26#
27# Revision 1.45  2004/03/01 10:22:30  jalet
28# Can now extract per printer pre and post hooks from the configuration file
29#
30# Revision 1.44  2004/02/20 14:42:21  jalet
31# Experimental ldapcache directive added
32#
33# Revision 1.43  2004/02/19 14:20:21  jalet
34# maildomain pykota.conf directive added.
35# Small improvements on mail headers quality.
36#
37# Revision 1.42  2004/01/08 14:10:32  jalet
38# Copyright year changed.
39#
40# Revision 1.41  2003/11/29 20:06:20  jalet
41# Added 'utolower' configuration option to convert all usernames to
42# lowercase when printing. All database accesses are still and will
43# remain case sensitive though.
44#
45# Revision 1.40  2003/11/18 23:43:12  jalet
46# Mailto can be any external command now, as usual.
47#
48# Revision 1.39  2003/10/08 21:41:38  jalet
49# External policies for printers works !
50# We can now auto-add users on first print, and do other useful things if needed.
51#
52# Revision 1.38  2003/10/07 22:06:05  jalet
53# Preliminary code to disable job history
54#
55# Revision 1.37  2003/10/07 09:07:28  jalet
56# Character encoding added to please latest version of Python
57#
58# Revision 1.36  2003/10/02 20:23:18  jalet
59# Storage caching mechanism added.
60#
61# Revision 1.35  2003/07/29 09:54:03  jalet
62# Added configurable LDAP mail attribute support
63#
64# Revision 1.34  2003/07/28 09:11:12  jalet
65# PyKota now tries to add its attributes intelligently in existing LDAP
66# directories.
67#
68# Revision 1.33  2003/07/16 21:53:07  jalet
69# Really big modifications wrt new configuration file's location and content.
70#
71# Revision 1.32  2003/07/08 19:43:51  jalet
72# Configurable warning messages.
73# Poor man's treshold value added.
74#
75# Revision 1.31  2003/07/07 11:49:24  jalet
76# Lots of small fixes with the help of PyChecker
77#
78# Revision 1.30  2003/06/25 14:10:01  jalet
79# Hey, it may work (edpykota --reset excepted) !
80#
81# Revision 1.29  2003/06/14 22:44:21  jalet
82# More work on LDAP storage backend.
83#
84# Revision 1.28  2003/06/10 16:37:54  jalet
85# Deletion of the second user which is not needed anymore.
86# Added a debug configuration field in /etc/pykota.conf
87# All queries can now be sent to the logger in debug mode, this will
88# greatly help improve performance when time for this will come.
89#
90# Revision 1.27  2003/05/27 23:00:21  jalet
91# Big rewrite of external accounting methods.
92# Should work well now.
93#
94# Revision 1.26  2003/04/30 19:53:58  jalet
95# 1.05
96#
97# Revision 1.25  2003/04/30 13:36:40  jalet
98# Stupid accounting method was added.
99#
100# Revision 1.24  2003/04/29 18:37:54  jalet
101# Pluggable accounting methods (actually doesn't support external scripts)
102#
103# Revision 1.23  2003/04/24 11:53:48  jalet
104# Default policy for unknown users/groups is to DENY printing instead
105# of the previous default to ALLOW printing. This is to solve an accuracy
106# problem. If you set the policy to ALLOW, jobs printed by in nexistant user
107# (from PyKota's POV) will be charged to the next user who prints on the
108# same printer.
109#
110# Revision 1.22  2003/04/23 22:13:57  jalet
111# Preliminary support for LPRng added BUT STILL UNTESTED.
112#
113# Revision 1.21  2003/03/29 13:45:27  jalet
114# GPL paragraphs were incorrectly (from memory) copied into the sources.
115# Two README files were added.
116# Upgrade script for PostgreSQL pre 1.01 schema was added.
117#
118# Revision 1.20  2003/03/29 13:08:28  jalet
119# Configuration is now expected to be found in /etc/pykota.conf instead of
120# in /etc/cups/pykota.conf
121# Installation script can move old config files to the new location if needed.
122# Better error handling if configuration file is absent.
123#
124# Revision 1.19  2003/03/16 09:56:52  jalet
125# Mailto option now accepts some additional values which all mean that
126# nobody will receive any email message.
127# Mailto option now works. Version 1.01 is now officially out.
128#
129# Revision 1.18  2003/03/16 08:00:50  jalet
130# Default hard coded options are now used if they are not set in the
131# configuration file.
132#
133# Revision 1.17  2003/03/15 23:01:28  jalet
134# New mailto option in configuration file added.
135# No time to test this tonight (although it should work).
136#
137# Revision 1.16  2003/02/17 23:01:56  jalet
138# Typos
139#
140# Revision 1.15  2003/02/17 22:55:01  jalet
141# More options can now be set per printer or globally :
142#
143#       admin
144#       adminmail
145#       gracedelay
146#       requester
147#
148# the printer option has priority when both are defined.
149#
150# Revision 1.14  2003/02/17 22:05:50  jalet
151# Storage backend now supports admin and user passwords (untested)
152#
153# Revision 1.13  2003/02/10 11:47:39  jalet
154# Moved some code down into the requesters
155#
156# Revision 1.12  2003/02/10 10:36:33  jalet
157# Small problem wrt external requester
158#
159# Revision 1.11  2003/02/10 08:50:45  jalet
160# External requester seems to be finally ok now
161#
162# Revision 1.10  2003/02/10 08:19:57  jalet
163# tell ConfigParser to return raw data, this allows our own strings
164# interpolations in the requester
165#
166# Revision 1.9  2003/02/10 00:44:38  jalet
167# Typos
168#
169# Revision 1.8  2003/02/10 00:42:17  jalet
170# External requester should be ok (untested)
171# New syntax for configuration file wrt requesters
172#
173# Revision 1.7  2003/02/09 13:05:43  jalet
174# Internationalization continues...
175#
176# Revision 1.6  2003/02/07 22:00:09  jalet
177# Bad cut&paste
178#
179# Revision 1.5  2003/02/06 23:58:05  jalet
180# repykota should be ok
181#
182# Revision 1.4  2003/02/06 09:19:02  jalet
183# More robust behavior (hopefully) when the user or printer is not managed
184# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
185# printer and/or user not 'yet?' in storage.
186#
187# Revision 1.3  2003/02/05 23:26:22  jalet
188# Incorrect handling of grace delay
189#
190# Revision 1.2  2003/02/05 23:09:20  jalet
191# Name conflict
192#
193# Revision 1.1  2003/02/05 21:28:17  jalet
194# Initial import into CVS
195#
196#
197#
198
199import os
200import ConfigParser
201
202class PyKotaConfigError(Exception):
203    """An exception for PyKota config related stuff."""
204    def __init__(self, message = ""):
205        self.message = message
206        Exception.__init__(self, message)
207    def __repr__(self):
208        return self.message
209    __str__ = __repr__
210   
211class PyKotaConfig :
212    """A class to deal with PyKota's configuration."""
213    def __init__(self, directory) :
214        """Reads and checks the configuration file."""
215        self.filename = os.path.join(directory, "pykota.conf")
216        if not os.path.isfile(self.filename) :
217            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
218        self.config = ConfigParser.ConfigParser()
219        self.config.read([self.filename])
220           
221    def isTrue(self, option) :       
222        """Returns 1 if option is set to true, else 0."""
223        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
224            return 1
225        else :   
226            return 0
227                       
228    def getPrinterNames(self) :   
229        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
230        return [pname for pname in self.config.sections() if pname != "global"]
231       
232    def getGlobalOption(self, option, ignore=0) :   
233        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
234        try :
235            return self.config.get("global", option, raw=1)
236        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
237            if ignore :
238                return
239            else :
240                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
241               
242    def getPrinterOption(self, printername, option) :   
243        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
244        globaloption = self.getGlobalOption(option, ignore=1)
245        try :
246            return self.config.get(printername, option, raw=1)
247        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
248            if globaloption is not None :
249                return globaloption
250            else :
251                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
252       
253    def getStorageBackend(self) :   
254        """Returns the storage backend information as a Python mapping."""       
255        backendinfo = {}
256        for option in [ "storagebackend", "storageserver", \
257                        "storagename", "storageuser", \
258                      ] :
259            backendinfo[option] = self.getGlobalOption(option)
260        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
261        backendinfo["storageadmin"] = None
262        backendinfo["storageadminpw"] = None
263        adminconf = ConfigParser.ConfigParser()
264        adminconf.read(["/etc/pykota/pykotadmin.conf"])
265        if adminconf.sections() : # were we able to read the file ?
266            try :
267                backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
268            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
269                raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", "/etc/pykota/pykotadmin.conf")
270            try :
271                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
272            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
273                pass # Password is optional
274        return backendinfo
275       
276    def getLDAPInfo(self) :   
277        """Returns some hints for the LDAP backend."""       
278        ldapinfo = {}
279        for option in [ "userbase", "userrdn", \
280                        "balancebase", "balancerdn", \
281                        "groupbase", "grouprdn", "groupmembers", \
282                        "printerbase", "printerrdn", \
283                        "userquotabase", "groupquotabase", \
284                        "jobbase", "lastjobbase", \
285                        "newuser", "newgroup", \
286                        "usermail", \
287                      ] :
288            ldapinfo[option] = self.getGlobalOption(option).strip()
289        for field in ["newuser", "newgroup"] :
290            if ldapinfo[field].lower().startswith('attach(') :
291                ldapinfo[field] = ldapinfo[field][7:-1]
292        return ldapinfo
293       
294    def getLoggingBackend(self) :   
295        """Returns the logging backend information."""
296        validloggers = [ "stderr", "system" ] 
297        try :
298            logger = self.getGlobalOption("logger").lower()
299        except PyKotaConfigError :   
300            logger = "system"
301        if logger not in validloggers :             
302            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
303        return logger   
304       
305    def getAccounterBackend(self, printername) :   
306        """Returns the accounter backend to use for a given printer.
307       
308           if it is not set, it defaults to 'hardware' which means ask printer
309           for its internal lifetime page counter.
310        """   
311        validaccounters = [ "hardware", "software" ]     
312        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
313        if fullaccounter.lower().startswith("software") :   
314            try :
315                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
316            except ValueError :   
317                raise PyKotaConfigError, _("Invalid external accounter %s for printer %s") % (fullaccounter, printername)
318            if args.endswith(')') :
319                args = args[:-1]
320            if not args :
321                raise PyKotaConfigError, _("Invalid external accounter %s for printer %s") % (fullaccounter, printername)
322            return (accounter.lower(), args)   
323        elif fullaccounter.lower() not in validaccounters :
324            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
325        else :   
326            return (fullaccounter.lower(), None)
327       
328    def getPreHook(self, printername) :   
329        """Returns the prehook command line to launch, or None if unset."""
330        try :
331            return self.getPrinterOption(printername, "prehook").strip()
332        except PyKotaConfigError :   
333            return      # No command to launch in the pre-hook
334           
335    def getPostHook(self, printername) :   
336        """Returns the posthook command line to launch, or None if unset."""
337        try :
338            return self.getPrinterOption(printername, "posthook").strip()
339        except PyKotaConfigError :   
340            return      # No command to launch in the post-hook
341           
342    def getRequesterBackend(self, printername) :   
343        """Returns the requester backend to use for a given printer, with its arguments."""
344        try :
345            fullrequester = self.getPrinterOption(printername, "requester")
346        except PyKotaConfigError :   
347            # No requester defined, maybe it is not needed if accounting method
348            # is not set to 'hardware', but if we are called, then the accounting
349            # method really IS 'hardware', and so there's a big problem.
350            raise PyKotaConfigError, _("Option requester for printer %s was not set") % printername
351        else :   
352            try :
353                (requester, args) = [x.strip() for x in fullrequester.split('(', 1)]
354            except ValueError :   
355                raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printername)
356            if args.endswith(')') :
357                args = args[:-1]
358            if not args :
359                raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printername)
360            validrequesters = [ "external" ] 
361            requester = requester.lower()
362            if requester not in validrequesters :
363                raise PyKotaConfigError, _("Option requester for printer %s only supports values in %s") % (printername, str(validrequesters))
364            return (requester, args)
365       
366    def getPrinterPolicy(self, printername) :   
367        """Returns the default policy for the current printer."""
368        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
369        try :
370            fullpolicy = self.getPrinterOption(printername, "policy")
371        except PyKotaConfigError :   
372            return ("DENY", None)
373        else :   
374            try :
375                policy = [x.strip() for x in fullpolicy.split('(', 1)]
376            except ValueError :   
377                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
378            if len(policy) == 1 :   
379                policy.append("")
380            (policy, args) = policy   
381            if args.endswith(')') :
382                args = args[:-1]
383            policy = policy.upper()   
384            if (policy == "EXTERNAL") and not args :
385                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
386            if policy not in validpolicies :
387                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
388            return (policy, args)
389       
390    def getSMTPServer(self) :   
391        """Returns the SMTP server to use to send messages to users."""
392        try :
393            return self.getGlobalOption("smtpserver")
394        except PyKotaConfigError :   
395            return "localhost"
396       
397    def getMailDomain(self) :   
398        """Returns the mail domain to use to send messages to users."""
399        try :
400            return self.getGlobalOption("maildomain")
401        except PyKotaConfigError :   
402            return 
403       
404    def getAdminMail(self, printername) :   
405        """Returns the Email address of the Print Quota Administrator."""
406        try :
407            return self.getPrinterOption(printername, "adminmail")
408        except PyKotaConfigError :   
409            return "root@localhost"
410       
411    def getAdmin(self, printername) :   
412        """Returns the full name of the Print Quota Administrator."""
413        try :
414            return self.getPrinterOption(printername, "admin")
415        except PyKotaConfigError :   
416            return "root"
417       
418    def getMailTo(self, printername) :   
419        """Returns the recipient of email messages."""
420        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
421        try :
422            fullmailto = self.getPrinterOption(printername, "mailto")
423        except PyKotaConfigError :   
424            return ("BOTH", None)
425        else :   
426            try :
427                mailto = [x.strip() for x in fullmailto.split('(', 1)]
428            except ValueError :   
429                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
430            if len(mailto) == 1 :   
431                mailto.append("")
432            (mailto, args) = mailto   
433            if args.endswith(')') :
434                args = args[:-1]
435            mailto = mailto.upper()   
436            if (mailto == "EXTERNAL") and not args :
437                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
438            if mailto not in validmailtos :
439                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
440            return (mailto, args)
441       
442    def getGraceDelay(self, printername) :   
443        """Returns the grace delay in days."""
444        try :
445            gd = self.getPrinterOption(printername, "gracedelay")
446        except PyKotaConfigError :   
447            gd = 7
448        try :
449            return int(gd)
450        except (TypeError, ValueError) :   
451            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
452           
453    def getPoorMan(self) :   
454        """Returns the poor man's treshold."""
455        try :
456            pm = self.getGlobalOption("poorman")
457        except PyKotaConfigError :   
458            pm = 1.0
459        try :
460            return float(pm)
461        except (TypeError, ValueError) :   
462            raise PyKotaConfigError, _("Invalid poor man's treshold %s") % pm
463           
464    def getPoorWarn(self) :   
465        """Returns the poor man's warning message."""
466        try :
467            return self.getGlobalOption("poorwarn")
468        except PyKotaConfigError :   
469            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.")
470           
471    def getHardWarn(self, printername) :   
472        """Returns the hard limit error message."""
473        try :
474            return self.getPrinterOption(printername, "hardwarn")
475        except PyKotaConfigError :   
476            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
477           
478    def getSoftWarn(self, printername) :   
479        """Returns the soft limit error message."""
480        try :
481            return self.getPrinterOption(printername, "softwarn")
482        except PyKotaConfigError :   
483            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
484           
485    def getDebug(self) :         
486        """Returns 1 if debugging is activated, else 0."""
487        return self.isTrue(self.getGlobalOption("debug", ignore=1))
488           
489    def getCaching(self) :         
490        """Returns 1 if database caching is enabled, else 0."""
491        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
492           
493    def getLDAPCache(self) :         
494        """Returns 1 if low-level LDAP caching is enabled, else 0."""
495        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
496           
497    def getDisableHistory(self) :         
498        """Returns 1 if we want to disable history, else 0."""
499        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
500           
501    def getUserNameToLower(self) :         
502        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
503        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
Note: See TracBrowser for help on using the browser.