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

Revision 715, 9.3 kB (checked in by jalet, 21 years ago)

Preliminary edpykota work.

  • 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
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$
17# Revision 1.9  2003/02/06 10:39:23  jalet
18# Preliminary edpykota work.
19#
20# Revision 1.8  2003/02/06 09:19:02  jalet
21# More robust behavior (hopefully) when the user or printer is not managed
22# correctly by the Quota System : e.g. cupsFilter added in ppd file, but
23# printer and/or user not 'yet?' in storage.
24#
25# Revision 1.7  2003/02/06 00:00:45  jalet
26# Now includes the printer name in email messages
27#
28# Revision 1.6  2003/02/05 23:55:02  jalet
29# Cleaner email messages
30#
31# Revision 1.5  2003/02/05 23:45:09  jalet
32# Better DateTime manipulation wrt grace delay
33#
34# Revision 1.4  2003/02/05 23:26:22  jalet
35# Incorrect handling of grace delay
36#
37# Revision 1.3  2003/02/05 22:16:20  jalet
38# DEVICE_URI is undefined outside of CUPS, i.e. for normal command line tools
39#
40# Revision 1.2  2003/02/05 22:10:29  jalet
41# Typos
42#
43# Revision 1.1  2003/02/05 21:28:17  jalet
44# Initial import into CVS
45#
46#
47#
48
49import sys
50import os
51import getopt
52import smtplib
53
54from mx import DateTime
55
56from pykota import version, config, storage, logger
57
58class PyKotaToolError(Exception):
59    """An exception for PyKota config related stuff."""
60    def __init__(self, message = ""):
61        self.message = message
62        Exception.__init__(self, message)
63    def __repr__(self):
64        return self.message
65    __str__ = __repr__
66   
67class PyKotaTool :   
68    """Base class for all PyKota command line tools."""
69    def __init__(self, isfilter=0, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
70        """Initializes the command line tool."""
71        self.documentation = doc
72        self.config = config.PyKotaConfig(os.environ.get("CUPS_SERVERROOT", "/etc/cups"))
73        self.logger = logger.openLogger(self.config)
74        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
75        self.printername = os.environ.get("PRINTER", None)
76        self.smtpserver = self.config.getSMTPServer()
77        self.admin = self.config.getAdmin()
78        self.adminmail = self.config.getAdminMail()
79       
80    def display_version_and_quit(self) :
81        """Displays version number, then exists successfully."""
82        print version.__version__
83        sys.exit(0)
84   
85    def display_usage_and_quit(self) :
86        """Displays command line usage, then exists successfully."""
87        print self.documentation
88        sys.exit(0)
89       
90    def parseCommandline(self, argv, short, long) :
91        """Parses the command line, controlling options."""
92        # split options in two lists: those which need an argument, those which don't need any
93        withoutarg = []
94        witharg = []
95        lgs = len(short)
96        i = 0
97        while i < lgs :
98            ii = i + 1
99            if (ii < lgs) and (short[ii] == ':') :
100                # needs an argument
101                witharg.append(short[i])
102                ii = ii + 1 # skip the ':'
103            else :
104                # doesn't need an argument
105                withoutarg.append(short[i])
106            i = ii
107               
108        for option in long :
109            if option[-1] == '=' :
110                # needs an argument
111                witharg.append(option[:-1])
112            else :
113                # doesn't need an argument
114                withoutarg.append(option)
115       
116        # we begin with all possible options unset
117        parsed = {}
118        for option in withoutarg + witharg :
119            parsed[option] = None
120       
121        # then we parse the command line
122        args = []       # to not break if something unexpected happened
123        try :
124            options, args = getopt.getopt(argv, short, long)
125            if options :
126                for (o, v) in options :
127                    # we skip the '-' chars
128                    lgo = len(o)
129                    i = 0
130                    while (i < lgo) and (o[i] == '-') :
131                        i = i + 1
132                    o = o[i:]
133                    if o in witharg :
134                        # needs an argument : set it
135                        parsed[o] = v
136                    elif o in withoutarg :
137                        # doesn't need an argument : boolean
138                        parsed[o] = 1
139                    else :
140                        # should never occur
141                        raise PyKotaToolError, "Unexpected problem when parsing command line"
142            elif (not args) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty
143                self.display_usage_and_quit()
144        except getopt.error, msg :
145            sys.stderr.write("%s\n" % msg)
146            sys.stderr.flush()
147            self.display_usage_and_quit()
148        return (parsed, args)
149   
150    def sendMessage(self, touser, fullmessage) :
151        """Sends an email message containing headers to some user."""
152        if "@" not in touser :
153            touser = "%s@%s" % (touser, self.smtpserver)
154        server = smtplib.SMTP(self.smtpserver)
155        server.sendmail(self.adminmail, [touser], fullmessage)
156        server.quit()
157       
158    def sendMessageToUser(self, username, subject, message) :
159        """Sends an email message to a user."""
160        message += "\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n" % (self.admin, self.adminmail)
161        self.sendMessage(username, "Subject: %s\n\n%s" % (subject, message))
162       
163    def sendMessageToAdmin(self, subject, message) :
164        """Sends an email message to the Print Quota administrator."""
165        self.sendMessage(self.adminmail, "Subject: %s\n\n%s" % (subject, message))
166       
167    def checkUserPQuota(self, username, printername) :
168        """Checks the user quota on a printer and deny or accept the job."""
169        now = DateTime.now()
170        quota = self.storage.getUserPQuota(username, printername)
171        if quota is None :
172            # Unknown user or printer or combination
173            policy = self.config.getPrinterPolicy(printername)
174            if policy in [None, "ALLOW"] :
175                action = "ALLOW"
176            else :   
177                action = "DENY"
178            self.logger.log_message("Unable to match user %s on printer %s, applying default policy (%s)" % (username, printername, action), "warn")
179            return (action, None, None)
180        else :   
181            pagecounter = quota["pagecounter"]
182            softlimit = quota["softlimit"]
183            hardlimit = quota["hardlimit"]
184            datelimit = quota["datelimit"]
185            if datelimit is not None :
186                datelimit = DateTime.ISO.ParseDateTime(datelimit)
187            if softlimit is not None :
188                if pagecounter < softlimit :
189                    action = "ALLOW"
190                elif hardlimit is not None :
191                     gracedelay = self.config.getGraceDelay()
192                     if softlimit <= pagecounter < hardlimit :   
193                         if datelimit is None :
194                             datelimit = now + gracedelay
195                             self.storage.doQuery("UPDATE userpquota SET datelimit=%s::DATETIME WHERE userid=%s AND printerid=%s;" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(self.getUserId(username)), self.doQuote(self.getPrinterId(printername))))
196                         if (now + gracedelay) < datelimit :
197                             action = "WARN"
198                         else :   
199                             action = "DENY"
200                     else :         
201                         action = "DENY"
202                else :       
203                    action = "DENY"
204            else :       
205                action = "ALLOW"
206            return (action, (hardlimit - pagecounter), datelimit)
207   
208    def warnQuotaPrinter(self, username) :
209        """Checks a user quota and send him a message if quota is exceeded on current printer."""
210        (action, grace, gracedate) = self.checkUserPQuota(username, self.printername)
211        if action == "DENY" :
212            if (grace is not None) and (gracedate is not None) :
213                # only when both user and printer are known
214                adminmessage = "Print Quota exceeded for user %s on printer %s" % (username, self.printername)
215                self.logger.log_message(adminmessage)
216                self.sendMessageToUser(username, "Print Quota Exceeded", "You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s." % self.printername)
217                self.sendMessageToAdmin("Print Quota", adminmessage)
218        elif action == "WARN" :   
219            adminmessage = "Print Quota soft limit exceeded for user %s on printer %s" % (username, self.printername)
220            self.logger.log_message(adminmessage)
221            self.sendMessageToUser(username, "Print Quota Exceeded", "You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s." % self.printername)
222            self.sendMessageToAdmin("Print Quota", adminmessage)
223        return action       
224   
Note: See TracBrowser for help on using the browser.