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

Revision 973, 11.3 kB (checked in by jalet, 21 years ago)

Pluggable accounting methods (actually doesn't support external scripts)

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