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

Revision 1130, 17.0 kB (checked in by jalet, 21 years ago)

Storage caching mechanism added.

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