root / pykota / trunk / bin / dumpykota @ 1990

Revision 1990, 13.4 kB (checked in by jalet, 19 years ago)

Prepared dumpykota to accept the new --filter command line option. Some
additionnal work needs to be done in the backends though.

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