root / pykota / trunk / bin / dumpykota @ 1785

Revision 1785, 10.6 kB (checked in by jalet, 20 years ago)

Minor changes to allow any PyKota administrator to launch enhanced versions
of the commands, and not only the root user.

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