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

Revision 1353, 20.0 kB (checked in by jalet, 20 years ago)

maildomain pykota.conf directive added.
Small improvements on mail headers quality.

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