root / pykota / trunk / bin / edpykota @ 2225

Revision 2225, 26.5 kB (checked in by jerome, 19 years ago)

Fixed inconstistency between SQL and LDAP backends' behavior.

  • 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: ISO-8859-15 -*-
3
4# PyKota Print Quota Editor
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25#
26
27import sys
28import os
29import pwd
30import grp
31from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
32from pykota.config import PyKotaConfigError
33from pykota.storage import PyKotaStorageError
34
35__doc__ = N_("""edpykota v%s (c) 2003, 2004, 2005 C@LL - Conseil Internet & Logiciels Libres
36A Print Quota editor for PyKota.
37
38command line usage :
39
40  edpykota [options] user1 user2 ... userN
41 
42  edpykota [options] group1 group2 ... groupN
43
44options :
45
46  -v | --version       Prints edpykota's version number then exits.
47  -h | --help          Prints this message then exits.
48 
49  -a | --add           Adds users and/or printers if they don't
50                       exist on the Quota Storage Server.
51                       
52  -d | --delete        Deletes users/groups from the quota storage.
53                       Printers are never deleted.
54                       
55  -c | --charge p[,j]  Sets the price per page and per job to charge
56                       for a particular printer. Job price is optional.
57                       If both are to be set, separate them with a comma.
58                       Floating point values are allowed.
59                       
60  -o | --overcharge f  Sets the overcharging factor applied to the user
61                       when computing the cost of a print job. Positive or
62                       negative floating point values are allowed,
63                       this allows you to do some really creative
64                       things like giving money to an user whenever
65                       he prints. The number of pages in a print job
66                       is not modified by this coefficient, only the
67                       cost of the job for a particular user.
68                       Only users have a coefficient.
69 
70  -i | --ingroups g1[,g2...]  Puts the users into each of the groups
71                              listed, separated by commas. The groups
72                              must already exist in the Quota Storage.
73 
74  -u | --users         Edit users print quotas, this is the default.
75 
76  -P | --printer p     Edit quotas on printer p only. Actually p can
77                       use wildcards characters to select only
78                       some printers. The default value is *, meaning
79                       all printers.
80                       You can specify several names or wildcards,
81                       by separating them with commas.
82 
83  -G | --pgroups pg1[,pg2...] Adds the printer(s) to the printer groups
84                       pg1, pg2, etc... which must already exist.
85                       A printer group is just like a normal printer,
86                       only that it is usually unknown from the printing
87                       system. Create printer groups exactly the same
88                       way that you create printers, then add other
89                       printers to them with this option.
90                       Accounting is done on a printer and on all
91                       the printer groups it belongs to, quota checking
92                       is done on a printer and on all the printer groups
93                       it belongs to.
94 
95  -g | --groups        Edit users groups print quotas instead of users.
96                         
97  -p | --prototype u|g Uses user u or group g as a prototype to set
98                       print quotas
99                       
100  -n | --noquota       Doesn't set a quota but only does accounting.
101 
102  -r | --reset         Resets the actual page counter for the user
103                       or group to zero on the specified printers.
104                       The life time page counter is kept unchanged.
105                       
106  -R | --hardreset     Resets the actual and life time page counters
107                       for the user or group to zero on the specified
108                       printers. This is a shortcut for '--used 0'.
109                       
110  -l | --limitby l     Choose if the user/group is limited in printing                     
111                       by its account balance or by its page quota.
112                       The default value is 'quota'. Allowed values
113                       are 'quota' 'balance' 'quota-then-balance' and
114                       'balance-then-quota'.
115                       WARNING : quota-then-balance and balance-then-quota
116                       are not yet implemented.
117                       
118  -b | --balance b     Sets the user's account balance to b.                     
119                       Account balance may be increase or decreased
120                       if b is prefixed with + or -.
121                       WARNING : when decreasing account balance,
122                       the total paid so far by the user is decreased
123                       too.
124                       Groups don't have a real balance, but the
125                       sum of their users' account balance.
126                       
127  -S | --softlimit sl  Sets the quota soft limit to sl pages.                       
128 
129  -H | --hardlimit hl  Sets the quota hard limit to hl pages.
130
131  -U | --used usage    Sets the pagecounters for the user to usage pages;
132                       useful for migrating users from a different system
133                       where they have already used some pages. Actual
134                       and Life Time page counters may be increased or decreased
135                       if usage is prefixed with + or -.
136                       WARNING : BOTH page counters are modified in all cases,
137                       so be careful.
138                       NB : if 'usage' equals '0', then the action taken is
139                       the same as if --hardreset was used.
140
141  user1 through userN and group1 through groupN can use wildcards
142  if the --add option is not set.
143 
144examples :                             
145
146  $ edpykota --add -p jerome john paul george ringo/ringo@example.com
147 
148  This will add users john, paul, george and ringo to the quota
149  database, and set their print quotas to the same values than user
150  jerome. User jerome must already exist.
151  User ringo's email address will also be set to 'ringo@example.com'
152 
153  $ edpykota --printer lp -S 50 -H 60 jerome
154 
155  This will set jerome's print quota on the lp printer to a soft limit
156  of 50 pages, and a hard limit of 60 pages. If either user jerome or
157  printer lp doesn't exist on the Quota Storage Server then nothing is done.
158
159  $ edpykota --add --printer lp --ingroups coders,it -S 50 -H 60 jerome
160 
161  Same as above, but if either user jerome or printer lp doesn't exist
162  on the Quota Storage Server they are automatically added. Also
163  user jerome is put into the groups "coders" and "it" which must
164  already exist in the Quota Storage.
165           
166  $ edpykota -g -S 500 -H 550 financial support           
167 
168  This will set print quota soft limit to 500 pages and hard limit
169  to 550 pages for groups financial and support on all printers.
170 
171  $ edpykota --reset jerome "jo*"
172 
173  This will reset jerome's page counter to zero on all printers, as
174  well as every user whose name begins with 'jo'.
175  Their life time page counter on each printer will be kept unchanged.
176  You can also reset the life time page counters by using the
177  --hardreset | -R command line option.
178 
179  $ edpykota --printer hpcolor --noquota jerome
180 
181  This will tell PyKota to not limit jerome when printing on the
182  hpcolor printer. All his jobs will be allowed on this printer, but
183  accounting of the pages he prints will still be kept.
184  Print Quotas for jerome on other printers are unchanged.
185 
186  $ edpykota --limitby balance jerome
187 
188  This will tell PyKota to limit jerome by his account's balance
189  when printing.
190 
191  $ edpykota --balance +10.0 jerome
192 
193  This will increase jerome's account balance by 10.0 (in your
194  own currency). You can decrease the account balance with a
195  dash prefix, and set it to a fixed amount with no prefix.
196 
197  $ edpykota --delete jerome rachel
198 
199  This will completely delete jerome and rachel from the Quota Storage
200  database. All their quotas and jobs will be deleted too.
201 
202  $ edpykota --printer lp --charge 0.1
203 
204  This will set the page price for printer lp to 0.1. Job price
205  will not be changed.
206 
207  $ edpykota --printer hplj1,hplj2 --pgroups Laser,HP
208 
209  This will put printers hplj1 and hplj2 in printers groups Laser and HP.
210  When printing either on hplj1 or hplj2, print quota will also be
211  checked and accounted for on virtual printers Laser and HP.
212 
213  $ edpykota --overcharge 2.5 poorstudent
214 
215  This will overcharge the poorstudent user by a factor of 2.5.
216 
217  $ edpykota --overcharge -1 jerome
218 
219  User jerome will actually earn money whenever he prints.
220 
221  $ edpykota --overcharge 0 boss
222 
223  User boss can print at will, it won't cost him anything because the
224  cost of each print job will be multiplied by zero before charging
225  his account.
226
227This program is free software; you can redistribute it and/or modify
228it under the terms of the GNU General Public License as published by
229the Free Software Foundation; either version 2 of the License, or
230(at your option) any later version.
231
232This program is distributed in the hope that it will be useful,
233but WITHOUT ANY WARRANTY; without even the implied warranty of
234MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
235GNU General Public License for more details.
236
237You should have received a copy of the GNU General Public License
238along with this program; if not, write to the Free Software
239Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
240
241Please e-mail bugs to: %s""") 
242       
243class EdPyKota(PyKotaTool) :       
244    """A class for edpykota."""
245    def main(self, names, options) :
246        """Edit user or group quotas."""
247        if not self.config.isAdmin :
248            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
249       
250        suffix = (options["groups"] and "Group") or "User"       
251       
252        softlimit = hardlimit = None
253
254        used = options["used"]
255        if used :
256            used = used.strip()
257            try :
258                int(used)
259            except ValueError :
260                raise PyKotaToolError, _("Invalid used value %s.") % used
261
262        if not options["noquota"] :
263            if options["softlimit"] :
264                try :
265                    softlimit = int(options["softlimit"].strip())
266                except ValueError :   
267                    raise PyKotaToolError, _("Invalid softlimit value %s.") % options["softlimit"]
268            if options["hardlimit"] :
269                try :
270                    hardlimit = int(options["hardlimit"].strip())
271                except ValueError :   
272                    raise PyKotaToolError, _("Invalid hardlimit value %s.") % options["hardlimit"]
273            if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :       
274                # error, exchange them
275                self.printInfo(_("Hard limit %i is less than soft limit %i, values will be exchanged.") % (hardlimit, softlimit))
276                (softlimit, hardlimit) = (hardlimit, softlimit)
277           
278        overcharge = options["overcharge"]
279        if overcharge :
280            try :
281                overcharge = float(overcharge.strip())
282            except (ValueError, AttributeError) :   
283                raise PyKotaToolError, _("Invalid overcharge value %s") % options["overcharge"]
284               
285        balance = options["balance"]
286        if balance :
287            balance = balance.strip()
288            try :
289                balancevalue = float(balance)
290            except ValueError :   
291                raise PyKotaToolError, _("Invalid balance value %s") % options["balance"]
292           
293        if options["charge"] :
294            try :
295                charges = [float(part) for part in options["charge"].split(',', 1)]
296            except ValueError :   
297                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
298            else :   
299                if len(charges) > 2 :
300                    charges = charges[:2]
301                if len(charges) != 2 :
302                    charges = [charges[0], None]
303                   
304        limitby = options["limitby"]
305        if limitby :
306            limitby = limitby.strip().lower()
307        if limitby and (limitby not in ('quota', 'balance', 'quota-then-balance', 'balance-then-quota')) :   
308            raise PyKotaToolError, _("Invalid limitby value %s") % options["limitby"]
309           
310        if options["ingroups"] :   
311            groupnames = [gname.strip() for gname in options["ingroups"].split(',')]
312        else :   
313            groupnames = []
314           
315        rejectunknown = self.config.getRejectUnknown()   
316        printeradded = 0
317        printers = self.storage.getMatchingPrinters(options["printer"])
318        if not printers :
319            pname = options["printer"]
320            if options["add"] and pname :
321                if self.isValidName(pname) :
322                    printers = [ self.storage.addPrinter(pname) ]
323                    if printers[0].Exists :
324                        printeradded = 1
325                    else :   
326                        raise PyKotaToolError, _("Impossible to add printer %s") % pname
327                else :   
328                    raise PyKotaToolError, _("Invalid printer name %s") % pname
329            else :
330                raise PyKotaToolError, _("There's no printer matching %s") % pname
331        if not names :   
332            if options["delete"] :   
333                raise PyKotaToolError, _("You have to pass user or group names on the command line")
334            else :
335                names = getattr(self.storage, "getAll%ssNames" % suffix)() # all users or groups
336               
337        printersgroups = []       
338        if options["pgroups"] :       
339            printersgroups = self.storage.getMatchingPrinters(options["pgroups"])
340           
341        if options["prototype"] :   
342            protoentry = getattr(self.storage, "get%s" % suffix)(options["prototype"])
343            if not protoentry.Exists :
344                raise PyKotaToolError, _("Prototype object %s not found in Quota Storage.") % protoentry.Name
345            else :   
346                limitby = protoentry.LimitBy
347                balancevalue = protoentry.AccountBalance
348                balance = str(balance)
349                overcharge = getattr(protoentry, "OverCharge", None)
350           
351        todelete = {}   
352        changed = {} # tracks changes made at the user/group level
353        for printer in printers :
354            for pgroup in printersgroups :
355                pgroup.addPrinterToGroup(printer)   
356               
357            if options["charge"] :
358                (perpage, perjob) = charges
359                printer.setPrices(perpage, perjob)   
360               
361            if options["prototype"] :
362                protoquota = getattr(self.storage, "get%sPQuota" % suffix)(protoentry, printer)
363                if not protoquota.Exists :
364                    self.printInfo(_("Prototype %s not found in Quota Storage for printer %s.") % (protoentry.Name, printer.Name))
365                else :   
366                    (softlimit, hardlimit) = (protoquota.SoftLimit, protoquota.HardLimit)
367                   
368            if not options["noquota"] :   
369                if hardlimit is None :   
370                    hardlimit = softlimit
371                    if hardlimit is not None :
372                        self.printInfo(_("Undefined hard limit set to soft limit (%s) on printer %s.") % (str(hardlimit), printer.Name))
373                if softlimit is None :   
374                    softlimit = hardlimit
375                    if softlimit is not None :
376                        self.printInfo(_("Undefined soft limit set to hard limit (%s) on printer %s.") % (str(softlimit), printer.Name))
377                       
378            if options["add"] :   
379                allentries = []   
380                for name in names :
381                    email = ""
382                    if not options["groups"] :
383                        splitname = name.split('/', 1)     # username/email
384                        if len(splitname) == 1 :
385                            splitname.append("")
386                        (name, email) = splitname
387                        if email and (email.count('@') != 1) :
388                            self.printInfo(_("Invalid email address %s") % email)
389                            email = ""
390                    entry = getattr(self.storage, "get%s" % suffix)(name)
391                    if email and not options["groups"] :
392                        entry.Email = email
393                    entrypquota = getattr(self.storage, "get%sPQuota" % suffix)(entry, printer)
394                    allentries.append((entry, entrypquota))
395            else :   
396                allentries = getattr(self.storage, "getPrinter%ssAndQuotas" % suffix)(printer, names)
397               
398            for (entry, entrypquota) in allentries :
399                if not changed.has_key(entry.Name) :
400                    changed[entry.Name] = {}
401                    if not options["groups"] :
402                        changed[entry.Name]["ingroups"] = []
403                       
404                if not entry.Exists :       
405                    # not found
406                    if options["add"] :
407                        # In case we want to add something, it is crucial
408                        # that we DON'T check with the system accounts files
409                        # like /etc/passwd because users may be defined
410                        # only remotely
411                        if self.isValidName(entry.Name) :
412                            reject = 0
413                            if rejectunknown :
414                                if options["groups"] :
415                                    try :
416                                        grp.getgrnam(entry.Name)
417                                    except KeyError :   
418                                        self.printInfo(_("Unknown group %s") % entry.Name, "error")
419                                        reject = 1
420                                else :   
421                                    try :
422                                        pwd.getpwnam(entry.Name)
423                                    except KeyError :   
424                                        self.printInfo(_("Unknown user %s") % entry.Name, "error")
425                                        reject = 1
426                            if not reject :       
427                                entry = getattr(self.storage, "add%s" % suffix)(entry)
428                        else :   
429                            if options["groups"] :
430                                self.printInfo(_("Invalid group name %s") % entry.Name)
431                            else :   
432                                self.printInfo(_("Invalid user name %s") % entry.Name)
433                elif options["delete"] :               
434                    todelete[entry.Name] = entry
435                               
436                if entry.Exists and (not entrypquota.Exists) :
437                    # not found
438                    if options["add"] :
439                        entrypquota = getattr(self.storage, "add%sPQuota" % suffix)(entry, printer)
440                       
441                if not entrypquota.Exists :     
442                    self.printInfo(_("Quota not found for object %s on printer %s.") % (entry.Name, printer.Name))
443                else :   
444                    if options["noquota"] or options["prototype"] or ((softlimit is not None) and (hardlimit is not None)) :
445                        entrypquota.setLimits(softlimit, hardlimit)
446                    if limitby :
447                        if changed[entry.Name].get("limitby") is None :
448                            entry.setLimitBy(limitby)
449                            changed[entry.Name]["limitby"] = limitby
450                   
451                    if options["reset"] :
452                        entrypquota.reset()
453                       
454                    if options["hardreset"] :   
455                        entrypquota.hardreset()
456                       
457                    if not options["groups"] :
458                        if used :
459                            entrypquota.setUsage(used)
460                           
461                        if overcharge is not None :   
462                            if changed[entry.Name].get("overcharge") is None :
463                                entry.setOverChargeFactor(overcharge)
464                                changed[entry.Name]["overcharge"] = overcharge
465                               
466                        if balance :
467                            if changed[entry.Name].get("balance") is None :
468                                if balance.startswith("+") or balance.startswith("-") :
469                                    newbalance = float(entry.AccountBalance or 0.0) + balancevalue
470                                    newlifetimepaid = float(entry.LifeTimePaid or 0.0) + balancevalue
471                                    entry.setAccountBalance(newbalance, newlifetimepaid)
472                                else :
473                                    diff = balancevalue - float(entry.AccountBalance or 0.0)
474                                    newlifetimepaid = float(entry.LifeTimePaid or 0.0) + diff
475                                    entry.setAccountBalance(balancevalue, newlifetimepaid)
476                                changed[entry.Name]["balance"] = balance
477                               
478                        for groupname in groupnames :       
479                            # not executed if option --ingroups is not used
480                            if groupname not in changed[entry.Name]["ingroups"] :
481                                group = self.storage.getGroup(groupname)
482                                if group.Exists :
483                                    self.storage.addUserToGroup(entry, group)
484                                    changed[entry.Name]["ingroups"].append(groupname)
485                                else :
486                                    self.printInfo(_("Group %s not found in the PyKota Storage.") % groupname)
487                       
488        # Now delete what has to be deleted               
489        for (name, entry) in todelete.items() :               
490            entry.delete()
491                     
492if __name__ == "__main__" : 
493    retcode = 0
494    try :
495        defaults = { \
496                     "printer" : "*", \
497                   }
498        short_options = "vhdo:c:l:b:i:naugrp:P:S:H:G:RU:"
499        long_options = ["help", "version", "overcharge=", "charge=", "delete", "limitby=", "balance=", "ingroups=", "noquota", "add", "users", "groups", "reset", "hardreset", "prototype=", "printer=", "softlimit=", "hardlimit=", "pgroups=", "used="]
500       
501        # Initializes the command line tool
502        editor = EdPyKota(doc=__doc__)
503        editor.deferredInit()
504       
505        # parse and checks the command line
506        (options, args) = editor.parseCommandline(sys.argv[1:], short_options, long_options)
507       
508        # sets long options
509        options["help"] = options["h"] or options["help"]
510        options["version"] = options["v"] or options["version"]
511        options["add"] = options["a"] or options["add"]
512        options["users"] = options["u"] or options["users"]
513        options["groups"] = options["g"] or options["groups"]
514        options["prototype"] = options["p"] or options["prototype"]
515        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
516        options["softlimit"] = options["S"] or options["softlimit"]
517        options["hardlimit"] = options["H"] or options["hardlimit"] 
518        options["reset"] = options["r"] or options["reset"] 
519        options["noquota"] = options["n"] or options["noquota"]
520        options["limitby"] = options["l"] or options["limitby"]
521        options["balance"] = options["b"] or options["balance"] 
522        options["delete"] = options["d"] or options["delete"] 
523        options["ingroups"] = options["i"] or options["ingroups"]
524        options["charge"] = options["c"] or options["charge"]
525        options["pgroups"] = options["G"] or options["pgroups"]
526        options["hardreset"] = options["R"] or options["hardreset"] 
527        options["used"] = options["U"] or options["used"]
528        options["overcharge"] = options["o"] or options["overcharge"]
529       
530        if options["help"] :
531            editor.display_usage_and_quit()
532        elif options["version"] :
533            editor.display_version_and_quit()
534        elif options["users"] and options["groups"] :   
535            raise PyKotaToolError, _("incompatible options, see help.")
536        elif (options["add"] or options["prototype"]) and options["delete"] :   
537            raise PyKotaToolError, _("incompatible options, see help.")
538        elif (options["reset"] or options["hardreset"] or options["limitby"] or options["used"] or options["balance"] or options["overcharge"] or options["softlimit"] or options["hardlimit"]) and options["prototype"] :
539            raise PyKotaToolError, _("incompatible options, see help.")
540        elif options["noquota"] and (options["prototype"] or options["hardlimit"] or options["softlimit"]) :
541            raise PyKotaToolError, _("incompatible options, see help.")
542        elif options["groups"] and (options["balance"] or options["ingroups"] or options["used"] or options["overcharge"]) :
543            raise PyKotaToolError, _("incompatible options, see help.")
544        else :
545            retcode = editor.main(args, options)
546    except KeyboardInterrupt :       
547        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
548    except SystemExit :       
549        pass
550    except :
551        try :
552            editor.crashed("edpykota failed")
553        except :   
554            crashed("edpykota failed")
555        retcode = -1
556
557    try :
558        editor.storage.close()
559    except (TypeError, NameError, AttributeError) :   
560        pass
561       
562    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.