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

Revision 872, 9.5 kB (checked in by jalet, 21 years ago)

Configuration is now expected to be found in /etc/pykota.conf instead of
in /etc/cups/pykota.conf
Installation script can move old config files to the new location if needed.
Better error handling if configuration file is absent.

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