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

Revision 1192, 19.3 kB (checked in by jalet, 20 years ago)

Mailto can be any external command now, as usual.

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