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

Revision 783, 7.0 kB (checked in by jalet, 21 years ago)

tell ConfigParser? to return raw data, this allows our own strings
interpolations in the requester

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