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
RevLine 
[973]1# PyKota
[1144]2# -*- coding: ISO-8859-15 -*-
[973]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$
[1200]24# Revision 1.8  2003/11/21 14:28:46  jalet
25# More complete job history.
26#
[1180]27# Revision 1.7  2003/11/12 23:29:24  jalet
28# More work on new backend. This commit may be unstable.
29#
[1144]30# Revision 1.6  2003/10/07 09:07:29  jalet
31# Character encoding added to please latest version of Python
32#
[1068]33# Revision 1.5  2003/07/07 11:49:24  jalet
34# Lots of small fixes with the help of PyChecker
35#
[1041]36# Revision 1.4  2003/06/25 14:10:01  jalet
37# Hey, it may work (edpykota --reset excepted) !
38#
[988]39# Revision 1.3  2003/05/06 14:55:47  jalet
40# Missing import !
41#
[976]42# Revision 1.2  2003/04/30 13:36:40  jalet
43# Stupid accounting method was added.
44#
[973]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
[976]51import sys
[1180]52import os
[988]53import time
[973]54from pykota.accounter import AccounterBase, PyKotaAccounterError
55from pykota.requester import openRequester, PyKotaRequesterError
56
[1041]57MAXTRIES = 12    # maximum number of tries to get the printer's internal page counter
[973]58TIMETOSLEEP = 10 # number of seconds to sleep between two tries to get the printer's internal page counter
59
60class Accounter(AccounterBase) :
[1180]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."""
[973]68        global MAXTRIES, TIMETOSLEEP
69        for i in range(MAXTRIES) :
70            try :
[1180]71                counter = self.requester.getPrinterPageCounter(self.filter.printerhostname)
[973]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")
[1180]76                counter = None
[973]77            else :   
78                # printer answered, it is on so we can exit the loop
79                break
80            time.sleep(TIMETOSLEEP)   
[1180]81        return counter   
[973]82       
[1180]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       
[973]123        # get last job information for this printer
[1041]124        if not printer.LastJob.Exists :
[973]125            # The printer hasn't been used yet, from PyKota's point of view
[1041]126            lastuser = user
[973]127            lastpagecounter = counterbeforejob
128        else :   
129            # get last values from Quota Storage
[1041]130            lastuser = printer.LastJob.User
131            lastpagecounter = printer.LastJob.PrinterPageCounter
[973]132           
133        # if printer is off then we assume the correct counter value is the last one
[1180]134        if counterbeforejob is None :
[973]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
[1041]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")
[973]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
[1041]167        lastuserquota = self.filter.storage.getUserPQuota(lastuser, printer)
168        if lastuserquota.Exists :
169            lastuserquota.increasePagesUsage(jobsize)
[973]170       
171        # update the last job size in the history
[1041]172        if printer.LastJob.Exists :
173            printer.LastJob.setSize(jobsize)
[973]174       
175        # warns the last user if he is over quota
[1041]176        if lastuserquota.Exists :
177            self.filter.warnUserPQuota(lastuserquota)
[973]178           
179        # Is the current user allowed to print at all ?
[1041]180        action = self.filter.warnUserPQuota(self.filter.storage.getUserPQuota(user, printer))
[973]181       
182        # adds the current job to history   
[1200]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)
[973]184           
185        return action
[976]186           
Note: See TracBrowser for help on using the browser.