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

Revision 1105, 16.5 kB (checked in by jalet, 21 years ago)

PyKota now tries to add its attributes intelligently in existing LDAP
directories.

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