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

Revision 780, 6.8 kB (checked in by jalet, 21 years ago)

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