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

Revision 854, 9.1 kB (checked in by jalet, 21 years ago)

Mailto option now accepts some additional values which all mean that
nobody will receive any email message.
Mailto option now works. Version 1.01 is now officially out.

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