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

Revision 1113, 21.7 kB (checked in by jalet, 21 years ago)

1.14 is out !

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