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

Revision 729, 9.7 kB (checked in by jalet, 21 years ago)

warnpykota doesn't need any user/group name argument, mimicing the
warnquota disk quota tool.

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