1 | # PyKota Print Quota Data Dumper |
---|
2 | # |
---|
3 | # PyKota - Print Quotas for CUPS and LPRng |
---|
4 | # |
---|
5 | # (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com> |
---|
6 | # This program is free software; you can redistribute it and/or modify |
---|
7 | # it under the terms of the GNU General Public License as published by |
---|
8 | # the Free Software Foundation; either version 2 of the License, or |
---|
9 | # (at your option) any later version. |
---|
10 | # |
---|
11 | # This program is distributed in the hope that it will be useful, |
---|
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
14 | # GNU General Public License for more details. |
---|
15 | # |
---|
16 | # You should have received a copy of the GNU General Public License |
---|
17 | # along with this program; if not, write to the Free Software |
---|
18 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
19 | # |
---|
20 | # $Id$ |
---|
21 | # |
---|
22 | # |
---|
23 | |
---|
24 | import sys |
---|
25 | import os |
---|
26 | import pwd |
---|
27 | from xml.sax import saxutils |
---|
28 | |
---|
29 | from mx import DateTime |
---|
30 | |
---|
31 | try : |
---|
32 | import jaxml |
---|
33 | except ImportError : |
---|
34 | sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n") |
---|
35 | sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n") |
---|
36 | hasJAXML = 0 |
---|
37 | else : |
---|
38 | hasJAXML = 1 |
---|
39 | |
---|
40 | from pykota import version |
---|
41 | from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, N_ |
---|
42 | |
---|
43 | class DumPyKota(PyKotaTool) : |
---|
44 | """A class for dumpykota.""" |
---|
45 | validdatatypes = { "history" : N_("History"), |
---|
46 | "users" : N_("Users"), |
---|
47 | "groups" : N_("Groups"), |
---|
48 | "printers" : N_("Printers"), |
---|
49 | "upquotas" : N_("Users Print Quotas"), |
---|
50 | "gpquotas" : N_("Users Groups Print Quotas"), |
---|
51 | "payments" : N_("History of Payments"), |
---|
52 | "pmembers" : N_("Printers Groups Membership"), |
---|
53 | "umembers" : N_("Users Groups Membership"), |
---|
54 | "billingcodes" : N_("Billing Codes"), |
---|
55 | "all": N_("All"), |
---|
56 | } |
---|
57 | validformats = { "csv" : N_("Comma Separated Values"), |
---|
58 | "ssv" : N_("Semicolon Separated Values"), |
---|
59 | "tsv" : N_("Tabulation Separated Values"), |
---|
60 | "xml" : N_("eXtensible Markup Language"), |
---|
61 | "cups" : N_("CUPS' page_log"), |
---|
62 | } |
---|
63 | validfilterkeys = [ "username", |
---|
64 | "groupname", |
---|
65 | "printername", |
---|
66 | "pgroupname", |
---|
67 | "hostname", |
---|
68 | "billingcode", |
---|
69 | "start", |
---|
70 | "end", |
---|
71 | ] |
---|
72 | def main(self, arguments, options, restricted=1) : |
---|
73 | """Print Quota Data Dumper.""" |
---|
74 | if restricted and not self.config.isAdmin : |
---|
75 | raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command.")) |
---|
76 | |
---|
77 | datatype = options["data"] |
---|
78 | if datatype not in self.validdatatypes.keys() : |
---|
79 | raise PyKotaCommandLineError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype |
---|
80 | |
---|
81 | extractonly = {} |
---|
82 | if datatype == "all" : |
---|
83 | if (options["format"] != "xml") or options["sum"] or arguments : |
---|
84 | self.printInfo(_("Dumping all PyKota's datas forces format to XML, and disables --sum and filters."), "warn") |
---|
85 | options["format"] = "xml" |
---|
86 | options["sum"] = None |
---|
87 | else : |
---|
88 | for filterexp in arguments : |
---|
89 | if filterexp.strip() : |
---|
90 | try : |
---|
91 | (filterkey, filtervalue) = [part.strip() for part in filterexp.split("=")] |
---|
92 | if filterkey not in self.validfilterkeys : |
---|
93 | raise ValueError |
---|
94 | except ValueError : |
---|
95 | raise PyKotaCommandLineError, _("Invalid filter value [%s], see help.") % filterexp |
---|
96 | else : |
---|
97 | extractonly.update({ filterkey : filtervalue }) |
---|
98 | |
---|
99 | format = options["format"] |
---|
100 | if (format not in self.validformats.keys()) \ |
---|
101 | or ((format == "cups") \ |
---|
102 | and ((datatype != "history") or options["sum"])) : |
---|
103 | raise PyKotaCommandLineError, _("Invalid modifier [%s] for --format command line option, see help.") % format |
---|
104 | |
---|
105 | if (format == "xml") and not hasJAXML : |
---|
106 | raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.") |
---|
107 | |
---|
108 | if options["sum"] and datatype not in ("payments", "history") : |
---|
109 | raise PyKotaCommandLineError, _("Invalid data type [%s] for --sum command line option, see help.") % datatype |
---|
110 | |
---|
111 | |
---|
112 | retcode = 0 |
---|
113 | nbentries = 0 |
---|
114 | mustclose = 0 |
---|
115 | if options["output"].strip() == "-" : |
---|
116 | self.outfile = sys.stdout |
---|
117 | else : |
---|
118 | self.outfile = open(options["output"], "w") |
---|
119 | mustclose = 1 |
---|
120 | |
---|
121 | if datatype == "all" : |
---|
122 | # NB : order does matter to allow easier or faster restore |
---|
123 | allentries = [] |
---|
124 | datatypes = [ "printers", "pmembers", "users", "groups", \ |
---|
125 | "billingcodes", "umembers", "upquotas", \ |
---|
126 | "gpquotas", "payments", "history" ] |
---|
127 | neededdatatypes = datatypes[:] |
---|
128 | for datatype in datatypes : |
---|
129 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) |
---|
130 | if entries : |
---|
131 | nbentries += len(entries) |
---|
132 | allentries.append(entries) |
---|
133 | else : |
---|
134 | neededdatatypes.remove(datatype) |
---|
135 | retcode = self.dumpXml(allentries, neededdatatypes) |
---|
136 | else : |
---|
137 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) |
---|
138 | if entries : |
---|
139 | nbentries = len(entries) |
---|
140 | retcode = getattr(self, "dump%s" % format.title())([self.summarizeDatas(entries, datatype, extractonly, options["sum"])], [datatype]) |
---|
141 | |
---|
142 | if mustclose : |
---|
143 | self.outfile.close() |
---|
144 | if not nbentries : |
---|
145 | os.remove(options["output"]) |
---|
146 | |
---|
147 | return retcode |
---|
148 | |
---|
149 | def summarizeDatas(self, entries, datatype, extractonly, sum=0) : |
---|
150 | """Transforms the datas into a summarized view (with totals). |
---|
151 | |
---|
152 | If sum is false, returns the entries unchanged. |
---|
153 | """ |
---|
154 | if not sum : |
---|
155 | return entries |
---|
156 | else : |
---|
157 | headers = entries[0] |
---|
158 | nbheaders = len(headers) |
---|
159 | fieldnumber = {} |
---|
160 | fieldname = {} |
---|
161 | for i in range(nbheaders) : |
---|
162 | fieldnumber[headers[i]] = i |
---|
163 | |
---|
164 | if datatype == "payments" : |
---|
165 | totalize = [ ("amount", float) ] |
---|
166 | keys = [ "username" ] |
---|
167 | else : # elif datatype == "history" |
---|
168 | totalize = [ ("jobsize", int), |
---|
169 | ("jobprice", float), |
---|
170 | ("jobsizebytes", int), |
---|
171 | ("precomputedjobsize", int), |
---|
172 | ("precomputedjobprice", float), |
---|
173 | ] |
---|
174 | keys = [ k for k in ("username", "printername", "hostname", "billingcode") if k in extractonly.keys() ] |
---|
175 | |
---|
176 | newentries = [ headers ] |
---|
177 | sortedentries = entries[1:] |
---|
178 | if keys : |
---|
179 | # If we have several keys, we can sort only on the first one, because they |
---|
180 | # will vary the same way. |
---|
181 | sortedentries.sort(lambda x, y, fnum=fieldnumber[keys[0]] : cmp(x[fnum], y[fnum])) |
---|
182 | totals = {} |
---|
183 | for (k, t) in totalize : |
---|
184 | totals[k] = { "convert" : t, "value" : 0.0 } |
---|
185 | prevkeys = {} |
---|
186 | for k in keys : |
---|
187 | prevkeys[k] = sortedentries[0][fieldnumber[k]] |
---|
188 | for entry in sortedentries : |
---|
189 | curval = '-'.join([str(entry[fieldnumber[k]]) for k in keys]) |
---|
190 | prevval = '-'.join([str(prevkeys[k]) for k in keys]) |
---|
191 | if curval != prevval : |
---|
192 | summary = [ "*" ] * nbheaders |
---|
193 | for k in keys : |
---|
194 | summary[fieldnumber[k]] = prevkeys[k] |
---|
195 | for k in totals.keys() : |
---|
196 | summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) |
---|
197 | newentries.append(summary) |
---|
198 | for k in totals.keys() : |
---|
199 | totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]]) |
---|
200 | else : |
---|
201 | for k in totals.keys() : |
---|
202 | totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]] or 0.0) |
---|
203 | for k in keys : |
---|
204 | prevkeys[k] = entry[fieldnumber[k]] |
---|
205 | summary = [ "*" ] * nbheaders |
---|
206 | for k in keys : |
---|
207 | summary[fieldnumber[k]] = prevkeys[k] |
---|
208 | for k in totals.keys() : |
---|
209 | summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) |
---|
210 | newentries.append(summary) |
---|
211 | return newentries |
---|
212 | |
---|
213 | def dumpWithSeparator(self, separator, allentries) : |
---|
214 | """Dumps datas with a separator.""" |
---|
215 | for entries in allentries : |
---|
216 | for entry in entries : |
---|
217 | line = [] |
---|
218 | for value in entry : |
---|
219 | if type(value).__name__ in ("str", "NoneType") : |
---|
220 | line.append('"%s"' % str(value).replace(separator, "\\%s" % separator).replace('"', '\\"')) |
---|
221 | else : |
---|
222 | line.append(str(value)) |
---|
223 | try : |
---|
224 | self.outfile.write("%s\n" % separator.join(line)) |
---|
225 | except IOError, msg : |
---|
226 | sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg)) |
---|
227 | return -1 |
---|
228 | return 0 |
---|
229 | |
---|
230 | def dumpCsv(self, allentries, dummy) : |
---|
231 | """Dumps datas with a comma as the separator.""" |
---|
232 | return self.dumpWithSeparator(",", allentries) |
---|
233 | |
---|
234 | def dumpSsv(self, allentries, dummy) : |
---|
235 | """Dumps datas with a comma as the separator.""" |
---|
236 | return self.dumpWithSeparator(";", allentries) |
---|
237 | |
---|
238 | def dumpTsv(self, allentries, dummy) : |
---|
239 | """Dumps datas with a comma as the separator.""" |
---|
240 | return self.dumpWithSeparator("\t", allentries) |
---|
241 | |
---|
242 | def dumpCups(self, allentries, dummy) : |
---|
243 | """Dumps history datas as CUPS' page_log format.""" |
---|
244 | entries = allentries[0] |
---|
245 | fieldnames = entries[0] |
---|
246 | fields = {} |
---|
247 | for i in range(len(fieldnames)) : |
---|
248 | fields[fieldnames[i]] = i |
---|
249 | sortindex = fields["jobdate"] |
---|
250 | entries = entries[1:] |
---|
251 | entries.sort(lambda m, n, si=sortindex : cmp(m[si], n[si])) |
---|
252 | for entry in entries : |
---|
253 | printername = entry[fields["printername"]] |
---|
254 | username = entry[fields["username"]] |
---|
255 | jobid = entry[fields["jobid"]] |
---|
256 | jobdate = DateTime.ISO.ParseDateTime(str(entry[fields["jobdate"]])) |
---|
257 | gmtoffset = jobdate.gmtoffset() |
---|
258 | jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour) |
---|
259 | jobsize = entry[fields["jobsize"]] or 0 |
---|
260 | copies = entry[fields["copies"]] or 1 |
---|
261 | hostname = entry[fields["hostname"]] or "" |
---|
262 | billingcode = entry[fields["billingcode"]] or "-" |
---|
263 | for pagenum in range(1, jobsize+1) : |
---|
264 | self.outfile.write("%s %s %s [%s] %s %s %s %s\n" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname)) |
---|
265 | return 0 |
---|
266 | |
---|
267 | def dumpXml(self, allentries, datatypes) : |
---|
268 | """Dumps datas as XML.""" |
---|
269 | x = jaxml.XML_document(encoding="UTF-8") |
---|
270 | x.pykota(version=version.__version__, author=version.__author__) |
---|
271 | for (entries, datatype) in zip(allentries, datatypes) : |
---|
272 | x._push() |
---|
273 | x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype) |
---|
274 | headers = entries[0] |
---|
275 | for entry in entries[1:] : |
---|
276 | x._push() |
---|
277 | x.entry() |
---|
278 | for (header, value) in zip(headers, entry) : |
---|
279 | strvalue = str(value) |
---|
280 | typval = type(value).__name__ |
---|
281 | if header in ("filename", "title", "options", "billingcode") \ |
---|
282 | and (typval == "str") : |
---|
283 | try : |
---|
284 | strvalue = unicode(strvalue, self.getCharset()).encode("UTF-8") |
---|
285 | except UnicodeError : |
---|
286 | pass |
---|
287 | strvalue = saxutils.escape(strvalue, { "'" : "'", \ |
---|
288 | '"' : """ }) |
---|
289 | x.attribute(strvalue, type=typval, name=header) |
---|
290 | x._pop() |
---|
291 | x._pop() |
---|
292 | x._output(self.outfile) |
---|
293 | return 0 |
---|