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

Revision 980, 12.1 kB (checked in by jalet, 21 years ago)

1.05

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