root / pykota / trunk / bin / repykota @ 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 mx import DateTime
29
30from pykota.errors import PyKotaToolError, PyKotaCommandLineError
31from pykota.tool import PyKotaTool, crashed, N_
32from pykota import reporter
33
34__doc__ = N_("""repykota v%(__version__)s (c) %(__years__)s %(__author__)s
35
36Generates print quota reports.
37
38command line usage :
39
40  repykota [options]
41
42options :
43
44  -v | --version       Prints repykota's version number then exits.
45  -h | --help          Prints this message then exits.
46 
47  -u | --users         Generates a report on users quota, this is
48                       the default.
49 
50  -g | --groups        Generates a report on group quota instead of users.
51 
52  -i | --ingroups g1[,g2...]  Only lists users who are members of these
53                              groups. Reserved to PyKota Administrators.
54 
55  -P | --printer p     Report quotas on this printer only. Actually p can
56                       use wildcards characters to select only
57                       some printers. The default value is *, meaning
58                       all printers.
59                       You can specify several names or wildcards,
60                       by separating them with commas.
61 
62examples :                             
63
64  $ repykota --printer lp
65 
66  This will print the quota status for all users who use the lp printer.
67
68  $ repykota
69 
70  This will print the quota status for all users on all printers.
71 
72  $ repykota --printer "laser*,*pson" jerome "jo*"
73 
74  This will print the quota status for user jerome and all users
75  whose name begins with "jo" on all printers which name begins
76  with "laser" or ends with "pson".
77 
78  If launched by an user who is not a PyKota administrator, additionnal
79  arguments representing users or groups names are ignored, and only the
80  current user/group is reported.
81""")
82       
83class RePyKota(PyKotaTool) :       
84    """A class for repykota."""
85    def main(self, ugnames, options) :
86        """Print Quota reports generator."""
87        if self.config.isAdmin :
88            # PyKota administrator
89            if not ugnames :
90                # no username, means all usernames
91                ugnames = [ "*" ]
92               
93            if options["ingroups"] :
94                groupsnames = options["ingroups"].split(",")
95                groups = [self.storage.getGroup(gname) for gname in groupsnames]
96                members = {}
97                for group in groups :
98                    if not group.Exists :
99                        self.printInfo("Group %s doesn't exist." % group.Name, "warn")
100                    else :   
101                        for user in self.storage.getGroupMembers(group) :
102                            members[user.Name] = user
103                ugnames = [ m for m in members.keys() if self.matchString(m, ugnames) ]
104        else :       
105            # reports only the current user
106            if options["ingroups"] :
107                raise PyKotaCommandLineError, _("Option --ingroups is reserved to PyKota Administrators.")
108               
109            username = pwd.getpwuid(os.geteuid())[0]
110            if options["groups"] :
111                user = self.storage.getUser(username)
112                if user.Exists :
113                    ugnames = [ g.Name for g in self.storage.getUserGroups(user) ]
114                else :   
115                    ugnames = [ ]
116            else :
117                ugnames = [ username ]
118       
119        printers = self.storage.getMatchingPrinters(options["printer"])
120        if not printers :
121            raise PyKotaCommandLineError, _("There's no printer matching %s") % options["printer"]
122           
123        self.reportingtool = reporter.openReporter(self, "text", printers, ugnames, (options["groups"] and 1) or 0)   
124        print self.reportingtool.generateReport()
125                   
126if __name__ == "__main__" : 
127    retcode = 0
128    try :
129        defaults = { \
130                     "printer" : "*", \
131                   }
132        short_options = "vhugi:P:"
133        long_options = ["help", "version", "users", "groups", "ingroups=", "printer="]
134       
135        # Initializes the command line tool
136        reportTool = RePyKota(doc=__doc__)
137        reportTool.deferredInit()
138       
139        # parse and checks the command line
140        (options, args) = reportTool.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        options["ingroups"] = options["i"] or options["ingroups"]
149       
150        if options["help"] :
151            reportTool.display_usage_and_quit()
152        elif options["version"] :
153            reportTool.display_version_and_quit()
154        elif (options["users"] or options["ingroups"]) and options["groups"] :
155            raise PyKotaCommandLineError, _("incompatible options, see help.")
156        else :
157            retcode = reportTool.main(args, options)
158    except KeyboardInterrupt :       
159        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
160        retcode = -3
161    except PyKotaCommandLineError, msg :   
162        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
163        retcode = -2
164    except SystemExit :       
165        pass
166    except :
167        try :
168            reportTool.crashed("repykota failed")
169        except :   
170            crashed("repykota failed")
171        retcode = -1
172
173    try :
174        reportTool.storage.close()
175    except (TypeError, NameError, AttributeError) :   
176        pass
177       
178    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.