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

Revision 853, 8.9 kB (checked in by jalet, 21 years ago)

Default hard coded options are now used if they are not set in the
configuration file.

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