root / pykota / trunk / pykota / accounters / querying.py @ 1200

Revision 1200, 8.1 kB (checked in by jalet, 21 years ago)

More complete job history.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota - Print Quotas for CUPS and LPRng
5#
6# (c) 2003 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.8  2003/11/21 14:28:46  jalet
25# More complete job history.
26#
27# Revision 1.7  2003/11/12 23:29:24  jalet
28# More work on new backend. This commit may be unstable.
29#
30# Revision 1.6  2003/10/07 09:07:29  jalet
31# Character encoding added to please latest version of Python
32#
33# Revision 1.5  2003/07/07 11:49:24  jalet
34# Lots of small fixes with the help of PyChecker
35#
36# Revision 1.4  2003/06/25 14:10:01  jalet
37# Hey, it may work (edpykota --reset excepted) !
38#
39# Revision 1.3  2003/05/06 14:55:47  jalet
40# Missing import !
41#
42# Revision 1.2  2003/04/30 13:36:40  jalet
43# Stupid accounting method was added.
44#
45# Revision 1.1  2003/04/29 18:37:54  jalet
46# Pluggable accounting methods (actually doesn't support external scripts)
47#
48#
49#
50
51import sys
52import os
53import time
54from pykota.accounter import AccounterBase, PyKotaAccounterError
55from pykota.requester import openRequester, PyKotaRequesterError
56
57MAXTRIES = 12    # maximum number of tries to get the printer's internal page counter
58TIMETOSLEEP = 10 # number of seconds to sleep between two tries to get the printer's internal page counter
59
60class Accounter(AccounterBase) :
61    def __init__(self, kotabackend, arguments) :
62        """Initializes querying accounter."""
63        AccounterBase.__init__(self, kotabackend, arguments)
64        self.requester = openRequester(kotabackend.config, kotabackend.printername)
65       
66    def getPrinterInternalPageCounter(self) :   
67        """Returns the printer's internal page counter."""
68        global MAXTRIES, TIMETOSLEEP
69        for i in range(MAXTRIES) :
70            try :
71                counter = self.requester.getPrinterPageCounter(self.filter.printerhostname)
72            except PyKotaRequesterError, msg :
73                # can't get actual page counter, assume printer is off or warming up
74                # log the message anyway.
75                self.filter.logger.log_message("%s" % msg, "warn")
76                counter = None
77            else :   
78                # printer answered, it is on so we can exit the loop
79                break
80            time.sleep(TIMETOSLEEP)   
81        return counter   
82       
83    def beginJob(self, printer, user) :   
84        """Saves printer internal page counter at start of job."""
85        # save page counter before job
86        self.LastPageCounter = self.counterbefore = self.getPrinterInternalPageCounter()
87       
88    def endJob(self, printer, user) :   
89        """Saves printer internal page counter at end of job."""
90        # save page counter after job
91        self.LastPageCounter = self.counterafter = self.getPrinterInternalPageCounter()
92       
93    def getJobSize(self) :   
94        """Returns the actual job size."""
95        try :
96            jobsize = (self.counterafter - self.counterbefore)   
97            if jobsize < 0 :
98                # Try to take care of HP printers
99                # Their internal page counter is saved to NVRAM
100                # only every 10 pages. If the printer was switched
101                # off then back on during the job, and that the
102                # counters difference is negative, we know
103                # the formula (we can't know if more than eleven
104                # pages were printed though) :
105                if jobsize > -10 :
106                    jobsize += 10
107                else :   
108                    # here we may have got a printer being replaced
109                    # DURING the job. This is HIGHLY improbable !
110                    jobsize = 0
111        except :   
112            # takes care of the case where one counter (or both) was never set.
113            jobsize = 0
114        return jobsize
115       
116    def doAccounting(self, printer, user) :
117        """Does print accounting and returns if the job status is ALLOW or DENY."""
118        # Get the page counter directly from the printer itself
119        # Tries MAXTRIES times, sleeping two seconds each time, in case the printer is sleeping.
120        # This was seen with my Apple LaserWriter 16/600 PS which doesn't answer before having warmed up.
121        counterbeforejob = self.getPrinterInternalPageCounter()
122       
123        # get last job information for this printer
124        if not printer.LastJob.Exists :
125            # The printer hasn't been used yet, from PyKota's point of view
126            lastuser = user
127            lastpagecounter = counterbeforejob
128        else :   
129            # get last values from Quota Storage
130            lastuser = printer.LastJob.User
131            lastpagecounter = printer.LastJob.PrinterPageCounter
132           
133        # if printer is off then we assume the correct counter value is the last one
134        if counterbeforejob is None :
135            counterbeforejob = lastpagecounter
136           
137        # if the internal lifetime page counter for this printer is 0   
138        # then this may be a printer with a volatile counter (never
139        # saved to NVRAM) which has just been switched off and then on
140        # so we use the last page counter from the Quota Storage instead
141        # explanation at : http://web.mit.edu/source/third/lprng/doc/LPRng-HOWTO-15.html
142        if counterbeforejob == 0 :
143            counterbeforejob = lastpagecounter
144           
145        # Computes the last job size as the difference between internal page
146        # counter in the printer and last page counter taken from the Quota
147        # Storage database for this particular printer
148        try :
149            jobsize = (counterbeforejob - lastpagecounter)   
150        except TypeError :   
151            # never used, and internal page counter not accessible
152            jobsize = 0
153           
154        if jobsize < 0 :
155            # Probably an HP printer which was switched off and back on,
156            # its primary counter is only saved in a 10 increment, so
157            # it may be lower than the last page counter saved in the
158            # Quota Storage.
159            # We unconditionnally set the last job's size to
160            # abs(int((10 - abs(lastcounter(snmp) - lastcounter(storage)) / 2))
161            # For more accurate accounting, don't switch off your HP printers !
162            # explanation at : http://web.mit.edu/source/third/lprng/doc/LPRng-HOWTO-15.html
163            self.filter.logger.log_message(_("Error in page count value %i for user %s on printer %s") % (jobsize, lastuser.Name, self.filter.printername), "error")
164            jobsize = abs(int((10 - abs(jobsize)) / 2))     # Workaround for HP printers' feature !
165           
166        # update the quota for the previous user on this printer
167        lastuserquota = self.filter.storage.getUserPQuota(lastuser, printer)
168        if lastuserquota.Exists :
169            lastuserquota.increasePagesUsage(jobsize)
170       
171        # update the last job size in the history
172        if printer.LastJob.Exists :
173            printer.LastJob.setSize(jobsize)
174       
175        # warns the last user if he is over quota
176        if lastuserquota.Exists :
177            self.filter.warnUserPQuota(lastuserquota)
178           
179        # Is the current user allowed to print at all ?
180        action = self.filter.warnUserPQuota(self.filter.storage.getUserPQuota(user, printer))
181       
182        # adds the current job to history   
183        printer.addJobToHistory(self.filter.jobid, user, counterbeforejob, action, filename=self.filter.preserveinputfile, title=self.filter.title, copies=self.filter.copies, options=self.filter.options)
184           
185        return action
186           
Note: See TracBrowser for help on using the browser.