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

Revision 728, 9.5 kB (checked in by jalet, 21 years ago)

warnpykota should be ok

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