root / pykota / trunk / bin / dumpykota @ 1777

Revision 1777, 10.2 kB (checked in by jalet, 20 years ago)

Restore compatibility with Python 2.1

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