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

Revision 824, 11.8 kB (checked in by jalet, 21 years ago)

WARN log priority doesn't exist.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[695]1#! /usr/bin/env python
2
3# PyKota - Print Quotas for CUPS
4#
5# (c) 2003 Jerome Alet <alet@librelogiciel.com>
6# You're welcome to redistribute this software under the
7# terms of the GNU General Public Licence version 2.0
8# or, at your option, any higher version.
9#
10# You can read the complete GNU GPL in the file COPYING
11# which should come along with this software, or visit
12# the Free Software Foundation's WEB site http://www.fsf.org
13#
14# $Id$
15#
16# $Log$
[824]17# Revision 1.23  2003/02/27 22:55:20  jalet
18# WARN log priority doesn't exist.
19#
[817]20# Revision 1.22  2003/02/27 09:09:20  jalet
21# Added a method to match strings against wildcard patterns
22#
[804]23# Revision 1.21  2003/02/17 23:01:56  jalet
24# Typos
25#
[802]26# Revision 1.20  2003/02/17 22:55:01  jalet
27# More options can now be set per printer or globally :
28#
[804]29#       admin
30#       adminmail
31#       gracedelay
32#       requester
[802]33#
34# the printer option has priority when both are defined.
35#
[788]36# Revision 1.19  2003/02/10 11:28:45  jalet
37# Localization
38#
[782]39# Revision 1.18  2003/02/10 01:02:17  jalet
40# External requester is about to work, but I must sleep
41#
[773]42# Revision 1.17  2003/02/09 13:05:43  jalet
43# Internationalization continues...
44#
[772]45# Revision 1.16  2003/02/09 12:56:53  jalet
46# Internationalization begins...
47#
[764]48# Revision 1.15  2003/02/08 22:09:52  jalet
49# Name check method moved here
50#
[742]51# Revision 1.14  2003/02/07 10:42:45  jalet
52# Indentation problem
53#
[733]54# Revision 1.13  2003/02/07 08:34:16  jalet
55# Test wrt date limit was wrong
56#
[729]57# Revision 1.12  2003/02/06 23:20:02  jalet
58# warnpykota doesn't need any user/group name argument, mimicing the
59# warnquota disk quota tool.
60#
[728]61# Revision 1.11  2003/02/06 22:54:33  jalet
62# warnpykota should be ok
63#
[722]64# Revision 1.10  2003/02/06 15:03:11  jalet
65# added a method to set the limit date
66#
[715]67# Revision 1.9  2003/02/06 10:39:23  jalet
68# Preliminary edpykota work.
69#
[713]70# Revision 1.8  2003/02/06 09:19:02  jalet
71# More robust behavior (hopefully) when the user or printer is not managed
72# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
73# printer and/or user not 'yet?' in storage.
74#
[712]75# Revision 1.7  2003/02/06 00:00:45  jalet
76# Now includes the printer name in email messages
77#
[711]78# Revision 1.6  2003/02/05 23:55:02  jalet
79# Cleaner email messages
80#
[709]81# Revision 1.5  2003/02/05 23:45:09  jalet
82# Better DateTime manipulation wrt grace delay
83#
[708]84# Revision 1.4  2003/02/05 23:26:22  jalet
85# Incorrect handling of grace delay
86#
[699]87# Revision 1.3  2003/02/05 22:16:20  jalet
88# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
89#
[698]90# Revision 1.2  2003/02/05 22:10:29  jalet
91# Typos
92#
[695]93# Revision 1.1  2003/02/05 21:28:17  jalet
94# Initial import into CVS
95#
96#
97#
98
99import sys
100import os
[817]101import fnmatch
[715]102import getopt
[695]103import smtplib
[772]104import gettext
[782]105import locale
[695]106
[708]107from mx import DateTime
108
[715]109from pykota import version, config, storage, logger
[695]110
111class PyKotaToolError(Exception):
112    """An exception for PyKota config related stuff."""
113    def __init__(self, message = ""):
114        self.message = message
115        Exception.__init__(self, message)
116    def __repr__(self):
117        return self.message
118    __str__ = __repr__
119   
120class PyKotaTool :   
121    """Base class for all PyKota command line tools."""
[715]122    def __init__(self, isfilter=0, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
[695]123        """Initializes the command line tool."""
[772]124        # locale stuff
[788]125        try :
[782]126            locale.setlocale(locale.LC_ALL, "")
[788]127            gettext.install("pykota")
128        except (locale.Error, IOError) :
129            gettext.NullTranslations().install()
[772]130   
131        # pykota specific stuff
[715]132        self.documentation = doc
[695]133        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
[698]134        self.logger = logger.openLogger(self.config)
[695]135        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
136        self.printername = os.environ.get("PRINTER", None)
137        self.smtpserver = self.config.getSMTPServer()
138       
[715]139    def display_version_and_quit(self) :
140        """Displays version number, then exists successfully."""
141        print version.__version__
142        sys.exit(0)
143   
144    def display_usage_and_quit(self) :
145        """Displays command line usage, then exists successfully."""
146        print self.documentation
147        sys.exit(0)
148       
[729]149    def parseCommandline(self, argv, short, long, allownothing=0) :
[715]150        """Parses the command line, controlling options."""
151        # split options in two lists: those which need an argument, those which don't need any
152        withoutarg = []
153        witharg = []
154        lgs = len(short)
155        i = 0
156        while i < lgs :
157            ii = i + 1
158            if (ii < lgs) and (short[ii] == ':') :
159                # needs an argument
160                witharg.append(short[i])
161                ii = ii + 1 # skip the ':'
162            else :
163                # doesn't need an argument
164                withoutarg.append(short[i])
165            i = ii
166               
167        for option in long :
168            if option[-1] == '=' :
169                # needs an argument
170                witharg.append(option[:-1])
171            else :
172                # doesn't need an argument
173                withoutarg.append(option)
174       
175        # we begin with all possible options unset
176        parsed = {}
177        for option in withoutarg + witharg :
178            parsed[option] = None
179       
180        # then we parse the command line
181        args = []       # to not break if something unexpected happened
182        try :
183            options, args = getopt.getopt(argv, short, long)
184            if options :
185                for (o, v) in options :
186                    # we skip the '-' chars
187                    lgo = len(o)
188                    i = 0
189                    while (i < lgo) and (o[i] == '-') :
190                        i = i + 1
191                    o = o[i:]
192                    if o in witharg :
193                        # needs an argument : set it
194                        parsed[o] = v
195                    elif o in withoutarg :
196                        # doesn't need an argument : boolean
197                        parsed[o] = 1
198                    else :
199                        # should never occur
200                        raise PyKotaToolError, "Unexpected problem when parsing command line"
[729]201            elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
[715]202                self.display_usage_and_quit()
203        except getopt.error, msg :
204            sys.stderr.write("%s\n" % msg)
205            sys.stderr.flush()
206            self.display_usage_and_quit()
207        return (parsed, args)
208   
[764]209    def isValidName(self, name) :
210        """Checks if a user or printer name is valid."""
211        # unfortunately Python 2.1 string modules doesn't define ascii_letters...
212        asciiletters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
213        digits = '0123456789'
214        if name[0] in asciiletters :
215            validchars = asciiletters + digits + "-_"
216            for c in name[1:] :
217                if c not in validchars :
218                    return 0
219            return 1       
220        return 0
221       
[817]222    def matchString(self, s, patterns) :
223        """Returns 1 if the string s matches one of the patterns, else 0."""
224        for pattern in patterns :
225            if fnmatch.fnmatchcase(s, pattern) :
226                return 1
227        return 0
228       
[802]229    def sendMessage(self, adminmail, touser, fullmessage) :
[695]230        """Sends an email message containing headers to some user."""
231        if "@" not in touser :
232            touser = "%s@%s" % (touser, self.smtpserver)
233        server = smtplib.SMTP(self.smtpserver)
[802]234        server.sendmail(adminmail, [touser], fullmessage)
[695]235        server.quit()
236       
[802]237    def sendMessageToUser(self, admin, adminmail, username, subject, message) :
[695]238        """Sends an email message to a user."""
[802]239        message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail)
240        self.sendMessage(adminmail, username, "Subject: %s\n\n%s" % (subject, message))
[695]241       
[802]242    def sendMessageToAdmin(self, adminmail, subject, message) :
[695]243        """Sends an email message to the Print Quota administrator."""
[802]244        self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message))
[695]245       
[708]246    def checkUserPQuota(self, username, printername) :
247        """Checks the user quota on a printer and deny or accept the job."""
248        quota = self.storage.getUserPQuota(username, printername)
[713]249        if quota is None :
250            # Unknown user or printer or combination
251            policy = self.config.getPrinterPolicy(printername)
252            if policy in [None, "ALLOW"] :
[708]253                action = "ALLOW"
[713]254            else :   
255                action = "DENY"
[824]256            self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (username, printername, action), "info")
[713]257            return (action, None, None)
258        else :   
259            pagecounter = quota["pagecounter"]
260            softlimit = quota["softlimit"]
261            hardlimit = quota["hardlimit"]
262            datelimit = quota["datelimit"]
263            if datelimit is not None :
264                datelimit = DateTime.ISO.ParseDateTime(datelimit)
265            if softlimit is not None :
266                if pagecounter < softlimit :
267                    action = "ALLOW"
268                elif hardlimit is not None :
[742]269                    if softlimit <= pagecounter < hardlimit :   
270                        now = DateTime.now()
271                        if datelimit is None :
[804]272                            datelimit = now + self.config.getGraceDelay(printername)
[742]273                            self.storage.setDateLimit(username, printername, datelimit)
274                        if now < datelimit :
275                            action = "WARN"
276                        else :   
277                            action = "DENY"
278                    else :         
279                        action = "DENY"
[713]280                else :       
281                    action = "DENY"
[708]282            else :       
[713]283                action = "ALLOW"
284            return (action, (hardlimit - pagecounter), datelimit)
[708]285   
[728]286    def warnGroupPQuota(self, username, printername=None) :
[695]287        """Checks a user quota and send him a message if quota is exceeded on current printer."""
[728]288        pname = printername or self.printername
[773]289        raise PyKotaToolError, _("Group quotas are currently not implemented.")
[728]290       
291    def warnUserPQuota(self, username, printername=None) :
292        """Checks a user quota and send him a message if quota is exceeded on current printer."""
293        pname = printername or self.printername
[802]294        admin = self.config.getAdmin(pname)
295        adminmail = self.config.getAdminMail(pname)
[728]296        (action, grace, gracedate) = self.checkUserPQuota(username, pname)
[695]297        if action == "DENY" :
[713]298            if (grace is not None) and (gracedate is not None) :
299                # only when both user and printer are known
[773]300                adminmessage = _("Print Quota exceeded for user %s on printer %s") % (username, pname)
[713]301                self.logger.log_message(adminmessage)
[802]302                self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % pname)
303                self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
[695]304        elif action == "WARN" :   
[773]305            adminmessage = _("Print Quota soft limit exceeded for user %s on printer %s") % (username, pname)
[695]306            self.logger.log_message(adminmessage)
[802]307            self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % pname)
308            self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
[695]309        return action       
310   
Note: See TracBrowser for help on using the browser.