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

Revision 1091, 21.4 kB (checked in by jalet, 21 years ago)

Modified some messages aout soft limit

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