root / pykota / trunk / bin / pkturnkey @ 2432

Revision 2432, 8.1 kB (checked in by jerome, 19 years ago)

pkturnkey now simulates by default, instead of modifying the database.
The --dryrun command line switch was replaced by the --force command line
switch, which does exactly the opposite : allows the database to be modified.
Now pkturnkey sends all the informations about what it does to the
screen (but on stderr).
Severity : now you can play with this without risking to loose your datas :-)

  • 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 Turn Key tool
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22#
23# $Id$
24#
25#
26
27import sys
28import os
29import pwd
30
31from pykota.tool import Tool, PyKotaToolError, crashed, N_
32
33__doc__ = N_("""pkturnkey v%(__version__)s (c) %(__years__)s %(__author__)s
34
35A turn key tool for PyKota. When launched, this command will initialize
36PyKota's database with all existing print queues and some or all users.
37For now, no prices or limits are set, so printing is fully accounted
38for, but not limited.
39
40command line usage :
41
42  pkturnkey [options]
43
44options :
45
46  -v | --version       Prints pkturnkey version number then exits.
47  -h | --help          Prints this message then exits.
48 
49  -f | --force         Modifies the database instead of printing what
50                       it would do.
51                       
52  -u | --uidmin uid    Only adds users whose uid is greater than or equal to
53                       uid. You can pass an username there as well, and its
54                       uid will be used automatically.
55                       If not set, 0 will be used automatically.
56                       
57  -U | --uidmax uid    Only adds users whose uid is lesser than or equal to
58                       uid. You can pass an username there as well, and its
59                       uid will be used automatically.
60                       If not set, a large value will be used automatically.
61
62examples :                             
63
64  $ pkturnkey --uidmin jerome
65
66  Will simulate the initialization of PyKota's database will all existing
67  printers and print accounts for all users whose uid is greater than
68  or equal to jerome's one.
69  To REALLY initialize the database instead of simulating it, please
70  use the -f | --force command line switch.
71""")
72       
73class PKTurnKey(Tool) :
74    """A class for an initialization tool."""
75    def listPrinters(self) :
76        """Returns a list of tuples (queuename, deviceuri) for all existing print queues."""
77        self.printInfo("Extracting all print queues.")
78        result = os.popen("lpstat -v", "r")
79        lines = result.readlines()
80        result.close()
81        printers = []
82        for line in lines :
83            (begin, end) = line.split(':', 1)
84            deviceuri = end.strip()
85            queuename = begin.split()[-1]
86            printers.append((queuename, deviceuri))
87        return printers   
88       
89    def listUsers(self, uidmin, uidmax) :   
90        """Returns a list of usernames whose uids are between uidmin and uidmax."""
91        self.printInfo("Extracting all users whose uid is between %s and %s." % (uidmin, uidmax))
92        return [entry[0] for entry in pwd.getpwall() if uidmin <= entry[2] <= uidmax]
93       
94    def runCommand(self, command, dryrun) :   
95        """Launches an external command."""
96        self.printInfo("%s" % command)
97        if not dryrun :   
98            os.system(command)
99           
100    def createPrinters(self, printers, dryrun=0) :   
101        """Creates all printers in PyKota's database."""
102        if printers :
103            needswarning = [p[0] for p in printers if p[1].find("cupspykota") == -1]
104            command = "pkprinters --add %s" % " ".join(['"%s"' % p[0] for p in printers])
105            self.runCommand(command, dryrun)
106            for p in needswarning :
107                self.printInfo(_("Printer %s is not managed by PyKota yet. Please modify printers.conf and restart CUPS.") % p, "warn")
108       
109    def createUsers(self, users, dryrun=0) :
110        """Creates all users in PyKota's database."""
111        if users :
112            command = "edpykota --add --noquota %s" % " ".join(['"%s"' % u for u in users])
113            self.runCommand(command, dryrun)
114       
115    def main(self, names, options) :
116        """Intializes PyKota's database."""
117        if not self.config.isAdmin :
118            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
119           
120        # TODO : names not used for now   
121        if not names :
122            names = ["*"]
123           
124        self.printInfo("Please be patient...")
125        dryrun = not options["force"]
126        if dryrun :
127            self.printInfo("Don't worry, the database WILL NOT BE MODIFIED.")
128        else :   
129            self.printInfo("Please WORRY NOW, the database WILL BE MODIFIED.")
130           
131        if not options["uidmin"] :   
132            self.printInfo(_("System users will have a print account as well !"), "warn")
133            uidmin = 0
134        else :   
135            try :
136                uidmin = int(options["uidmin"])
137            except :   
138                try :
139                    uidmin = pwd.getpwnam(options["uidmin"])[2]
140                except KeyError, msg :   
141                    raise PyKotaToolError, _("Unknown username %s : %s") % (options["uidmin"], msg)
142                   
143        if not options["uidmax"] :   
144            uidmax = sys.maxint
145        else :   
146            try :
147                uidmax = int(options["uidmax"])
148            except :   
149                try :
150                    uidmax = pwd.getpwnam(options["uidmax"])[2]
151                except KeyError, msg :   
152                    raise PyKotaToolError, _("Unknown username %s : %s") % (options["uidmax"], msg)
153       
154        if uidmin > uidmax :           
155            (uidmin, uidmax) = (uidmax, uidmin)
156        users = self.listUsers(uidmin, uidmax)
157        printers = self.listPrinters()                   
158       
159        if printers :
160            self.createPrinters(printers, dryrun)
161            self.createUsers(users, dryrun)
162       
163        if dryrun :
164            self.printInfo("Simulation terminated.")
165        else :   
166            self.printInfo("Database initialized !")
167                   
168                     
169if __name__ == "__main__" : 
170    retcode = 0
171    try :
172        short_options = "hvfu:U:"
173        long_options = ["help", "version", "force", "uidmin=", "uidmax="]
174       
175        # Initializes the command line tool
176        manager = PKTurnKey(doc=__doc__)
177        manager.deferredInit()
178       
179        # parse and checks the command line
180        (options, args) = manager.parseCommandline(sys.argv[1:], \
181                                                   short_options, \
182                                                   long_options, \
183                                                   allownothing=1)
184       
185        # sets long options
186        options["help"] = options["h"] or options["help"]
187        options["version"] = options["v"] or options["version"]
188        options["force"] = options["f"] or options["force"]
189        options["uidmin"] = options["u"] or options["uidmin"]
190        options["uidmax"] = options["U"] or options["uidmax"]
191       
192        if options["help"] :
193            manager.display_usage_and_quit()
194        elif options["version"] :
195            manager.display_version_and_quit()
196        else :
197            retcode = manager.main(args, options)
198    except KeyboardInterrupt :       
199        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
200    except SystemExit :       
201        pass
202    except :
203        try :
204            manager.crashed("pkturnkey failed")
205        except :   
206            crashed("pkturnkey failed")
207        retcode = -1
208
209    try :
210        manager.storage.close()
211    except (TypeError, NameError, AttributeError) :   
212        pass
213       
214    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.