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

Revision 1646, 20.8 kB (checked in by jalet, 20 years ago)

Typo : treshold ==> threshold

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