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

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

Can now extract per printer pre and post hooks from the configuration file

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