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

Revision 952, 10.2 kB (checked in by jalet, 21 years ago)

Preliminary support for LPRng added BUT STILL UNTESTED.

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