root / pykota / trunk / bin / dumpykota @ 1789

Revision 1789, 10.8 kB (checked in by jalet, 20 years ago)

Now edpykota refuses to launch if the user is not a PyKota administrator.
dumpykota : now has the same error message than edpykota in this case.

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