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

Revision 956, 10.6 kB (checked in by jalet, 21 years ago)

Default policy for unknown users/groups is to DENY printing instead
of the previous default to ALLOW printing. This is to solve an accuracy
problem. If you set the policy to ALLOW, jobs printed by in nexistant user
(from PyKota's POV) will be charged to the next user who prints on the
same printer.

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