root / pykota / trunk / bin / dumpykota @ 1790

Revision 1790, 11.0 kB (checked in by jalet, 20 years ago)

Hopefully final fix for data encoding to and from the database

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