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

Revision 1257, 19.6 kB (checked in by jalet, 20 years ago)

Copyright year changed.

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