root / pykota / trunk / bin / edpykota @ 890

Revision 890, 15.7 kB (checked in by jalet, 21 years ago)

Checks --groups option presence instead of --users because --users is the default.

  • 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
3# PyKota Print Quota Editor
4#
5# PyKota - Print Quotas for CUPS
6#
7# (c) 2003 Jerome Alet <alet@librelogiciel.com>
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
21#
22# $Id$
23#
24# $Log$
25# Revision 1.30  2003/04/08 21:10:18  jalet
26# Checks --groups option presence instead of --users because --users is the default.
27#
28# Revision 1.29  2003/04/05 09:28:56  jalet
29# Unnecessary message was logged
30#
31# Revision 1.28  2003/03/29 13:45:26  jalet
32# GPL paragraphs were incorrectly (from memory) copied into the sources.
33# Two README files were added.
34# Upgrade script for PostgreSQL pre 1.01 schema was added.
35#
36# Revision 1.27  2003/03/10 00:23:04  jalet
37# Bad english
38#
39# Revision 1.26  2003/03/10 00:11:27  jalet
40# Cleaner example.
41#
42# Revision 1.25  2003/03/09 23:56:21  jalet
43# Option noquota added to do accounting only.
44#
45# Revision 1.24  2003/02/27 23:48:41  jalet
46# Correctly maps PyKota's log levels to syslog log levels
47#
48# Revision 1.23  2003/02/27 22:55:20  jalet
49# WARN log priority doesn't exist.
50#
51# Revision 1.22  2003/02/27 09:37:02  jalet
52# Wildcards seem to work now
53#
54# Revision 1.21  2003/02/27 09:04:46  jalet
55# user and group names can be passed as wildcards if the --add option
56# is not set. The default is to act on all users or groups.
57#
58# Revision 1.20  2003/02/10 12:07:30  jalet
59# Now repykota should output the recorded total page number for each printer too.
60#
61# Revision 1.19  2003/02/09 13:40:29  jalet
62# typo
63#
64# Revision 1.18  2003/02/09 12:56:53  jalet
65# Internationalization begins...
66#
67# Revision 1.17  2003/02/08 22:47:23  jalet
68# Option --reset can now be used without having to use soft and hard limits
69# on the command line.
70#
71# Revision 1.16  2003/02/08 22:39:46  jalet
72# --reset command line option added
73#
74# Revision 1.15  2003/02/08 22:20:01  jalet
75# Clarification on why we don't check with /etc/passwd to see if the user
76# name is valid or not.
77#
78# Revision 1.14  2003/02/08 22:18:15  jalet
79# Now checks user and group names for validity before adding them
80#
81# Revision 1.13  2003/02/08 22:09:02  jalet
82# Only printer was added the first time.
83#
84# Revision 1.12  2003/02/08 21:44:49  jalet
85# Python 2.1 string module doesn't define ascii_letters
86#
87# Revision 1.11  2003/02/08 09:42:44  jalet
88# Better handle wrong or bad command line arguments
89#
90# Revision 1.10  2003/02/08 09:39:20  jalet
91# typos
92#
93# Revision 1.9  2003/02/08 09:38:06  jalet
94# Badly placed test
95#
96# Revision 1.8  2003/02/07 22:53:57  jalet
97# Checks if printer name is valid before adding it
98#
99# Revision 1.7  2003/02/07 22:17:58  jalet
100# Incomplete test
101#
102# Revision 1.6  2003/02/07 22:13:13  jalet
103# Perhaps edpykota is now able to add printers !!! Oh, stupid me !
104#
105# Revision 1.5  2003/02/06 14:49:04  jalet
106# edpykota should be ok now
107#
108# Revision 1.4  2003/02/06 14:28:59  jalet
109# edpykota should be ok, minus some typos
110#
111# Revision 1.3  2003/02/06 10:47:21  jalet
112# Documentation string and command line options didn't match.
113#
114# Revision 1.2  2003/02/06 10:39:23  jalet
115# Preliminary edpykota work.
116#
117# Revision 1.1  2003/02/05 21:41:09  jalet
118# Skeletons added for all command line tools
119#
120#
121#
122
123import sys
124
125from pykota import version
126from pykota.tool import PyKotaTool, PyKotaToolError
127
128__doc__ = """edpykota v%s (C) 2003 C@LL - Conseil Internet & Logiciels Libres
129A Print Quota editor for PyKota.
130
131command line usage :
132
133  edpykota [options] user1 user2 ... userN
134  edpykota [options] group1 group2 ... groupN
135
136options :
137
138  -v | --version       Prints edpykota's version number then exits.
139  -h | --help          Prints this message then exits.
140 
141  -a | --add           Adds users and/or printers if they don't
142                       exist on the Quota Storage Server.
143                       
144  -u | --users         Edit users print quotas, this is the default.
145 
146  -P | --printer p     Edit quotas on printer p only. Actually p can
147                       use wildcards characters to select only
148                       some printers. The default value is *, meaning
149                       all printers.
150 
151  -g | --groups        Edit groups print quotas instead of users.
152                         
153  -p | --prototype u|g Uses user u or group g as a prototype to set
154                       print quotas
155                       
156  -n | --noquota       Doesn't set a quota but only does accounting.
157 
158  -r | --reset         Resets the printed page counter for the user
159                       or group to zero. The life time page counter
160                       is kept unchanged.
161                       
162  -S | --softlimit sl  Sets the quota soft limit to sl pages.                       
163 
164  -H | --hardlimit hl  Sets the quota hard limit to hl pages.
165 
166  user1 through userN and group1 through groupN can use wildcards
167  if the --add option is not set.
168 
169examples :                             
170
171  $ edpykota -p jerome john paul george ringo
172 
173  This will set print quotas for the users john, paul, george and ringo
174  to the same values than user jerome. User jerome must exist.
175 
176  $ edpykota --printer lp -S 50 -H 60 jerome
177 
178  This will set jerome's print quota on the lp printer to a soft limit
179  of 50 pages, and a hard limit of 60 pages. If either user jerome or
180  printer lp doesn't exist on the Quota Storage Server then nothing is done.
181
182  $ edpykota --add --printer lp -S 50 -H 60 jerome
183 
184  Same as above, but if either user jerome or printer lp doesn't exist
185  on the Quota Storage Server they are automatically added.
186  WARNING : the CUPS PPD file for this printer must still be modified
187            manually, as well as pykota's configuration file for a
188            new printer to be managed successfully.
189           
190  $ edpykota -g -S 500 -H 550 financial support           
191 
192  This will set print quota soft limit to 500 pages and hard limit
193  to 550 pages for groups financial and support on all printers.
194 
195  $ edpykota --reset jerome "jo*"
196 
197  This will reset jerome's page counter to zero on all printers, as
198  well as every user whose name begins with 'jo'.
199  Their life time page counter on each printer will be kept unchanged.
200 
201  $ edpykota --printer hpcolor --noquota jerome
202 
203  This will tell PyKota to not limit jerome when printing on the
204  hpcolor printer. All his jobs will be allowed on this printer, but
205  accounting of the pages he prints will still be kept.
206  Print Quotas for jerome on other printers are unchanged.
207
208This program is free software; you can redistribute it and/or modify
209it under the terms of the GNU General Public License as published by
210the Free Software Foundation; either version 2 of the License, or
211(at your option) any later version.
212
213This program is distributed in the hope that it will be useful,
214but WITHOUT ANY WARRANTY; without even the implied warranty of
215MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
216GNU General Public License for more details.
217
218You should have received a copy of the GNU General Public License
219along with this program; if not, write to the Free Software
220Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
221
222Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
223       
224class EdPyKota(PyKotaTool) :       
225    """A class for edpykota."""
226    def main(self, names, options) :
227        """Edit user or group quotas."""
228        printernames = self.storage.getMatchingPrinters(options["printer"])
229        if not printernames :
230            pname = options["printer"]
231            if options["add"] and pname :
232                if self.isValidName(pname) :
233                    self.storage.addPrinter(pname)
234                    printernames = [ (pname, 0) ]
235                else :   
236                    raise PyKotaToolError, _("Invalid printer name %s") % pname
237            else :
238                raise PyKotaToolError, _("There's no printer matching %s") % pname
239        softlimit = hardlimit = None   
240        if options["softlimit"] :
241            try :
242                softlimit = int(options["softlimit"].strip())
243            except ValueError :   
244                raise PyKotaToolError, _("Invalid softlimit value %s.") % options["softlimit"]
245        if options["hardlimit"] :
246            try :
247                hardlimit = int(options["hardlimit"].strip())
248            except ValueError :   
249                raise PyKotaToolError, _("Invalid hardlimit value %s.") % options["hardlimit"]
250        if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :       
251            # error, exchange them
252            self.logger.log_message(_("Hard limit %i is less than soft limit %i, values will be exchanged.") % (hardlimit, softlimit))
253            (softlimit, hardlimit) = (hardlimit, softlimit)
254        if not names :   
255            if options["add"] :
256                raise PyKotaToolError, _("You have to pass user names on the command line")
257            else :   
258                names = [ "*" ] # all users
259        for (printer, printerpagecounter) in printernames :
260            if options["prototype"] :
261                if options["groups"] :
262                    prototype = self.storage.getGroupPQuota(options["prototype"], printer)
263                else :     
264                    # default is user quota edition
265                    prototype = self.storage.getUserPQuota(options["prototype"], printer)
266                if prototype is None :
267                    self.logger.log_message(_("Prototype %s not found in Quota Storage for printer %s.") % (options["prototype"], printer))
268                    continue    # skip this printer
269                else :   
270                    (softlimit, hardlimit) = (prototype["softlimit"], prototype["hardlimit"])
271            if hardlimit is None :   
272                hardlimit = softlimit
273                if hardlimit is not None :
274                    self.logger.log_message(_("Undefined hard limit set to soft limit (%s) on printer %s.") % (str(hardlimit), printer))
275            if softlimit is None :   
276                softlimit = hardlimit
277                if softlimit is not None :
278                    self.logger.log_message(_("Undefined soft limit set to hard limit (%s) on printer %s.") % (str(softlimit), printer))
279            if (not options["reset"] and not options["noquota"]) and ((hardlimit is None) or (softlimit is None)) :
280                raise PyKotaToolError, _("Both hard and soft limits must be set ! Aborting.")
281            if options["add"] :   
282                allnames = names
283            else :   
284                if options["groups"] :   
285                    allnames = self.storage.getPrinterGroups(printer)
286                else :   
287                    allnames = self.storage.getPrinterUsers(printer)
288            for name in [n for n in allnames if self.matchString(n, names)]:
289                if options["groups"] :
290                    quota = self.storage.getGroupPQuota(name, printer)
291                else :
292                    quota = self.storage.getUserPQuota(name, printer)
293                if quota is None :
294                    # not found
295                    if options["add"] :
296                        # In case we want to add something, it is crucial
297                        # that we DON'T check with the system accounts files
298                        # like /etc/passwd because users may be defined
299                        # only remotely
300                        if options["groups"] :
301                            if self.isValidName(name) :
302                                self.storage.addGroupPQuota(name, printer)
303                                quota = self.storage.getGroupPQuota(name, printer)
304                            else :   
305                                self.logger.log_message(_("Invalid group name %s") % name)
306                        else :
307                            if self.isValidName(name) :
308                                self.storage.addUserPQuota(name, printer)
309                                quota = self.storage.getUserPQuota(name, printer)
310                            else :   
311                                self.logger.log_message(_("Invalid user name %s") % name)
312                if quota is None :     
313                    self.logger.log_message(_("Quota not found for object %s on printer %s.") % (name, printer))
314                else :   
315                    if options["groups"] :
316                        if options["noquota"] or ((softlimit is not None) and (hardlimit is not None)) :
317                            self.storage.setGroupPQuota(name, printer, softlimit, hardlimit)
318                        if options["reset"] :
319                            self.storage.resetGroupPQuota(name, printer)
320                    else :
321                        if options["noquota"] or ((softlimit is not None) and (hardlimit is not None)) :
322                            self.storage.setUserPQuota(name, printer, softlimit, hardlimit)
323                        if options["reset"] :
324                            self.storage.resetUserPQuota(name, printer)
325                     
326if __name__ == "__main__" : 
327    try :
328        defaults = { \
329                     "users"  : 1, \
330                     "groups" : 0, \
331                     "printer" : "*", \
332                   }
333        short_options = "vhnaugrp:P:S:H:"
334        long_options = ["help", "version", "noquota", "add", "users", "groups", "reset", "prototype=", "printer=", "softlimit=", "hardlimit="]
335       
336        # Initializes the command line tool
337        editor = EdPyKota(doc=__doc__)
338       
339        # parse and checks the command line
340        (options, args) = editor.parseCommandline(sys.argv[1:], short_options, long_options)
341       
342        # sets long options
343        options["help"] = options["h"] or options["help"]
344        options["version"] = options["v"] or options["version"]
345        options["add"] = options["a"] or options["add"]
346        options["users"] = options["u"] or options["users"] or defaults["users"]
347        options["groups"] = options["g"] or options["groups"] or defaults["groups"]
348        options["prototype"] = options["p"] or options["prototype"]
349        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
350        options["softlimit"] = options["S"] or options["softlimit"]
351        options["hardlimit"] = options["H"] or options["hardlimit"] 
352        options["reset"] = options["r"] or options["reset"] 
353        options["noquota"] = options["n"] or options["noquota"]
354       
355        if options["help"] :
356            editor.display_usage_and_quit()
357        elif options["version"] :
358            editor.display_version_and_quit()
359        elif options["users"] and options["groups"] :   
360            raise PyKotaToolError, _("incompatible options, see help.")
361        elif (options["softlimit"] or options["hardlimit"]) and options["prototype"] :   
362            raise PyKotaToolError, _("incompatible options, see help.")
363        elif options["noquota"] and (options["prototype"] or options["hardlimit"] or options["softlimit"]) :
364            raise PyKotaToolError, _("incompatible options, see help.")
365        elif options["groups"] :   
366            raise PyKotaToolError, _("option --groups is currently not implemented.")
367        else :
368            sys.exit(editor.main(args, options))
369    except PyKotaToolError, msg :           
370        sys.stderr.write("%s\n" % msg)
371        sys.stderr.flush()
372        sys.exit(-1)
Note: See TracBrowser for help on using the browser.