root / pykota / trunk / bin / warnpykota @ 3288

Revision 3288, 6.5 kB (checked in by jerome, 16 years ago)

Moved all exceptions definitions to a dedicated module.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: UTF-8 -*-
3#
4# PyKota : Print Quotas for CUPS
5#
6# (c) 2003, 2004, 2005, 2006, 2007, 2008 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 3 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, see <http://www.gnu.org/licenses/>.
19#
20# $Id$
21#
22#
23
24import sys
25import os
26import pwd
27
28from pykota.errors import PyKotaCommandLineError
29from pykota.tool import PyKotaTool, crashed, N_
30
31__doc__ = N_("""warnpykota v%(__version__)s (c) %(__years__)s %(__author__)s
32
33Sends mail to users over print quota.
34
35command line usage :
36
37  warnpykota  [options]  [names]
38
39options :
40
41  -v | --version       Prints warnpykota's version number then exits.
42  -h | --help          Prints this message then exits.
43 
44  -u | --users         Warns users over their print quota, this is the
45                       default.
46 
47  -g | --groups        Warns users whose groups quota are over limit.
48 
49  -P | --printer p     Verify quotas on this printer only. Actually p can
50                       use wildcards characters to select only
51                       some printers. The default value is *, meaning
52                       all printers.
53                       You can specify several names or wildcards,
54                       by separating them with commas.
55 
56examples :                             
57
58  $ warnpykota --printer lp
59 
60  This will warn all users of the lp printer who have exceeded their
61  print quota.
62
63  $ warnpykota
64 
65  This will warn all users  who have exceeded their print quota on
66  any printer.
67
68  $ warnpykota --groups --printer "laserjet*" "dev*"
69 
70  This will warn all users of groups which names begins with "dev" and
71  who have exceeded their print quota on any printer which name begins
72  with "laserjet"
73 
74  If launched by an user who is not a PyKota administrator, additionnal
75  arguments representing users or groups names are ignored, and only the
76  current user/group is reported.
77""")
78       
79class WarnPyKota(PyKotaTool) :       
80    """A class for warnpykota."""
81    def main(self, ugnames, options) :
82        """Warn users or groups over print quota."""
83        if self.config.isAdmin :
84            # PyKota administrator
85            if not ugnames :
86                # no username, means all usernames
87                ugnames = [ "*" ]
88        else :       
89            # not a PyKota administrator
90            # warns only the current user
91            # the utility of this is discutable, but at least it
92            # protects other users from mail bombing if they are
93            # over quota.
94            username = pwd.getpwuid(os.geteuid())[0]
95            if options["groups"] :
96                user = self.storage.getUser(username)
97                if user.Exists :
98                    ugnames = [ g.Name for g in self.storage.getUserGroups(user) ]
99                else :   
100                    ugnames = [ ]
101            else :
102                ugnames = [ username ]
103       
104        printers = self.storage.getMatchingPrinters(options["printer"])
105        if not printers :
106            raise PyKotaCommandLineError, _("There's no printer matching %s") % options["printer"]
107        alreadydone = {}
108        for printer in printers :
109            if options["groups"] :
110                for (group, grouppquota) in self.storage.getPrinterGroupsAndQuotas(printer, ugnames) :
111                    self.warnGroupPQuota(grouppquota)
112            else :
113                for (user, userpquota) in self.storage.getPrinterUsersAndQuotas(printer, ugnames) :
114                    # we only want to warn users who have ever printed something
115                    # and don't want to warn users who have never printed
116                    if ((user.AccountBalance > self.config.getBalanceZero()) and \
117                       (user.AccountBalance != user.LifeTimePaid)) or \
118                       userpquota.PageCounter or userpquota.LifePageCounter or \
119                       self.storage.getUserNbJobsFromHistory(user) :
120                        done = alreadydone.get(user.Name)
121                        if (user.LimitBy == 'quota') or not done :
122                            action = self.warnUserPQuota(userpquota)
123                            if not done :
124                                alreadydone[user.Name] = (action in ('WARN', 'DENY'))
125                     
126if __name__ == "__main__" : 
127    retcode = 0
128    try :
129        defaults = { \
130                     "printer" : "*", \
131                   }
132        short_options = "vhugP:"
133        long_options = ["help", "version", "users", "groups", "printer="]
134       
135        # Initializes the command line tool
136        sender = WarnPyKota(doc=__doc__)
137        sender.deferredInit()
138       
139        # parse and checks the command line
140        (options, args) = sender.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
141       
142        # sets long options
143        options["help"] = options["h"] or options["help"]
144        options["version"] = options["v"] or options["version"]
145        options["users"] = options["u"] or options["users"]
146        options["groups"] = options["g"] or options["groups"]
147        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
148       
149        if options["help"] :
150            sender.display_usage_and_quit()
151        elif options["version"] :
152            sender.display_version_and_quit()
153        elif options["users"] and options["groups"] :   
154            raise PyKotaCommandLineError, _("incompatible options, see help.")
155        else :
156            retcode = sender.main(args, options)
157    except KeyboardInterrupt :       
158        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
159        retcode = -3
160    except PyKotaCommandLineError, msg :   
161        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
162        retcode = -2
163    except SystemExit :       
164        pass
165    except :
166        try :
167            sender.crashed("warnpykota failed")
168        except :   
169            crashed("warnpykota failed")
170        retcode = -1
171       
172    try :
173        sender.storage.close()
174    except (TypeError, NameError, AttributeError) :   
175        pass
176       
177    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.