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
Line 
1#! /usr/bin/env python
2
3# PyKota - Print Quotas for CUPS and LPRng
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
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.
10#
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.
19#
20# $Id$
21#
22# $Log$
23# Revision 1.46  2003/07/09 20:17:07  jalet
24# Email field added to PostgreSQL schema
25#
26# Revision 1.45  2003/07/08 19:43:51  jalet
27# Configurable warning messages.
28# Poor man's treshold value added.
29#
30# Revision 1.44  2003/07/07 11:49:24  jalet
31# Lots of small fixes with the help of PyChecker
32#
33# Revision 1.43  2003/07/04 09:06:32  jalet
34# Small bug fix wrt undefined "LimitBy" field.
35#
36# Revision 1.42  2003/06/30 12:46:15  jalet
37# Extracted reporting code.
38#
39# Revision 1.41  2003/06/25 14:10:01  jalet
40# Hey, it may work (edpykota --reset excepted) !
41#
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#
48# Revision 1.39  2003/04/29 18:37:54  jalet
49# Pluggable accounting methods (actually doesn't support external scripts)
50#
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#
58# Revision 1.37  2003/04/24 08:08:27  jalet
59# Debug message forgotten
60#
61# Revision 1.36  2003/04/24 07:59:40  jalet
62# LPRng support now works !
63#
64# Revision 1.35  2003/04/23 22:13:57  jalet
65# Preliminary support for LPRng added BUT STILL UNTESTED.
66#
67# Revision 1.34  2003/04/17 09:26:21  jalet
68# repykota now reports account balances too.
69#
70# Revision 1.33  2003/04/16 12:35:49  jalet
71# Groups quota work now !
72#
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#
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#
83# Revision 1.30  2003/04/10 21:47:20  jalet
84# Job history added. Upgrade script neutralized for now !
85#
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#
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#
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#
101# Revision 1.26  2003/03/09 23:58:16  jalet
102# Comment
103#
104# Revision 1.25  2003/03/07 22:56:14  jalet
105# 0.99 is out with some bug fixes.
106#
107# Revision 1.24  2003/02/27 23:48:41  jalet
108# Correctly maps PyKota's log levels to syslog log levels
109#
110# Revision 1.23  2003/02/27 22:55:20  jalet
111# WARN log priority doesn't exist.
112#
113# Revision 1.22  2003/02/27 09:09:20  jalet
114# Added a method to match strings against wildcard patterns
115#
116# Revision 1.21  2003/02/17 23:01:56  jalet
117# Typos
118#
119# Revision 1.20  2003/02/17 22:55:01  jalet
120# More options can now be set per printer or globally :
121#
122#       admin
123#       adminmail
124#       gracedelay
125#       requester
126#
127# the printer option has priority when both are defined.
128#
129# Revision 1.19  2003/02/10 11:28:45  jalet
130# Localization
131#
132# Revision 1.18  2003/02/10 01:02:17  jalet
133# External requester is about to work, but I must sleep
134#
135# Revision 1.17  2003/02/09 13:05:43  jalet
136# Internationalization continues...
137#
138# Revision 1.16  2003/02/09 12:56:53  jalet
139# Internationalization begins...
140#
141# Revision 1.15  2003/02/08 22:09:52  jalet
142# Name check method moved here
143#
144# Revision 1.14  2003/02/07 10:42:45  jalet
145# Indentation problem
146#
147# Revision 1.13  2003/02/07 08:34:16  jalet
148# Test wrt date limit was wrong
149#
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#
154# Revision 1.11  2003/02/06 22:54:33  jalet
155# warnpykota should be ok
156#
157# Revision 1.10  2003/02/06 15:03:11  jalet
158# added a method to set the limit date
159#
160# Revision 1.9  2003/02/06 10:39:23  jalet
161# Preliminary edpykota work.
162#
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#
168# Revision 1.7  2003/02/06 00:00:45  jalet
169# Now includes the printer name in email messages
170#
171# Revision 1.6  2003/02/05 23:55:02  jalet
172# Cleaner email messages
173#
174# Revision 1.5  2003/02/05 23:45:09  jalet
175# Better DateTime manipulation wrt grace delay
176#
177# Revision 1.4  2003/02/05 23:26:22  jalet
178# Incorrect handling of grace delay
179#
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#
183# Revision 1.2  2003/02/05 22:10:29  jalet
184# Typos
185#
186# Revision 1.1  2003/02/05 21:28:17  jalet
187# Initial import into CVS
188#
189#
190#
191
192import sys
193import fnmatch
194import getopt
195import smtplib
196import gettext
197import locale
198
199from mx import DateTime
200
201from pykota import version, config, storage, logger
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."""
214    def __init__(self, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
215        """Initializes the command line tool."""
216        # locale stuff
217        try :
218            locale.setlocale(locale.LC_ALL, "")
219            gettext.install("pykota")
220        except (locale.Error, IOError) :
221            gettext.NullTranslations().install()
222   
223        # pykota specific stuff
224        self.documentation = doc
225        self.config = config.PyKotaConfig("/etc")
226        self.logger = logger.openLogger(self)
227        self.storage = storage.openConnection(self)
228        self.smtpserver = self.config.getSMTPServer()
229       
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       
240    def parseCommandline(self, argv, short, long, allownothing=0) :
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"
292            elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
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   
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       
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       
320    def sendMessage(self, adminmail, touser, fullmessage) :
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)
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")
330        server.quit()
331       
332    def sendMessageToUser(self, admin, adminmail, user, subject, message) :
333        """Sends an email message to a user."""
334        message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail)
335        self.sendMessage(adminmail, user.Email or user.Name, "Subject: %s\n\n%s" % (subject, message))
336       
337    def sendMessageToAdmin(self, adminmail, subject, message) :
338        """Sends an email message to the Print Quota administrator."""
339        self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message))
340       
341    def checkGroupPQuota(self, grouppquota) :   
342        """Checks the group quota on a printer and deny or accept the job."""
343        group = grouppquota.Group
344        printer = grouppquota.Printer
345        if group.LimitBy and (group.LimitBy.lower() == "balance") : 
346            if group.AccountBalance <= 0.0 :
347                action = "DENY"
348            elif group.AccountBalance <= self.config.getPoorMan() :   
349                action = "WARN"
350            else :   
351                action = "ALLOW"
352        else :
353            if grouppquota.SoftLimit is not None :
354                softlimit = int(grouppquota.SoftLimit)
355                if grouppquota.PageCounter < softlimit :
356                    action = "ALLOW"
357                else :   
358                    if grouppquota.HardLimit is None :
359                        # only a soft limit, this is equivalent to having only a hard limit
360                        action = "DENY"
361                    else :   
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 :   
373                                action = "DENY"
374                        else :         
375                            action = "DENY"
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 :
381                        action = "ALLOW"
382                    else :     
383                        action = "DENY"
384                else :
385                    # Both are unset, no quota, i.e. accounting only
386                    action = "ALLOW"
387        return action
388   
389    def checkUserPQuota(self, userpquota) :
390        """Checks the user quota on a printer and deny or accept the job."""
391        user = userpquota.User
392        printer = userpquota.Printer
393       
394        # first we check any group the user is a member of
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
401               
402        # then we check the user's own quota
403        policy = self.config.getPrinterPolicy(printer.Name)
404        if user.LimitBy and (user.LimitBy.lower() == "balance") : 
405            if user.AccountBalance is None :
406                if policy == "ALLOW" :
407                    action = "POLICY_ALLOW"
408                else :   
409                    action = "POLICY_DENY"
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))
411            else :   
412                val = float(user.AccountBalance or 0.0)
413                if val <= 0.0 :
414                    action = "DENY"
415                elif val <= self.config.getPoorMan() :   
416                    action = "WARN"
417                else :   
418                    action = "ALLOW"
419        else :
420            if not userpquota.Exists :
421                # Unknown userquota
422                if policy == "ALLOW" :
423                    action = "POLICY_ALLOW"
424                else :   
425                    action = "POLICY_DENY"
426                self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action))
427            else :   
428                pagecounter = int(userpquota.PageCounter or 0)
429                if userpquota.SoftLimit is not None :
430                    softlimit = int(userpquota.SoftLimit)
431                    if pagecounter < softlimit :
432                        action = "ALLOW"
433                    else :   
434                        if userpquota.HardLimit is None :
435                            # only a soft limit, this is equivalent to having only a hard limit
436                            action = "DENY"
437                        else :   
438                            hardlimit = int(userpquota.HardLimit)
439                            if softlimit <= pagecounter < hardlimit :   
440                                now = DateTime.now()
441                                if userpquota.DateLimit is not None :
442                                    datelimit = DateTime.ISO.ParseDateTime(userpquota.DateLimit)
443                                else :
444                                    datelimit = now + self.config.getGraceDelay(printer.Name)
445                                    userpquota.setDateLimit(datelimit)
446                                if now < datelimit :
447                                    action = "WARN"
448                                else :   
449                                    action = "DENY"
450                            else :         
451                                action = "DENY"
452                else :       
453                    if userpquota.HardLimit is not None :
454                        # no soft limit, only a hard one.
455                        hardlimit = int(userpquota.HardLimit)
456                        if pagecounter < hardlimit :
457                            action = "ALLOW"
458                        else :     
459                            action = "DENY"
460                    else :
461                        # Both are unset, no quota, i.e. accounting only
462                        action = "ALLOW"
463        return action
464   
465    def warnGroupPQuota(self, grouppquota) :
466        """Checks a group quota and send messages if quota is exceeded on current printer."""
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)
472        action = self.checkGroupPQuota(grouppquota)
473        if action.startswith("POLICY_") :
474            action = action[7:]
475        if action == "DENY" :
476            adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name)
477            self.logger.log_message(adminmessage)
478            if mailto in [ "BOTH", "ADMIN" ] :
479                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
480            for user in self.storage.getGroupMembers(group) :
481                if mailto in [ "BOTH", "USER" ] :
482                    self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name))
483        elif action == "WARN" :   
484            adminmessage = _("Print Quota soft limit exceeded for group %s on printer %s") % (group.Name, printer.Name)
485            self.logger.log_message(adminmessage)
486            if mailto in [ "BOTH", "ADMIN" ] :
487                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
488            if group.LimitBy and (group.LimitBy.lower() == "balance") : 
489                message = self.config.getPoorWarn()
490            else :     
491                message = self.config.getSoftWarn(printer.Name)
492            for user in self.storage.getGroupMembers(group) :
493                if mailto in [ "BOTH", "USER" ] :
494                    self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message)
495        return action       
496       
497    def warnUserPQuota(self, userpquota) :
498        """Checks a user quota and send him a message if quota is exceeded on current printer."""
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)
505        if action.startswith("POLICY_") :
506            action = action[7:]
507        if action == "DENY" :
508            adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name)
509            self.logger.log_message(adminmessage)
510            if mailto in [ "BOTH", "USER" ] :
511                self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name))
512            if mailto in [ "BOTH", "ADMIN" ] :
513                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
514        elif action == "WARN" :   
515            adminmessage = _("Print Quota soft limit exceeded for user %s on printer %s") % (user.Name, printer.Name)
516            self.logger.log_message(adminmessage)
517            if mailto in [ "BOTH", "USER" ] :
518                if user.LimitBy and (user.LimitBy.lower() == "balance") : 
519                    message = self.config.getPoorWarn()
520                else :     
521                    message = self.config.getSoftWarn(printer.Name)
522                self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message)
523            if mailto in [ "BOTH", "ADMIN" ] :
524                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
525        return action       
Note: See TracBrowser for help on using the browser.