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

Revision 1021, 12.8 kB (checked in by jalet, 21 years ago)

Deletion of the second user which is not needed anymore.
Added a debug configuration field in /etc/pykota.conf
All queries can now be sent to the logger in debug mode, this will
greatly help improve performance when time for this will come.

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