[2016] | 1 | # PyKota Print Quota Data Dumper |
---|
| 2 | # |
---|
| 3 | # PyKota - Print Quotas for CUPS and LPRng |
---|
| 4 | # |
---|
| 5 | # (c) 2003-2004 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 |
---|
[2302] | 18 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
---|
[2016] | 19 | # |
---|
| 20 | # $Id$ |
---|
| 21 | # |
---|
[2034] | 22 | # |
---|
[2016] | 23 | |
---|
| 24 | import sys |
---|
| 25 | import os |
---|
| 26 | import pwd |
---|
[2264] | 27 | from xml.sax import saxutils |
---|
| 28 | |
---|
[2016] | 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 |
---|
[2512] | 41 | from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, N_ |
---|
[2016] | 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"), |
---|
[2342] | 54 | "billingcodes" : N_("Billing Codes"), |
---|
[2600] | 55 | "all": N_("All"), |
---|
[2016] | 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", |
---|
[2218] | 67 | "hostname", |
---|
| 68 | "billingcode", |
---|
[2266] | 69 | "start", |
---|
| 70 | "end", |
---|
[2016] | 71 | ] |
---|
[2032] | 72 | def main(self, arguments, options, restricted=1) : |
---|
[2016] | 73 | """Print Quota Data Dumper.""" |
---|
[2032] | 74 | if restricted and not self.config.isAdmin : |
---|
[2512] | 75 | raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command.")) |
---|
[2016] | 76 | |
---|
| 77 | datatype = options["data"] |
---|
| 78 | if datatype not in self.validdatatypes.keys() : |
---|
[2512] | 79 | raise PyKotaCommandLineError, _("Invalid modifier [%s] for --data command line option, see help.") % datatype |
---|
[2016] | 80 | |
---|
[2600] | 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 | |
---|
[2016] | 99 | format = options["format"] |
---|
[2567] | 100 | if (format not in self.validformats.keys()) \ |
---|
| 101 | or ((format == "cups") \ |
---|
| 102 | and ((datatype != "history") or options["sum"])) : |
---|
[2512] | 103 | raise PyKotaCommandLineError, _("Invalid modifier [%s] for --format command line option, see help.") % format |
---|
[2016] | 104 | |
---|
| 105 | if (format == "xml") and not hasJAXML : |
---|
| 106 | raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.") |
---|
| 107 | |
---|
[2285] | 108 | if options["sum"] and datatype not in ("payments", "history") : |
---|
[2512] | 109 | raise PyKotaCommandLineError, _("Invalid data type [%s] for --sum command line option, see help.") % datatype |
---|
[2285] | 110 | |
---|
[2600] | 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 | for datatype in datatypes : |
---|
| 128 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) |
---|
| 129 | nbentries += len(entries) |
---|
| 130 | allentries.append(entries) |
---|
| 131 | retcode = self.dumpXml(allentries, datatypes) |
---|
| 132 | |
---|
| 133 | else : |
---|
| 134 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) |
---|
| 135 | if entries : |
---|
| 136 | nbentries = len(entries) |
---|
| 137 | retcode = getattr(self, "dump%s" % format.title())([self.summarizeDatas(entries, datatype, extractonly, options["sum"])], [datatype]) |
---|
[2016] | 138 | |
---|
[2600] | 139 | if mustclose : |
---|
| 140 | self.outfile.close() |
---|
| 141 | if not nbentries : |
---|
| 142 | os.remove(options["output"]) |
---|
[2016] | 143 | |
---|
[2600] | 144 | return retcode |
---|
[2016] | 145 | |
---|
[2295] | 146 | def summarizeDatas(self, entries, datatype, extractonly, sum=0) : |
---|
[2285] | 147 | """Transforms the datas into a summarized view (with totals). |
---|
| 148 | |
---|
| 149 | If sum is false, returns the entries unchanged. |
---|
| 150 | """ |
---|
| 151 | if not sum : |
---|
| 152 | return entries |
---|
| 153 | else : |
---|
[2289] | 154 | headers = entries[0] |
---|
| 155 | nbheaders = len(headers) |
---|
| 156 | fieldnumber = {} |
---|
[2293] | 157 | fieldname = {} |
---|
[2289] | 158 | for i in range(nbheaders) : |
---|
[2295] | 159 | fieldnumber[headers[i]] = i |
---|
| 160 | |
---|
[2289] | 161 | if datatype == "payments" : |
---|
[2293] | 162 | totalize = [ ("amount", float) ] |
---|
[2295] | 163 | keys = [ "username" ] |
---|
| 164 | else : # elif datatype == "history" |
---|
| 165 | totalize = [ ("jobsize", int), |
---|
| 166 | ("jobprice", float), |
---|
| 167 | ("jobsizebytes", int), |
---|
| 168 | ] |
---|
| 169 | keys = [ k for k in ("username", "printername", "hostname", "billingcode") if k in extractonly.keys() ] |
---|
[2293] | 170 | |
---|
[2295] | 171 | newentries = [ headers ] |
---|
| 172 | sortedentries = entries[1:] |
---|
| 173 | if keys : |
---|
| 174 | # If we have several keys, we can sort only on the first one, because they |
---|
| 175 | # will vary the same way. |
---|
| 176 | sortedentries.sort(lambda x, y, fnum=fieldnumber[keys[0]] : cmp(x[fnum], y[fnum])) |
---|
| 177 | totals = {} |
---|
| 178 | for (k, t) in totalize : |
---|
| 179 | totals[k] = { "convert" : t, "value" : 0.0 } |
---|
| 180 | prevkeys = {} |
---|
| 181 | for k in keys : |
---|
| 182 | prevkeys[k] = sortedentries[0][fieldnumber[k]] |
---|
| 183 | for entry in sortedentries : |
---|
| 184 | curval = '-'.join([str(entry[fieldnumber[k]]) for k in keys]) |
---|
| 185 | prevval = '-'.join([str(prevkeys[k]) for k in keys]) |
---|
| 186 | if curval != prevval : |
---|
| 187 | summary = [ "*" ] * nbheaders |
---|
| 188 | for k in keys : |
---|
| 189 | summary[fieldnumber[k]] = prevkeys[k] |
---|
| 190 | for k in totals.keys() : |
---|
| 191 | summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) |
---|
| 192 | newentries.append(summary) |
---|
| 193 | for k in totals.keys() : |
---|
| 194 | totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]]) |
---|
| 195 | else : |
---|
| 196 | for k in totals.keys() : |
---|
| 197 | totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]]) |
---|
| 198 | for k in keys : |
---|
| 199 | prevkeys[k] = entry[fieldnumber[k]] |
---|
| 200 | summary = [ "*" ] * nbheaders |
---|
| 201 | for k in keys : |
---|
| 202 | summary[fieldnumber[k]] = prevkeys[k] |
---|
| 203 | for k in totals.keys() : |
---|
| 204 | summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) |
---|
| 205 | newentries.append(summary) |
---|
[2289] | 206 | return newentries |
---|
[2285] | 207 | |
---|
[2600] | 208 | def dumpWithSeparator(self, separator, allentries) : |
---|
[2016] | 209 | """Dumps datas with a separator.""" |
---|
[2600] | 210 | for entries in allentries : |
---|
| 211 | for entry in entries : |
---|
| 212 | line = [] |
---|
| 213 | for value in entry : |
---|
| 214 | if type(value).__name__ in ("str", "NoneType") : |
---|
| 215 | line.append('"%s"' % str(value).replace(separator, "\\%s" % separator).replace('"', '\\"')) |
---|
| 216 | else : |
---|
| 217 | line.append(str(value)) |
---|
| 218 | try : |
---|
| 219 | self.outfile.write("%s\n" % separator.join(line)) |
---|
| 220 | except IOError, msg : |
---|
| 221 | sys.stderr.write("%s : %s\n" % (_("PyKota data dumper failed : I/O error"), msg)) |
---|
| 222 | return -1 |
---|
[2016] | 223 | return 0 |
---|
| 224 | |
---|
[2600] | 225 | def dumpCsv(self, allentries, dummy) : |
---|
[2016] | 226 | """Dumps datas with a comma as the separator.""" |
---|
[2600] | 227 | return self.dumpWithSeparator(",", allentries) |
---|
[2016] | 228 | |
---|
[2600] | 229 | def dumpSsv(self, allentries, dummy) : |
---|
[2016] | 230 | """Dumps datas with a comma as the separator.""" |
---|
[2600] | 231 | return self.dumpWithSeparator(";", allentries) |
---|
[2016] | 232 | |
---|
[2600] | 233 | def dumpTsv(self, allentries, dummy) : |
---|
[2016] | 234 | """Dumps datas with a comma as the separator.""" |
---|
[2600] | 235 | return self.dumpWithSeparator("\t", allentries) |
---|
[2016] | 236 | |
---|
[2600] | 237 | def dumpCups(self, allentries, dummy) : |
---|
[2016] | 238 | """Dumps history datas as CUPS' page_log format.""" |
---|
[2600] | 239 | entries = allentries[0] |
---|
[2016] | 240 | fieldnames = entries[0] |
---|
| 241 | fields = {} |
---|
| 242 | for i in range(len(fieldnames)) : |
---|
| 243 | fields[fieldnames[i]] = i |
---|
| 244 | sortindex = fields["jobdate"] |
---|
| 245 | entries = entries[1:] |
---|
[2034] | 246 | entries.sort(lambda m,n,si=sortindex : cmp(m[si], n[si])) |
---|
[2219] | 247 | for entry in entries : |
---|
[2016] | 248 | printername = entry[fields["printername"]] |
---|
| 249 | username = entry[fields["username"]] |
---|
| 250 | jobid = entry[fields["jobid"]] |
---|
| 251 | jobdate = DateTime.ISO.ParseDateTime(entry[fields["jobdate"]]) |
---|
| 252 | gmtoffset = jobdate.gmtoffset() |
---|
| 253 | jobdate = "%s %+03i00" % (jobdate.strftime("%d/%b/%Y:%H:%M:%S"), gmtoffset.hour) |
---|
| 254 | jobsize = entry[fields["jobsize"]] or 0 |
---|
| 255 | copies = entry[fields["copies"]] or 1 |
---|
| 256 | hostname = entry[fields["hostname"]] or "" |
---|
[2217] | 257 | billingcode = entry[fields["billingcode"]] or "-" |
---|
[2163] | 258 | for pagenum in range(1, jobsize+1) : |
---|
[2217] | 259 | self.outfile.write("%s %s %s [%s] %s %s %s %s\n" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname)) |
---|
[2600] | 260 | return 0 |
---|
[2016] | 261 | |
---|
[2600] | 262 | def dumpXml(self, allentries, datatypes) : |
---|
[2016] | 263 | """Dumps datas as XML.""" |
---|
| 264 | x = jaxml.XML_document(encoding="UTF-8") |
---|
| 265 | x.pykota(version=version.__version__, author=version.__author__) |
---|
[2600] | 266 | for (entries, datatype) in zip(allentries, datatypes) : |
---|
[2016] | 267 | x._push() |
---|
[2600] | 268 | x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype) |
---|
| 269 | headers = entries[0] |
---|
| 270 | for entry in entries[1:] : |
---|
| 271 | x._push() |
---|
| 272 | x.entry() |
---|
| 273 | for (header, value) in zip(headers, entry) : |
---|
| 274 | strvalue = str(value) |
---|
| 275 | typval = type(value).__name__ |
---|
| 276 | if header in ("filename", "title", "options", "billingcode") \ |
---|
| 277 | and (typval == "str") : |
---|
| 278 | try : |
---|
| 279 | strvalue = unicode(strvalue, self.getCharset()).encode("UTF-8") |
---|
| 280 | except UnicodeError : |
---|
| 281 | pass |
---|
| 282 | strvalue = saxutils.escape(strvalue, { "'" : "'", \ |
---|
| 283 | '"' : """ }) |
---|
| 284 | x.attribute(strvalue, type=typval, name=header) |
---|
| 285 | x._pop() |
---|
[2016] | 286 | x._pop() |
---|
| 287 | x._output(self.outfile) |
---|
[2600] | 288 | return 0 |
---|