root / pykota / trunk / pykota / tool.py @ 1152

Revision 1152, 22.4 kB (checked in by jalet, 21 years ago)

External policies for printers works !
We can now auto-add users on first print, and do other useful things if needed.

  • 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 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.53  2003/10/08 21:41:38  jalet
25# External policies for printers works !
26# We can now auto-add users on first print, and do other useful things if needed.
27#
28# Revision 1.52  2003/10/07 09:07:28  jalet
29# Character encoding added to please latest version of Python
30#
31# Revision 1.51  2003/10/06 14:21:41  jalet
32# Test reversed to not retrieve group members when no messages for them.
33#
34# Revision 1.50  2003/10/02 20:23:18  jalet
35# Storage caching mechanism added.
36#
37# Revision 1.49  2003/07/29 20:55:17  jalet
38# 1.14 is out !
39#
40# Revision 1.48  2003/07/21 23:01:56  jalet
41# Modified some messages aout soft limit
42#
43# Revision 1.47  2003/07/16 21:53:08  jalet
44# Really big modifications wrt new configuration file's location and content.
45#
46# Revision 1.46  2003/07/09 20:17:07  jalet
47# Email field added to PostgreSQL schema
48#
49# Revision 1.45  2003/07/08 19:43:51  jalet
50# Configurable warning messages.
51# Poor man's treshold value added.
52#
53# Revision 1.44  2003/07/07 11:49:24  jalet
54# Lots of small fixes with the help of PyChecker
55#
56# Revision 1.43  2003/07/04 09:06:32  jalet
57# Small bug fix wrt undefined "LimitBy" field.
58#
59# Revision 1.42  2003/06/30 12:46:15  jalet
60# Extracted reporting code.
61#
62# Revision 1.41  2003/06/25 14:10:01  jalet
63# Hey, it may work (edpykota --reset excepted) !
64#
65# Revision 1.40  2003/06/10 16:37:54  jalet
66# Deletion of the second user which is not needed anymore.
67# Added a debug configuration field in /etc/pykota.conf
68# All queries can now be sent to the logger in debug mode, this will
69# greatly help improve performance when time for this will come.
70#
71# Revision 1.39  2003/04/29 18:37:54  jalet
72# Pluggable accounting methods (actually doesn't support external scripts)
73#
74# Revision 1.38  2003/04/24 11:53:48  jalet
75# Default policy for unknown users/groups is to DENY printing instead
76# of the previous default to ALLOW printing. This is to solve an accuracy
77# problem. If you set the policy to ALLOW, jobs printed by in nexistant user
78# (from PyKota's POV) will be charged to the next user who prints on the
79# same printer.
80#
81# Revision 1.37  2003/04/24 08:08:27  jalet
82# Debug message forgotten
83#
84# Revision 1.36  2003/04/24 07:59:40  jalet
85# LPRng support now works !
86#
87# Revision 1.35  2003/04/23 22:13:57  jalet
88# Preliminary support for LPRng added BUT STILL UNTESTED.
89#
90# Revision 1.34  2003/04/17 09:26:21  jalet
91# repykota now reports account balances too.
92#
93# Revision 1.33  2003/04/16 12:35:49  jalet
94# Groups quota work now !
95#
96# Revision 1.32  2003/04/16 08:53:14  jalet
97# Printing can now be limited either by user's account balance or by
98# page quota (the default). Quota report doesn't include account balance
99# yet, though.
100#
101# Revision 1.31  2003/04/15 11:30:57  jalet
102# More work done on money print charging.
103# Minor bugs corrected.
104# All tools now access to the storage as priviledged users, repykota excepted.
105#
106# Revision 1.30  2003/04/10 21:47:20  jalet
107# Job history added. Upgrade script neutralized for now !
108#
109# Revision 1.29  2003/03/29 13:45:27  jalet
110# GPL paragraphs were incorrectly (from memory) copied into the sources.
111# Two README files were added.
112# Upgrade script for PostgreSQL pre 1.01 schema was added.
113#
114# Revision 1.28  2003/03/29 13:08:28  jalet
115# Configuration is now expected to be found in /etc/pykota.conf instead of
116# in /etc/cups/pykota.conf
117# Installation script can move old config files to the new location if needed.
118# Better error handling if configuration file is absent.
119#
120# Revision 1.27  2003/03/15 23:01:28  jalet
121# New mailto option in configuration file added.
122# No time to test this tonight (although it should work).
123#
124# Revision 1.26  2003/03/09 23:58:16  jalet
125# Comment
126#
127# Revision 1.25  2003/03/07 22:56:14  jalet
128# 0.99 is out with some bug fixes.
129#
130# Revision 1.24  2003/02/27 23:48:41  jalet
131# Correctly maps PyKota's log levels to syslog log levels
132#
133# Revision 1.23  2003/02/27 22:55:20  jalet
134# WARN log priority doesn't exist.
135#
136# Revision 1.22  2003/02/27 09:09:20  jalet
137# Added a method to match strings against wildcard patterns
138#
139# Revision 1.21  2003/02/17 23:01:56  jalet
140# Typos
141#
142# Revision 1.20  2003/02/17 22:55:01  jalet
143# More options can now be set per printer or globally :
144#
145#       admin
146#       adminmail
147#       gracedelay
148#       requester
149#
150# the printer option has priority when both are defined.
151#
152# Revision 1.19  2003/02/10 11:28:45  jalet
153# Localization
154#
155# Revision 1.18  2003/02/10 01:02:17  jalet
156# External requester is about to work, but I must sleep
157#
158# Revision 1.17  2003/02/09 13:05:43  jalet
159# Internationalization continues...
160#
161# Revision 1.16  2003/02/09 12:56:53  jalet
162# Internationalization begins...
163#
164# Revision 1.15  2003/02/08 22:09:52  jalet
165# Name check method moved here
166#
167# Revision 1.14  2003/02/07 10:42:45  jalet
168# Indentation problem
169#
170# Revision 1.13  2003/02/07 08:34:16  jalet
171# Test wrt date limit was wrong
172#
173# Revision 1.12  2003/02/06 23:20:02  jalet
174# warnpykota doesn't need any user/group name argument, mimicing the
175# warnquota disk quota tool.
176#
177# Revision 1.11  2003/02/06 22:54:33  jalet
178# warnpykota should be ok
179#
180# Revision 1.10  2003/02/06 15:03:11  jalet
181# added a method to set the limit date
182#
183# Revision 1.9  2003/02/06 10:39:23  jalet
184# Preliminary edpykota work.
185#
186# Revision 1.8  2003/02/06 09:19:02  jalet
187# More robust behavior (hopefully) when the user or printer is not managed
188# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
189# printer and/or user not 'yet?' in storage.
190#
191# Revision 1.7  2003/02/06 00:00:45  jalet
192# Now includes the printer name in email messages
193#
194# Revision 1.6  2003/02/05 23:55:02  jalet
195# Cleaner email messages
196#
197# Revision 1.5  2003/02/05 23:45:09  jalet
198# Better DateTime manipulation wrt grace delay
199#
200# Revision 1.4  2003/02/05 23:26:22  jalet
201# Incorrect handling of grace delay
202#
203# Revision 1.3  2003/02/05 22:16:20  jalet
204# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
205#
206# Revision 1.2  2003/02/05 22:10:29  jalet
207# Typos
208#
209# Revision 1.1  2003/02/05 21:28:17  jalet
210# Initial import into CVS
211#
212#
213#
214
215import sys
216import fnmatch
217import getopt
218import smtplib
219import gettext
220import locale
221
222from mx import DateTime
223
224from pykota import version, config, storage, logger
225
226class PyKotaToolError(Exception):
227    """An exception for PyKota config related stuff."""
228    def __init__(self, message = ""):
229        self.message = message
230        Exception.__init__(self, message)
231    def __repr__(self):
232        return self.message
233    __str__ = __repr__
234   
235class PyKotaTool :   
236    """Base class for all PyKota command line tools."""
237    def __init__(self, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
238        """Initializes the command line tool."""
239        # locale stuff
240        try :
241            locale.setlocale(locale.LC_ALL, "")
242            gettext.install("pykota")
243        except (locale.Error, IOError) :
244            gettext.NullTranslations().install()
245   
246        # pykota specific stuff
247        self.documentation = doc
248        self.config = config.PyKotaConfig("/etc/pykota")
249        self.logger = logger.openLogger(self)
250        self.debug = self.config.getDebug()
251        self.storage = storage.openConnection(self)
252        self.smtpserver = self.config.getSMTPServer()
253       
254    def logdebug(self, message) :   
255        """Logs something to debug output if debug is enabled."""
256        if self.debug :
257            self.logger.log_message(message, "debug")
258       
259    def clean(self) :   
260        """Ensures that the database is closed."""
261        try :
262            self.storage.close()
263        except (TypeError, NameError, AttributeError) :   
264            pass
265           
266    def display_version_and_quit(self) :
267        """Displays version number, then exists successfully."""
268        self.clean()
269        print version.__version__
270        sys.exit(0)
271   
272    def display_usage_and_quit(self) :
273        """Displays command line usage, then exists successfully."""
274        self.clean()
275        print self.documentation
276        sys.exit(0)
277       
278    def parseCommandline(self, argv, short, long, allownothing=0) :
279        """Parses the command line, controlling options."""
280        # split options in two lists: those which need an argument, those which don't need any
281        withoutarg = []
282        witharg = []
283        lgs = len(short)
284        i = 0
285        while i < lgs :
286            ii = i + 1
287            if (ii < lgs) and (short[ii] == ':') :
288                # needs an argument
289                witharg.append(short[i])
290                ii = ii + 1 # skip the ':'
291            else :
292                # doesn't need an argument
293                withoutarg.append(short[i])
294            i = ii
295               
296        for option in long :
297            if option[-1] == '=' :
298                # needs an argument
299                witharg.append(option[:-1])
300            else :
301                # doesn't need an argument
302                withoutarg.append(option)
303       
304        # we begin with all possible options unset
305        parsed = {}
306        for option in withoutarg + witharg :
307            parsed[option] = None
308       
309        # then we parse the command line
310        args = []       # to not break if something unexpected happened
311        try :
312            options, args = getopt.getopt(argv, short, long)
313            if options :
314                for (o, v) in options :
315                    # we skip the '-' chars
316                    lgo = len(o)
317                    i = 0
318                    while (i < lgo) and (o[i] == '-') :
319                        i = i + 1
320                    o = o[i:]
321                    if o in witharg :
322                        # needs an argument : set it
323                        parsed[o] = v
324                    elif o in withoutarg :
325                        # doesn't need an argument : boolean
326                        parsed[o] = 1
327                    else :
328                        # should never occur
329                        raise PyKotaToolError, "Unexpected problem when parsing command line"
330            elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
331                self.display_usage_and_quit()
332        except getopt.error, msg :
333            sys.stderr.write("%s\n" % msg)
334            sys.stderr.flush()
335            self.display_usage_and_quit()
336        return (parsed, args)
337   
338    def isValidName(self, name) :
339        """Checks if a user or printer name is valid."""
340        # unfortunately Python 2.1 string modules doesn't define ascii_letters...
341        asciiletters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
342        digits = '0123456789'
343        if name[0] in asciiletters :
344            validchars = asciiletters + digits + "-_"
345            for c in name[1:] :
346                if c not in validchars :
347                    return 0
348            return 1       
349        return 0
350       
351    def matchString(self, s, patterns) :
352        """Returns 1 if the string s matches one of the patterns, else 0."""
353        for pattern in patterns :
354            if fnmatch.fnmatchcase(s, pattern) :
355                return 1
356        return 0
357       
358    def sendMessage(self, adminmail, touser, fullmessage) :
359        """Sends an email message containing headers to some user."""
360        if "@" not in touser :
361            touser = "%s@%s" % (touser, self.smtpserver)
362        server = smtplib.SMTP(self.smtpserver)
363        try :
364            server.sendmail(adminmail, [touser], fullmessage)
365        except smtplib.SMTPRecipientsRefused, answer :   
366            for (k, v) in answer.recipients.items() :
367                self.logger.log_message(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error")
368        server.quit()
369       
370    def sendMessageToUser(self, admin, adminmail, user, subject, message) :
371        """Sends an email message to a user."""
372        message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail)
373        self.sendMessage(adminmail, user.Email or user.Name, "Subject: %s\n\n%s" % (subject, message))
374       
375    def sendMessageToAdmin(self, adminmail, subject, message) :
376        """Sends an email message to the Print Quota administrator."""
377        self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message))
378       
379    def checkGroupPQuota(self, grouppquota) :   
380        """Checks the group quota on a printer and deny or accept the job."""
381        group = grouppquota.Group
382        printer = grouppquota.Printer
383        if group.LimitBy and (group.LimitBy.lower() == "balance") : 
384            if group.AccountBalance <= 0.0 :
385                action = "DENY"
386            elif group.AccountBalance <= self.config.getPoorMan() :   
387                action = "WARN"
388            else :   
389                action = "ALLOW"
390        else :
391            if grouppquota.SoftLimit is not None :
392                softlimit = int(grouppquota.SoftLimit)
393                if grouppquota.PageCounter < softlimit :
394                    action = "ALLOW"
395                else :   
396                    if grouppquota.HardLimit is None :
397                        # only a soft limit, this is equivalent to having only a hard limit
398                        action = "DENY"
399                    else :   
400                        hardlimit = int(grouppquota.HardLimit)
401                        if softlimit <= grouppquota.PageCounter < hardlimit :   
402                            now = DateTime.now()
403                            if grouppquota.DateLimit is not None :
404                                datelimit = DateTime.ISO.ParseDateTime(grouppquota.DateLimit)
405                            else :
406                                datelimit = now + self.config.getGraceDelay(printer.Name)
407                                grouppquota.setDateLimit(datelimit)
408                            if now < datelimit :
409                                action = "WARN"
410                            else :   
411                                action = "DENY"
412                        else :         
413                            action = "DENY"
414            else :       
415                if grouppquota.HardLimit is not None :
416                    # no soft limit, only a hard one.
417                    hardlimit = int(grouppquota.HardLimit)
418                    if grouppquota.PageCounter < hardlimit :
419                        action = "ALLOW"
420                    else :     
421                        action = "DENY"
422                else :
423                    # Both are unset, no quota, i.e. accounting only
424                    action = "ALLOW"
425        return action
426   
427    def checkUserPQuota(self, userpquota) :
428        """Checks the user quota on a printer and deny or accept the job."""
429        user = userpquota.User
430        printer = userpquota.Printer
431       
432        # first we check any group the user is a member of
433        for group in self.storage.getUserGroups(user) :
434            grouppquota = self.storage.getGroupPQuota(group, printer)
435            if grouppquota.Exists :
436                action = self.checkGroupPQuota(grouppquota)
437                if action == "DENY" :
438                    return action
439               
440        # then we check the user's own quota
441        # if we get there we are sure that policy is not EXTERNAL
442        (policy, dummy) = self.config.getPrinterPolicy(printer.Name)
443        if user.LimitBy and (user.LimitBy.lower() == "balance") : 
444            if user.AccountBalance is None :
445                if policy == "ALLOW" :
446                    action = "POLICY_ALLOW"
447                else :   
448                    action = "POLICY_DENY"
449                self.logger.log_message(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name))
450            else :   
451                val = float(user.AccountBalance or 0.0)
452                if val <= 0.0 :
453                    action = "DENY"
454                elif val <= self.config.getPoorMan() :   
455                    action = "WARN"
456                else :   
457                    action = "ALLOW"
458        else :
459            if not userpquota.Exists :
460                # Unknown userquota
461                if policy == "ALLOW" :
462                    action = "POLICY_ALLOW"
463                else :   
464                    action = "POLICY_DENY"
465                self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action))
466            else :   
467                pagecounter = int(userpquota.PageCounter or 0)
468                if userpquota.SoftLimit is not None :
469                    softlimit = int(userpquota.SoftLimit)
470                    if pagecounter < softlimit :
471                        action = "ALLOW"
472                    else :   
473                        if userpquota.HardLimit is None :
474                            # only a soft limit, this is equivalent to having only a hard limit
475                            action = "DENY"
476                        else :   
477                            hardlimit = int(userpquota.HardLimit)
478                            if softlimit <= pagecounter < hardlimit :   
479                                now = DateTime.now()
480                                if userpquota.DateLimit is not None :
481                                    datelimit = DateTime.ISO.ParseDateTime(userpquota.DateLimit)
482                                else :
483                                    datelimit = now + self.config.getGraceDelay(printer.Name)
484                                    userpquota.setDateLimit(datelimit)
485                                if now < datelimit :
486                                    action = "WARN"
487                                else :   
488                                    action = "DENY"
489                            else :         
490                                action = "DENY"
491                else :       
492                    if userpquota.HardLimit is not None :
493                        # no soft limit, only a hard one.
494                        hardlimit = int(userpquota.HardLimit)
495                        if pagecounter < hardlimit :
496                            action = "ALLOW"
497                        else :     
498                            action = "DENY"
499                    else :
500                        # Both are unset, no quota, i.e. accounting only
501                        action = "ALLOW"
502        return action
503   
504    def warnGroupPQuota(self, grouppquota) :
505        """Checks a group quota and send messages if quota is exceeded on current printer."""
506        group = grouppquota.Group
507        printer = grouppquota.Printer
508        admin = self.config.getAdmin(printer.Name)
509        adminmail = self.config.getAdminMail(printer.Name)
510        mailto = self.config.getMailTo(printer.Name)
511        action = self.checkGroupPQuota(grouppquota)
512        if action.startswith("POLICY_") :
513            action = action[7:]
514        if action == "DENY" :
515            adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name)
516            self.logger.log_message(adminmessage)
517            if mailto in [ "BOTH", "ADMIN" ] :
518                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
519            if mailto in [ "BOTH", "USER" ] :
520                for user in self.storage.getGroupMembers(group) :
521                    self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name))
522        elif action == "WARN" :   
523            adminmessage = _("Print Quota low for group %s on printer %s") % (group.Name, printer.Name)
524            self.logger.log_message(adminmessage)
525            if mailto in [ "BOTH", "ADMIN" ] :
526                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
527            if group.LimitBy and (group.LimitBy.lower() == "balance") : 
528                message = self.config.getPoorWarn()
529            else :     
530                message = self.config.getSoftWarn(printer.Name)
531            if mailto in [ "BOTH", "USER" ] :
532                for user in self.storage.getGroupMembers(group) :
533                    self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message)
534        return action       
535       
536    def warnUserPQuota(self, userpquota) :
537        """Checks a user quota and send him a message if quota is exceeded on current printer."""
538        user = userpquota.User
539        printer = userpquota.Printer
540        admin = self.config.getAdmin(printer.Name)
541        adminmail = self.config.getAdminMail(printer.Name)
542        mailto = self.config.getMailTo(printer.Name)
543        action = self.checkUserPQuota(userpquota)
544        if action.startswith("POLICY_") :
545            action = action[7:]
546        if action == "DENY" :
547            adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name)
548            self.logger.log_message(adminmessage)
549            if mailto in [ "BOTH", "USER" ] :
550                self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name))
551            if mailto in [ "BOTH", "ADMIN" ] :
552                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
553        elif action == "WARN" :   
554            adminmessage = _("Print Quota low for user %s on printer %s") % (user.Name, printer.Name)
555            self.logger.log_message(adminmessage)
556            if mailto in [ "BOTH", "USER" ] :
557                if user.LimitBy and (user.LimitBy.lower() == "balance") : 
558                    message = self.config.getPoorWarn()
559                else :     
560                    message = self.config.getSoftWarn(printer.Name)
561                self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message)
562            if mailto in [ "BOTH", "ADMIN" ] :
563                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
564        return action       
Note: See TracBrowser for help on using the browser.