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

Revision 785, 7.1 kB (checked in by jalet, 22 years ago)

External requester seems to be finally ok now

  • 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.11  2003/02/10 08:50:45  jalet
18# External requester seems to be finally ok now
19#
20# Revision 1.10  2003/02/10 08:19:57  jalet
21# tell ConfigParser to return raw data, this allows our own strings
22# interpolations in the requester
23#
24# Revision 1.9  2003/02/10 00:44:38  jalet
25# Typos
26#
27# Revision 1.8  2003/02/10 00:42:17  jalet
28# External requester should be ok (untested)
29# New syntax for configuration file wrt requesters
30#
31# Revision 1.7  2003/02/09 13:05:43  jalet
32# Internationalization continues...
33#
34# Revision 1.6  2003/02/07 22:00:09  jalet
35# Bad cut&paste
36#
37# Revision 1.5  2003/02/06 23:58:05  jalet
38# repykota should be ok
39#
40# Revision 1.4  2003/02/06 09:19:02  jalet
41# More robust behavior (hopefully) when the user or printer is not managed
42# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
43# printer and/or user not 'yet?' in storage.
44#
45# Revision 1.3  2003/02/05 23:26:22  jalet
46# Incorrect handling of grace delay
47#
48# Revision 1.2  2003/02/05 23:09:20  jalet
49# Name conflict
50#
51# Revision 1.1  2003/02/05 21:28:17  jalet
52# Initial import into CVS
53#
54#
55#
56
57import sys
58import os
59import ConfigParser
60
61class PyKotaConfigError(Exception):
62    """An exception for PyKota config related stuff."""
63    def __init__(self, message = ""):
64        self.message = message
65        Exception.__init__(self, message)
66    def __repr__(self):
67        return self.message
68    __str__ = __repr__
69   
70class PyKotaConfig :
71    """A class to deal with PyKota's configuration."""
72    def __init__(self, directory) :
73        """Reads and checks the configuration file."""
74        self.filename = os.path.join(directory, "pykota.conf")
75        self.config = ConfigParser.ConfigParser()
76        self.config.read([self.filename])
77        self.checkConfiguration()
78       
79    def checkConfiguration(self) :
80        """Checks if configuration is correct.
81       
82           raises PyKotaConfigError in case a problem is detected
83        """
84        for option in [ "storagebackend", "storageserver", \
85                        "storagename", "storageadmin", \
86                        "storageuser", # TODO : "storageadminpw", "storageusepw", \
87                        "logger", "admin", "adminmail",
88                        "smtpserver", "method", "gracedelay" ] :
89            if not self.config.has_option("global", option) :           
90                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
91               
92        # more precise checks       
93        validloggers = [ "stderr", "system" ] 
94        if self.config.get("global", "logger", raw=1).lower() not in validloggers :             
95            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
96           
97        validmethods = [ "lazy" ] # TODO add more methods           
98        if self.config.get("global", "method", raw=1).lower() not in validmethods :             
99            raise PyKotaConfigError, _("Option method only supports values in %s") % str(validmethods)
100           
101        # check all printers now
102        for printer in self.getPrinterNames() :
103            for poption in [ "requester", "policy" ] : 
104                if not self.config.has_option(printer, poption) :
105                    raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printer, self.filename)
106                   
107            validpolicies = [ "ALLOW", "DENY" ]     
108            if self.config.get(printer, "policy", raw=1).upper() not in validpolicies :
109                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printer, str(validpolicies))
110           
111            validrequesters = [ "snmp", "external" ] # TODO : add more requesters
112            fullrequester = self.config.get(printer, "requester", raw=1)
113            try :
114                (requester, args) = [x.strip() for x in fullrequester.split('(', 1)]
115            except ValueError :   
116                raise PyKotaConfigError, _("Invalid requester %s for printer %s") % (fullrequester, printer)
117            else :
118                if requester not in validrequesters :
119                    raise PyKotaConfigError, _("Option requester for printer %s only supports values in %s") % (printer, str(validrequesters))
120                       
121    def getPrinterNames(self) :   
122        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
123        return [pname for pname in self.config.sections() if pname != "global"]
124       
125    def getStorageBackend(self) :   
126        """Returns the storage backend information as a tuple.
127       
128           The tuple has the form :
129           
130             (backend, host, database, admin, user)
131        """       
132        backendinfo = []
133        for option in [ "storagebackend", "storageserver", \
134                        "storagename", "storageadmin", \
135                        "storageuser", # TODO : "storageadminpw", "storageusepw", \
136                      ] :
137            backendinfo.append(self.config.get("global", option, raw=1))
138        return tuple(backendinfo)   
139       
140    def getLoggingBackend(self) :   
141        """Returns the logging backend information."""
142        return self.config.get("global", "logger", raw=1).lower()
143       
144    def getRequesterBackend(self, printer) :   
145        """Returns the requester backend to use for a given printer, with its arguments."""
146        fullrequester = self.config.get(printer, "requester", raw=1)
147        (requester, args) = [x.strip() for x in fullrequester.split('(')]
148        if args.endswith(')') :
149            args = args[:-1]
150        args = [x.strip() for x in args.split(',')]
151        if not args :
152            raise PyKotaConfigError, _("Invalid requester for printer %s") % printer
153        return (requester, args)
154       
155    def getPrinterPolicy(self, printer) :   
156        """Returns the default policy for the current printer."""
157        return self.config.get(printer, "policy", raw=1).upper()
158       
159    def getSMTPServer(self) :   
160        """Returns the SMTP server to use to send messages to users."""
161        return self.config.get("global", "smtpserver", raw=1)
162       
163    def getAdminMail(self) :   
164        """Returns the Email address of the Print Quota Administrator."""
165        return self.config.get("global", "adminmail", raw=1)
166       
167    def getAdmin(self) :   
168        """Returns the full name of the Print Quota Administrator."""
169        return self.config.get("global", "admin", raw=1)
170       
171    def getGraceDelay(self) :   
172        """Returns the grace delay in days."""
173        gd = self.config.get("global", "gracedelay", raw=1)
174        try :
175            return int(gd)
176        except ValueError :   
177            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
Note: See TracBrowser for help on using the browser.