root / pykota / trunk / bin / dumpykota @ 1855

Revision 1809, 11.4 kB (checked in by jalet, 20 years ago)

Now outputs the name of the offending user if a mere mortal tries to use
one of these commands !!!

  • 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 Data Dumper
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 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# $Log$
26# Revision 1.15  2004/10/12 15:37:00  jalet
27# Now outputs the name of the offending user if a mere mortal tries to use
28# one of these commands !!!
29#
30# Revision 1.14  2004/10/11 22:53:05  jalet
31# Postponed string interpolation to help message's output method
32#
33# Revision 1.13  2004/10/11 12:49:06  jalet
34# Renders help translatable
35#
36# Revision 1.12  2004/10/07 21:14:28  jalet
37# Hopefully final fix for data encoding to and from the database
38#
39# Revision 1.11  2004/10/07 14:35:40  jalet
40# Now edpykota refuses to launch if the user is not a PyKota administrator.
41# dumpykota : now has the same error message than edpykota in this case.
42#
43# Revision 1.10  2004/10/06 10:05:47  jalet
44# Minor changes to allow any PyKota administrator to launch enhanced versions
45# of the commands, and not only the root user.
46#
47# Revision 1.9  2004/10/05 20:08:46  jalet
48# Misleading help message. Thx to Johannes Laemmermann.
49#
50# Revision 1.8  2004/10/05 09:59:19  jalet
51# Restore compatibility with Python 2.1
52#
53# Revision 1.7  2004/10/04 21:25:29  jalet
54# dumpykota can now output datas in the XML format
55#
56# Revision 1.6  2004/09/15 18:28:41  jalet
57# Updated help for dumpykota
58#
59# Revision 1.5  2004/09/15 07:38:05  jalet
60# Fix for uninitialized variable
61#
62# Revision 1.4  2004/09/15 07:26:19  jalet
63# Data dumps are now ordered by entry creation date if applicable.
64# Now dumpykota exits with a message when there's a broken pipe like
65# in dumpykota --data history | head -3
66#
67# Revision 1.3  2004/09/15 06:58:25  jalet
68# User groups membership and printer groups membership can now be dumped too
69#
70# Revision 1.2  2004/09/14 22:29:12  jalet
71# First version of dumpykota. Works fine but only with PostgreSQL backend
72# for now.
73#
74# Revision 1.1  2004/07/01 19:22:37  jalet
75# First draft of dumpykota
76#
77#
78#
79
80import sys
81import os
82import pwd
83
84try :
85    import jaxml
86except ImportError :   
87    sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n")
88    sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n")
89    hasJAXML = 0
90else :   
91    hasJAXML = 1
92
93from pykota import version
94from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
95from pykota.config import PyKotaConfigError
96from pykota.storage import PyKotaStorageError
97
98__doc__ = N_("""dumpykota v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
99
100Dumps PyKota database's content.
101
102command line usage :
103
104  dumpykota [options]
105
106options :
107
108  -v | --version       Prints dumpykota's version number then exits.
109  -h | --help          Prints this message then exits.
110 
111  -d | --data type     Dumps 'type' datas. Allowed types are :
112                       
113                         - history : dumps the jobs history.
114                         - users : dumps users.
115                         - groups : dumps user groups.
116                         - printers : dump printers.
117                         - upquotas : dump user quotas.
118                         - gpquotas : dump user groups quotas.
119                         - payments : dumps user payments.
120                         - pmembers : dumps printer groups members.
121                         - umembers : dumps user groups members.
122                         
123                       NB : the -d | --data command line option   
124                       is MANDATORY.
125 
126  -f | --format fmt    Dumps datas in the 'fmt' format. When not specified,
127                       the format is to dump datas in the csv format (comma
128                       separated values). All data dumped is between double
129                       quotes. Allowed formats are :
130                       
131                         - csv : separate datas with commas
132                         - ssv : separate datas with semicolons
133                         - tsv : separate datas with tabs
134                         - xml : dump data as XML
135                         
136  -o | --output fname  All datas will be dumped to the file instead of
137                       to the standard output. The special '-' filename
138                       is the default value and means stdout.
139                       WARNING : existing files are truncated !
140 
141Examples :
142
143  $ dumpykota --data history --format csv >myfile.csv
144 
145  This dumps the history in a comma separated values file, for possible
146  use in a spreadsheet.
147 
148  $ dumpykota --data users --format xml -o users.xml
149 
150  Dumps all users datas to the users.xml file.
151 
152This program is free software; you can redistribute it and/or modify
153it under the terms of the GNU General Public License as published by
154the Free Software Foundation; either version 2 of the License, or
155(at your option) any later version.
156
157This program is distributed in the hope that it will be useful,
158but WITHOUT ANY WARRANTY; without even the implied warranty of
159MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
160GNU General Public License for more details.
161
162You should have received a copy of the GNU General Public License
163along with this program; if not, write to the Free Software
164Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
165
166Please e-mail bugs to: %s""")
167       
168class DumPyKota(PyKotaTool) :       
169    """A class for dumpykota."""
170    def main(self, arguments, options) :
171        """Print Quota Data Dumper."""
172        if not self.config.isAdmin :
173            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
174           
175        datatype = options["data"]
176        if datatype not in [ "history",
177                             "users",
178                             "groups",
179                             "printers",
180                             "upquotas",
181                             "gpquotas",
182                             "payments",
183                             "pmembers",
184                             "umembers",
185                           ] :
186            raise PyKotaToolError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype
187                   
188        format = options["format"]
189        if format not in [ "csv",
190                           "ssv",
191                           "tsv",
192                           "xml",
193                         ] :
194            raise PyKotaToolError, _("Invalid modifier [%s] for --format command line option, see help.") % datatype
195           
196        if (format == "xml") and not hasJAXML :
197            raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.")
198           
199        entries = getattr(self.storage, "extract%s" % datatype.title())()   
200        if entries :
201            mustclose = 0   
202            if options["output"].strip() == "-" :   
203                self.outfile = sys.stdout
204            else :   
205                self.outfile = open(options["output"], "w")
206                mustclose = 1
207               
208            retcode = getattr(self, "dump%s" % format.title())(entries, datatype)
209           
210            if mustclose :
211                self.outfile.close()
212               
213            return retcode   
214        return 0
215       
216    def dumpWithSeparator(self, separator, entries) :   
217        """Dumps datas with a separator."""
218        for entry in entries :
219            line = separator.join([ '"%s"' % field for field in entry ])
220            try :
221                self.outfile.write("%s\n" % line)
222            except IOError, msg :   
223                sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg))
224                return -1
225        return 0       
226       
227    def dumpCsv(self, entries, dummy) :   
228        """Dumps datas with a comma as the separator."""
229        return self.dumpWithSeparator(",", entries)
230                           
231    def dumpSsv(self, entries, dummy) :   
232        """Dumps datas with a comma as the separator."""
233        return self.dumpWithSeparator(";", entries)
234                           
235    def dumpTsv(self, entries, dummy) :   
236        """Dumps datas with a comma as the separator."""
237        return self.dumpWithSeparator("\t", entries)
238       
239    def dumpXml(self, entries, datatype) :   
240        """Dumps datas as XML."""
241        x = jaxml.XML_document(encoding="UTF-8")
242        x.pykota(version=version.__version__, author=version.__author__)
243        x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype)
244        headers = entries[0]
245        for entry in entries[1:] :
246            x._push()
247            x.entry()
248            for i in range(len(entry)) :
249                value = str(entry[i])
250                try :
251                    value = unicode(value, self.getCharset()).encode("UTF-8")
252                except UnicodeError :   
253                    pass
254                x.attribute(value, type=type(value).__name__, name=headers[i])
255            x._pop()   
256        x._output(self.outfile)
257                           
258if __name__ == "__main__" : 
259    retcode = 0
260    try :
261        defaults = { \
262                     "format" : "csv", \
263                     "output" : "-", \
264                   }
265        short_options = "vhd:f:o:"
266        long_options = ["help", "version", "data=", "format=", "output="]
267       
268        # Initializes the command line tool
269        dumper = DumPyKota(doc=__doc__)
270       
271        # parse and checks the command line
272        (options, args) = dumper.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
273       
274        # sets long options
275        options["help"] = options["h"] or options["help"]
276        options["version"] = options["v"] or options["version"]
277        options["data"] = options["d"] or options["data"]
278        options["format"] = options["f"] or options["format"] or defaults["format"]
279        options["output"] = options["o"] or options["output"] or defaults["output"]
280       
281        if options["help"] :
282            dumper.display_usage_and_quit()
283        elif options["version"] :
284            dumper.display_version_and_quit()
285        elif options["data"] is None :   
286            raise PyKotaToolError, _("The -d | --data command line option is mandatory, see help.")
287        else :
288            if args :
289                raise PyKotaToolError, _("Too many arguments, see help.")
290            retcode = dumper.main(args, options)
291    except SystemExit :       
292        pass
293    except :
294        try :
295            dumper.crashed("dumpykota failed")
296        except :   
297            crashed("dumpykota failed")
298        retcode = -1
299
300    try :
301        dumper.storage.close()
302    except (TypeError, NameError, AttributeError) :   
303        pass
304       
305    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.