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

Revision 976, 11.4 kB (checked in by jalet, 21 years ago)

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