root / pykota / trunk / bin / edpykota @ 916

Revision 916, 16.5 kB (checked in by jalet, 21 years ago)

Allow to add a printer without any user

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