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

Revision 789, 7.3 kB (checked in by jalet, 21 years ago)

Moved some code down into the requesters

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