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

Revision 1079, 21.2 kB (checked in by jalet, 21 years ago)

Email field added to PostgreSQL schema

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