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

Revision 1518, 20.7 kB (checked in by jalet, 20 years ago)

crashrecipient directive

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.49  2004/06/03 21:53:24  jalet
25# crashrecipient directive
26#
27# Revision 1.48  2004/05/24 22:45:49  jalet
28# New 'enforcement' directive added
29# Polling loop improvements
30#
31# Revision 1.47  2004/05/18 14:49:20  jalet
32# Big code changes to completely remove the need for "requester" directives,
33# jsut use "hardware(... your previous requester directive's content ...)"
34#
35# Revision 1.46  2004/05/13 13:59:28  jalet
36# Code simplifications
37#
38# Revision 1.45  2004/03/01 10:22:30  jalet
39# Can now extract per printer pre and post hooks from the configuration file
40#
41# Revision 1.44  2004/02/20 14:42:21  jalet
42# Experimental ldapcache directive added
43#
44# Revision 1.43  2004/02/19 14:20:21  jalet
45# maildomain pykota.conf directive added.
46# Small improvements on mail headers quality.
47#
48# Revision 1.42  2004/01/08 14:10:32  jalet
49# Copyright year changed.
50#
51# Revision 1.41  2003/11/29 20:06:20  jalet
52# Added 'utolower' configuration option to convert all usernames to
53# lowercase when printing. All database accesses are still and will
54# remain case sensitive though.
55#
56# Revision 1.40  2003/11/18 23:43:12  jalet
57# Mailto can be any external command now, as usual.
58#
59# Revision 1.39  2003/10/08 21:41:38  jalet
60# External policies for printers works !
61# We can now auto-add users on first print, and do other useful things if needed.
62#
63# Revision 1.38  2003/10/07 22:06:05  jalet
64# Preliminary code to disable job history
65#
66# Revision 1.37  2003/10/07 09:07:28  jalet
67# Character encoding added to please latest version of Python
68#
69# Revision 1.36  2003/10/02 20:23:18  jalet
70# Storage caching mechanism added.
71#
72# Revision 1.35  2003/07/29 09:54:03  jalet
73# Added configurable LDAP mail attribute support
74#
75# Revision 1.34  2003/07/28 09:11:12  jalet
76# PyKota now tries to add its attributes intelligently in existing LDAP
77# directories.
78#
79# Revision 1.33  2003/07/16 21:53:07  jalet
80# Really big modifications wrt new configuration file's location and content.
81#
82# Revision 1.32  2003/07/08 19:43:51  jalet
83# Configurable warning messages.
84# Poor man's treshold value added.
85#
86# Revision 1.31  2003/07/07 11:49:24  jalet
87# Lots of small fixes with the help of PyChecker
88#
89# Revision 1.30  2003/06/25 14:10:01  jalet
90# Hey, it may work (edpykota --reset excepted) !
91#
92# Revision 1.29  2003/06/14 22:44:21  jalet
93# More work on LDAP storage backend.
94#
95# Revision 1.28  2003/06/10 16:37:54  jalet
96# Deletion of the second user which is not needed anymore.
97# Added a debug configuration field in /etc/pykota.conf
98# All queries can now be sent to the logger in debug mode, this will
99# greatly help improve performance when time for this will come.
100#
101# Revision 1.27  2003/05/27 23:00:21  jalet
102# Big rewrite of external accounting methods.
103# Should work well now.
104#
105# Revision 1.26  2003/04/30 19:53:58  jalet
106# 1.05
107#
108# Revision 1.25  2003/04/30 13:36:40  jalet
109# Stupid accounting method was added.
110#
111# Revision 1.24  2003/04/29 18:37:54  jalet
112# Pluggable accounting methods (actually doesn't support external scripts)
113#
114# Revision 1.23  2003/04/24 11:53:48  jalet
115# Default policy for unknown users/groups is to DENY printing instead
116# of the previous default to ALLOW printing. This is to solve an accuracy
117# problem. If you set the policy to ALLOW, jobs printed by in nexistant user
118# (from PyKota's POV) will be charged to the next user who prints on the
119# same printer.
120#
121# Revision 1.22  2003/04/23 22:13:57  jalet
122# Preliminary support for LPRng added BUT STILL UNTESTED.
123#
124# Revision 1.21  2003/03/29 13:45:27  jalet
125# GPL paragraphs were incorrectly (from memory) copied into the sources.
126# Two README files were added.
127# Upgrade script for PostgreSQL pre 1.01 schema was added.
128#
129# Revision 1.20  2003/03/29 13:08:28  jalet
130# Configuration is now expected to be found in /etc/pykota.conf instead of
131# in /etc/cups/pykota.conf
132# Installation script can move old config files to the new location if needed.
133# Better error handling if configuration file is absent.
134#
135# Revision 1.19  2003/03/16 09:56:52  jalet
136# Mailto option now accepts some additional values which all mean that
137# nobody will receive any email message.
138# Mailto option now works. Version 1.01 is now officially out.
139#
140# Revision 1.18  2003/03/16 08:00:50  jalet
141# Default hard coded options are now used if they are not set in the
142# configuration file.
143#
144# Revision 1.17  2003/03/15 23:01:28  jalet
145# New mailto option in configuration file added.
146# No time to test this tonight (although it should work).
147#
148# Revision 1.16  2003/02/17 23:01:56  jalet
149# Typos
150#
151# Revision 1.15  2003/02/17 22:55:01  jalet
152# More options can now be set per printer or globally :
153#
154#       admin
155#       adminmail
156#       gracedelay
157#       requester
158#
159# the printer option has priority when both are defined.
160#
161# Revision 1.14  2003/02/17 22:05:50  jalet
162# Storage backend now supports admin and user passwords (untested)
163#
164# Revision 1.13  2003/02/10 11:47:39  jalet
165# Moved some code down into the requesters
166#
167# Revision 1.12  2003/02/10 10:36:33  jalet
168# Small problem wrt external requester
169#
170# Revision 1.11  2003/02/10 08:50:45  jalet
171# External requester seems to be finally ok now
172#
173# Revision 1.10  2003/02/10 08:19:57  jalet
174# tell ConfigParser to return raw data, this allows our own strings
175# interpolations in the requester
176#
177# Revision 1.9  2003/02/10 00:44:38  jalet
178# Typos
179#
180# Revision 1.8  2003/02/10 00:42:17  jalet
181# External requester should be ok (untested)
182# New syntax for configuration file wrt requesters
183#
184# Revision 1.7  2003/02/09 13:05:43  jalet
185# Internationalization continues...
186#
187# Revision 1.6  2003/02/07 22:00:09  jalet
188# Bad cut&paste
189#
190# Revision 1.5  2003/02/06 23:58:05  jalet
191# repykota should be ok
192#
193# Revision 1.4  2003/02/06 09:19:02  jalet
194# More robust behavior (hopefully) when the user or printer is not managed
195# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
196# printer and/or user not 'yet?' in storage.
197#
198# Revision 1.3  2003/02/05 23:26:22  jalet
199# Incorrect handling of grace delay
200#
201# Revision 1.2  2003/02/05 23:09:20  jalet
202# Name conflict
203#
204# Revision 1.1  2003/02/05 21:28:17  jalet
205# Initial import into CVS
206#
207#
208#
209
210import os
211import ConfigParser
212
213class PyKotaConfigError(Exception):
214    """An exception for PyKota config related stuff."""
215    def __init__(self, message = ""):
216        self.message = message
217        Exception.__init__(self, message)
218    def __repr__(self):
219        return self.message
220    __str__ = __repr__
221   
222class PyKotaConfig :
223    """A class to deal with PyKota's configuration."""
224    def __init__(self, directory) :
225        """Reads and checks the configuration file."""
226        self.filename = os.path.join(directory, "pykota.conf")
227        if not os.path.isfile(self.filename) :
228            raise PyKotaConfigError, _("Configuration file %s not found.") % self.filename
229        self.config = ConfigParser.ConfigParser()
230        self.config.read([self.filename])
231           
232    def isTrue(self, option) :       
233        """Returns 1 if option is set to true, else 0."""
234        if (option is not None) and (option.upper().strip() in ['Y', 'YES', '1', 'ON', 'T', 'TRUE']) :
235            return 1
236        else :   
237            return 0
238                       
239    def getPrinterNames(self) :   
240        """Returns the list of configured printers, i.e. all sections names minus 'global'."""
241        return [pname for pname in self.config.sections() if pname != "global"]
242       
243    def getGlobalOption(self, option, ignore=0) :   
244        """Returns an option from the global section, or raises a PyKotaConfigError if ignore is not set, else returns None."""
245        try :
246            return self.config.get("global", option, raw=1)
247        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
248            if ignore :
249                return
250            else :
251                raise PyKotaConfigError, _("Option %s not found in section global of %s") % (option, self.filename)
252               
253    def getPrinterOption(self, printername, option) :   
254        """Returns an option from the printer section, or the global section, or raises a PyKotaConfigError."""
255        globaloption = self.getGlobalOption(option, ignore=1)
256        try :
257            return self.config.get(printername, option, raw=1)
258        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
259            if globaloption is not None :
260                return globaloption
261            else :
262                raise PyKotaConfigError, _("Option %s not found in section %s of %s") % (option, printername, self.filename)
263       
264    def getStorageBackend(self) :   
265        """Returns the storage backend information as a Python mapping."""       
266        backendinfo = {}
267        for option in [ "storagebackend", "storageserver", \
268                        "storagename", "storageuser", \
269                      ] :
270            backendinfo[option] = self.getGlobalOption(option)
271        backendinfo["storageuserpw"] = self.getGlobalOption("storageuserpw", ignore=1)  # password is optional
272        backendinfo["storageadmin"] = None
273        backendinfo["storageadminpw"] = None
274        adminconf = ConfigParser.ConfigParser()
275        adminconf.read(["/etc/pykota/pykotadmin.conf"])
276        if adminconf.sections() : # were we able to read the file ?
277            try :
278                backendinfo["storageadmin"] = adminconf.get("global", "storageadmin", raw=1)
279            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
280                raise PyKotaConfigError, _("Option %s not found in section global of %s") % ("storageadmin", "/etc/pykota/pykotadmin.conf")
281            try :
282                backendinfo["storageadminpw"] = adminconf.get("global", "storageadminpw", raw=1)
283            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) :   
284                pass # Password is optional
285        return backendinfo
286       
287    def getLDAPInfo(self) :   
288        """Returns some hints for the LDAP backend."""       
289        ldapinfo = {}
290        for option in [ "userbase", "userrdn", \
291                        "balancebase", "balancerdn", \
292                        "groupbase", "grouprdn", "groupmembers", \
293                        "printerbase", "printerrdn", \
294                        "userquotabase", "groupquotabase", \
295                        "jobbase", "lastjobbase", \
296                        "newuser", "newgroup", \
297                        "usermail", \
298                      ] :
299            ldapinfo[option] = self.getGlobalOption(option).strip()
300        for field in ["newuser", "newgroup"] :
301            if ldapinfo[field].lower().startswith('attach(') :
302                ldapinfo[field] = ldapinfo[field][7:-1]
303        return ldapinfo
304       
305    def getLoggingBackend(self) :   
306        """Returns the logging backend information."""
307        validloggers = [ "stderr", "system" ] 
308        try :
309            logger = self.getGlobalOption("logger").lower()
310        except PyKotaConfigError :   
311            logger = "system"
312        if logger not in validloggers :             
313            raise PyKotaConfigError, _("Option logger only supports values in %s") % str(validloggers)
314        return logger   
315       
316    def getAccounterBackend(self, printername) :   
317        """Returns the accounter backend to use for a given printer.
318       
319           if it is not set, it defaults to 'hardware' which means ask printer
320           for its internal lifetime page counter.
321        """   
322        validaccounters = [ "hardware", "software" ]     
323        fullaccounter = self.getPrinterOption(printername, "accounter").strip()
324        flower = fullaccounter.lower()
325        if flower.startswith("software") or flower.startswith("hardware") :   
326            try :
327                (accounter, args) = [x.strip() for x in fullaccounter.split('(', 1)]
328            except ValueError :   
329                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
330            if args.endswith(')') :
331                args = args[:-1]
332            if not args :
333                raise PyKotaConfigError, _("Invalid accounter %s for printer %s") % (fullaccounter, printername)
334            return (accounter.lower(), args)   
335        else :
336            raise PyKotaConfigError, _("Option accounter in section %s only supports values in %s") % (printername, str(validaccounters))
337       
338    def getPreHook(self, printername) :   
339        """Returns the prehook command line to launch, or None if unset."""
340        try :
341            return self.getPrinterOption(printername, "prehook").strip()
342        except PyKotaConfigError :   
343            return      # No command to launch in the pre-hook
344           
345    def getPostHook(self, printername) :   
346        """Returns the posthook command line to launch, or None if unset."""
347        try :
348            return self.getPrinterOption(printername, "posthook").strip()
349        except PyKotaConfigError :   
350            return      # No command to launch in the post-hook
351           
352    def getPrinterEnforcement(self, printername) :   
353        """Returns if quota enforcement should be strict or laxist for the current printer."""
354        validenforcements = [ "STRICT", "LAXIST" ]     
355        try :
356            enforcement = self.getPrinterOption(printername, "enforcement")
357        except PyKotaConfigError :   
358            return "LAXIST"
359        else :   
360            enforcement = enforcement.upper()
361            if enforcement not in validenforcements :
362                raise PyKotaConfigError, _("Option enforcement in section %s only supports values in %s") % (printername, str(validenforcements))
363            return enforcement   
364           
365    def getPrinterPolicy(self, printername) :   
366        """Returns the default policy for the current printer."""
367        validpolicies = [ "ALLOW", "DENY", "EXTERNAL" ]     
368        try :
369            fullpolicy = self.getPrinterOption(printername, "policy")
370        except PyKotaConfigError :   
371            return ("DENY", None)
372        else :   
373            try :
374                policy = [x.strip() for x in fullpolicy.split('(', 1)]
375            except ValueError :   
376                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
377            if len(policy) == 1 :   
378                policy.append("")
379            (policy, args) = policy   
380            if args.endswith(')') :
381                args = args[:-1]
382            policy = policy.upper()   
383            if (policy == "EXTERNAL") and not args :
384                raise PyKotaConfigError, _("Invalid policy %s for printer %s") % (fullpolicy, printername)
385            if policy not in validpolicies :
386                raise PyKotaConfigError, _("Option policy in section %s only supports values in %s") % (printername, str(validpolicies))
387            return (policy, args)
388       
389    def getCrashRecipient(self) :   
390        """Returns the email address of the software crash messages recipient."""
391        try :
392            return self.getGlobalOption("crashrecipient")
393        except :   
394            return
395           
396    def getSMTPServer(self) :   
397        """Returns the SMTP server to use to send messages to users."""
398        try :
399            return self.getGlobalOption("smtpserver")
400        except PyKotaConfigError :   
401            return "localhost"
402       
403    def getMailDomain(self) :   
404        """Returns the mail domain to use to send messages to users."""
405        try :
406            return self.getGlobalOption("maildomain")
407        except PyKotaConfigError :   
408            return 
409       
410    def getAdminMail(self, printername) :   
411        """Returns the Email address of the Print Quota Administrator."""
412        try :
413            return self.getPrinterOption(printername, "adminmail")
414        except PyKotaConfigError :   
415            return "root@localhost"
416       
417    def getAdmin(self, printername) :   
418        """Returns the full name of the Print Quota Administrator."""
419        try :
420            return self.getPrinterOption(printername, "admin")
421        except PyKotaConfigError :   
422            return "root"
423       
424    def getMailTo(self, printername) :   
425        """Returns the recipient of email messages."""
426        validmailtos = [ "EXTERNAL", "NOBODY", "NONE", "NOONE", "BITBUCKET", "DEVNULL", "BOTH", "USER", "ADMIN" ]
427        try :
428            fullmailto = self.getPrinterOption(printername, "mailto")
429        except PyKotaConfigError :   
430            return ("BOTH", None)
431        else :   
432            try :
433                mailto = [x.strip() for x in fullmailto.split('(', 1)]
434            except ValueError :   
435                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
436            if len(mailto) == 1 :   
437                mailto.append("")
438            (mailto, args) = mailto   
439            if args.endswith(')') :
440                args = args[:-1]
441            mailto = mailto.upper()   
442            if (mailto == "EXTERNAL") and not args :
443                raise PyKotaConfigError, _("Invalid option mailto %s for printer %s") % (fullmailto, printername)
444            if mailto not in validmailtos :
445                raise PyKotaConfigError, _("Option mailto in section %s only supports values in %s") % (printername, str(validmailtos))
446            return (mailto, args)
447       
448    def getGraceDelay(self, printername) :   
449        """Returns the grace delay in days."""
450        try :
451            gd = self.getPrinterOption(printername, "gracedelay")
452        except PyKotaConfigError :   
453            gd = 7
454        try :
455            return int(gd)
456        except (TypeError, ValueError) :   
457            raise PyKotaConfigError, _("Invalid grace delay %s") % gd
458           
459    def getPoorMan(self) :   
460        """Returns the poor man's treshold."""
461        try :
462            pm = self.getGlobalOption("poorman")
463        except PyKotaConfigError :   
464            pm = 1.0
465        try :
466            return float(pm)
467        except (TypeError, ValueError) :   
468            raise PyKotaConfigError, _("Invalid poor man's treshold %s") % pm
469           
470    def getPoorWarn(self) :   
471        """Returns the poor man's warning message."""
472        try :
473            return self.getGlobalOption("poorwarn")
474        except PyKotaConfigError :   
475            return _("Your Print Quota account balance is Low.\nSoon you'll not be allowed to print anymore.\nPlease contact the Print Quota Administrator to solve the problem.")
476           
477    def getHardWarn(self, printername) :   
478        """Returns the hard limit error message."""
479        try :
480            return self.getPrinterOption(printername, "hardwarn")
481        except PyKotaConfigError :   
482            return _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername
483           
484    def getSoftWarn(self, printername) :   
485        """Returns the soft limit error message."""
486        try :
487            return self.getPrinterOption(printername, "softwarn")
488        except PyKotaConfigError :   
489            return _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername
490           
491    def getDebug(self) :         
492        """Returns 1 if debugging is activated, else 0."""
493        return self.isTrue(self.getGlobalOption("debug", ignore=1))
494           
495    def getCaching(self) :         
496        """Returns 1 if database caching is enabled, else 0."""
497        return self.isTrue(self.getGlobalOption("storagecaching", ignore=1))
498           
499    def getLDAPCache(self) :         
500        """Returns 1 if low-level LDAP caching is enabled, else 0."""
501        return self.isTrue(self.getGlobalOption("ldapcache", ignore=1))
502           
503    def getDisableHistory(self) :         
504        """Returns 1 if we want to disable history, else 0."""
505        return self.isTrue(self.getGlobalOption("disablehistory", ignore=1))
506           
507    def getUserNameToLower(self) :         
508        """Returns 1 if we want to convert usernames to lowercase when printing, else 0."""
509        return self.isTrue(self.getGlobalOption("utolower", ignore=1))
Note: See TracBrowser for help on using the browser.