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

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

Test wrt date limit was wrong

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