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

Revision 1144, 17.1 kB (checked in by jalet, 21 years ago)

Character encoding added to please latest version of Python

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