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

Revision 1152, 18.4 kB (checked in by jalet, 21 years ago)

External policies for printers works !
We can now auto-add users on first print, and do other useful things if needed.

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