[3411] | 1 | # -*- coding: utf-8 -*-*- |
---|
[2016] | 2 | # |
---|
[3260] | 3 | # PyKota : Print Quotas for CUPS |
---|
[2016] | 4 | # |
---|
[3275] | 5 | # (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com> |
---|
[3260] | 6 | # This program is free software: you can redistribute it and/or modify |
---|
[2016] | 7 | # it under the terms of the GNU General Public License as published by |
---|
[3260] | 8 | # the Free Software Foundation, either version 3 of the License, or |
---|
[2016] | 9 | # (at your option) any later version. |
---|
[3413] | 10 | # |
---|
[2016] | 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. |
---|
[3413] | 15 | # |
---|
[2016] | 16 | # You should have received a copy of the GNU General Public License |
---|
[3260] | 17 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
---|
[2016] | 18 | # |
---|
| 19 | # $Id$ |
---|
| 20 | # |
---|
[2034] | 21 | # |
---|
[2016] | 22 | |
---|
[3184] | 23 | """This module handles all the data dumping facilities for PyKota.""" |
---|
| 24 | |
---|
[2016] | 25 | import sys |
---|
| 26 | import os |
---|
| 27 | import pwd |
---|
[2264] | 28 | from xml.sax import saxutils |
---|
| 29 | |
---|
[2016] | 30 | from mx import DateTime |
---|
| 31 | |
---|
| 32 | try : |
---|
| 33 | import jaxml |
---|
[3413] | 34 | except ImportError : |
---|
[2016] | 35 | sys.stderr.write("The jaxml Python module is not installed. XML output is disabled.\n") |
---|
| 36 | sys.stderr.write("Download jaxml from http://www.librelogiciel.com/software/ or from your Debian archive of choice\n") |
---|
[3288] | 37 | hasJAXML = False |
---|
[3413] | 38 | else : |
---|
[3288] | 39 | hasJAXML = True |
---|
[2016] | 40 | |
---|
[3295] | 41 | from pykota.utils import * |
---|
| 42 | |
---|
[2016] | 43 | from pykota import version |
---|
[3295] | 44 | from pykota.tool import PyKotaTool |
---|
[3288] | 45 | from pykota.errors import PyKotaToolError, PyKotaCommandLineError |
---|
[2016] | 46 | |
---|
[3413] | 47 | class DumPyKota(PyKotaTool) : |
---|
[2016] | 48 | """A class for dumpykota.""" |
---|
[3368] | 49 | validdatatypes = { u"history" : N_("History"), |
---|
| 50 | u"users" : N_("Users"), |
---|
| 51 | u"groups" : N_("Groups"), |
---|
| 52 | u"printers" : N_("Printers"), |
---|
| 53 | u"upquotas" : N_("Users Print Quotas"), |
---|
| 54 | u"gpquotas" : N_("Users Groups Print Quotas"), |
---|
| 55 | u"payments" : N_("History of Payments"), |
---|
[3413] | 56 | u"pmembers" : N_("Printers Groups Membership"), |
---|
[3368] | 57 | u"umembers" : N_("Users Groups Membership"), |
---|
| 58 | u"billingcodes" : N_("Billing Codes"), |
---|
| 59 | u"all": N_("All"), |
---|
[2016] | 60 | } |
---|
[3368] | 61 | validformats = { u"csv" : N_("Comma Separated Values"), |
---|
| 62 | u"ssv" : N_("Semicolon Separated Values"), |
---|
| 63 | u"tsv" : N_("Tabulation Separated Values"), |
---|
| 64 | u"xml" : N_("eXtensible Markup Language"), |
---|
| 65 | u"cups" : N_("CUPS' page_log"), |
---|
[3413] | 66 | } |
---|
[2016] | 67 | validfilterkeys = [ "username", |
---|
| 68 | "groupname", |
---|
| 69 | "printername", |
---|
| 70 | "pgroupname", |
---|
[2218] | 71 | "hostname", |
---|
| 72 | "billingcode", |
---|
[3413] | 73 | "jobid", |
---|
[2266] | 74 | "start", |
---|
| 75 | "end", |
---|
[2016] | 76 | ] |
---|
[3368] | 77 | def main(self, arguments, options, restricted=True) : |
---|
[2016] | 78 | """Print Quota Data Dumper.""" |
---|
[3368] | 79 | self.adminOnly(restricted) |
---|
[3413] | 80 | |
---|
[3368] | 81 | datatype = options.data |
---|
[2016] | 82 | if datatype not in self.validdatatypes.keys() : |
---|
[3368] | 83 | raise PyKotaCommandLineError, _("Invalid data type '%(datatype)s', see help.") % locals() |
---|
[3413] | 84 | |
---|
[3368] | 85 | orderby = options.orderby or [] |
---|
[3165] | 86 | if orderby : |
---|
| 87 | fields = [f.strip() for f in orderby.split(",")] |
---|
| 88 | orderby = [] |
---|
| 89 | for field in fields : |
---|
| 90 | if field.isalpha() \ |
---|
| 91 | or ((field[0] in ("+", "-")) and field[1:].isalpha()) : |
---|
| 92 | orderby.append(field) |
---|
[3413] | 93 | else : |
---|
[3368] | 94 | logerr(_("Skipping invalid ordering statement '%(field)s'") % locals()) |
---|
[3413] | 95 | |
---|
[2600] | 96 | extractonly = {} |
---|
[3413] | 97 | if datatype == u"all" : |
---|
[3368] | 98 | if (options.format != u"xml") or options.sum or arguments : |
---|
[2600] | 99 | self.printInfo(_("Dumping all PyKota's datas forces format to XML, and disables --sum and filters."), "warn") |
---|
[3368] | 100 | options.format = u"xml" |
---|
| 101 | options.sum = None |
---|
[3413] | 102 | else : |
---|
[2600] | 103 | for filterexp in arguments : |
---|
| 104 | if filterexp.strip() : |
---|
| 105 | try : |
---|
| 106 | (filterkey, filtervalue) = [part.strip() for part in filterexp.split("=")] |
---|
[3368] | 107 | filterkey = filterkey.encode("ASCII", "replace").lower() |
---|
[2600] | 108 | if filterkey not in self.validfilterkeys : |
---|
[3413] | 109 | raise ValueError |
---|
| 110 | except ValueError : |
---|
[3368] | 111 | raise PyKotaCommandLineError, _("Invalid filter value '%(filterexp)s', see help.") % locals() |
---|
[3413] | 112 | else : |
---|
[2600] | 113 | extractonly.update({ filterkey : filtervalue }) |
---|
[3413] | 114 | |
---|
[3368] | 115 | format = options.format |
---|
[2567] | 116 | if (format not in self.validformats.keys()) \ |
---|
[3368] | 117 | or ((format == u"cups") \ |
---|
| 118 | and ((datatype != u"history") or options.sum)) : |
---|
| 119 | raise PyKotaCommandLineError, _("Invalid format '%(format)s', see help.") % locals() |
---|
[3413] | 120 | |
---|
[3368] | 121 | if (format == u"xml") and not hasJAXML : |
---|
[2016] | 122 | raise PyKotaToolError, _("XML output is disabled because the jaxml module is not available.") |
---|
[3413] | 123 | |
---|
| 124 | if datatype not in (u"payments", u"history") : |
---|
| 125 | if options.sum : |
---|
[3368] | 126 | raise PyKotaCommandLineError, _("Invalid data type '%(datatype)s' for --sum command line option, see help.") % locals() |
---|
[3413] | 127 | if extractonly.has_key(u"start") or extractonly.has_key(u"end") : |
---|
[3368] | 128 | self.printInfo(_("Invalid filter for the '%(datatype)s' data type.") % locals(), "warn") |
---|
[3142] | 129 | try : |
---|
[3368] | 130 | del extractonly[u"start"] |
---|
[3413] | 131 | except KeyError : |
---|
[3142] | 132 | pass |
---|
| 133 | try : |
---|
[3368] | 134 | del extractonly[u"end"] |
---|
[3413] | 135 | except KeyError : |
---|
[3142] | 136 | pass |
---|
[3413] | 137 | |
---|
[2600] | 138 | retcode = 0 |
---|
[3413] | 139 | nbentries = 0 |
---|
[3368] | 140 | mustclose = False |
---|
| 141 | outfname = options.output.strip().encode(sys.getfilesystemencoding()) |
---|
[3413] | 142 | if outfname == "-" : |
---|
[2600] | 143 | self.outfile = sys.stdout |
---|
[3413] | 144 | else : |
---|
[3368] | 145 | self.outfile = open(outfname, "w") |
---|
| 146 | mustclose = True |
---|
[3413] | 147 | |
---|
| 148 | if datatype == u"all" : |
---|
[2600] | 149 | # NB : order does matter to allow easier or faster restore |
---|
| 150 | allentries = [] |
---|
| 151 | datatypes = [ "printers", "pmembers", "users", "groups", \ |
---|
| 152 | "billingcodes", "umembers", "upquotas", \ |
---|
| 153 | "gpquotas", "payments", "history" ] |
---|
[3413] | 154 | neededdatatypes = datatypes[:] |
---|
[2600] | 155 | for datatype in datatypes : |
---|
[3166] | 156 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly) # We don't care about ordering here |
---|
[2601] | 157 | if entries : |
---|
| 158 | nbentries += len(entries) |
---|
| 159 | allentries.append(entries) |
---|
[3413] | 160 | else : |
---|
[2602] | 161 | neededdatatypes.remove(datatype) |
---|
| 162 | retcode = self.dumpXml(allentries, neededdatatypes) |
---|
[3413] | 163 | else : |
---|
[3368] | 164 | datatype = datatype.encode("ASCII") |
---|
| 165 | format = format.encode("ASCII") |
---|
[3165] | 166 | entries = getattr(self.storage, "extract%s" % datatype.title())(extractonly, orderby) |
---|
[2600] | 167 | if entries : |
---|
| 168 | nbentries = len(entries) |
---|
[3368] | 169 | retcode = getattr(self, "dump%s" % format.title())([self.summarizeDatas(entries, datatype, extractonly, options.sum)], [datatype]) |
---|
[3413] | 170 | |
---|
[2600] | 171 | if mustclose : |
---|
| 172 | self.outfile.close() |
---|
[3413] | 173 | if not nbentries : |
---|
[3368] | 174 | os.remove(options.output) |
---|
[3413] | 175 | |
---|
[2600] | 176 | return retcode |
---|
[3413] | 177 | |
---|
| 178 | def summarizeDatas(self, entries, datatype, extractonly, sum=0) : |
---|
[2285] | 179 | """Transforms the datas into a summarized view (with totals). |
---|
[3413] | 180 | |
---|
[2285] | 181 | If sum is false, returns the entries unchanged. |
---|
[3413] | 182 | """ |
---|
[2285] | 183 | if not sum : |
---|
| 184 | return entries |
---|
[3413] | 185 | else : |
---|
[2289] | 186 | headers = entries[0] |
---|
| 187 | nbheaders = len(headers) |
---|
| 188 | fieldnumber = {} |
---|
[2293] | 189 | fieldname = {} |
---|
[2289] | 190 | for i in range(nbheaders) : |
---|
[2295] | 191 | fieldnumber[headers[i]] = i |
---|
[3413] | 192 | |
---|
[2289] | 193 | if datatype == "payments" : |
---|
[2293] | 194 | totalize = [ ("amount", float) ] |
---|
[2295] | 195 | keys = [ "username" ] |
---|
| 196 | else : # elif datatype == "history" |
---|
[3413] | 197 | totalize = [ ("jobsize", int), |
---|
[2295] | 198 | ("jobprice", float), |
---|
| 199 | ("jobsizebytes", int), |
---|
[2664] | 200 | ("precomputedjobsize", int), |
---|
| 201 | ("precomputedjobprice", float), |
---|
[2295] | 202 | ] |
---|
| 203 | keys = [ k for k in ("username", "printername", "hostname", "billingcode") if k in extractonly.keys() ] |
---|
[3413] | 204 | |
---|
[2295] | 205 | newentries = [ headers ] |
---|
| 206 | sortedentries = entries[1:] |
---|
| 207 | if keys : |
---|
| 208 | # If we have several keys, we can sort only on the first one, because they |
---|
| 209 | # will vary the same way. |
---|
| 210 | sortedentries.sort(lambda x, y, fnum=fieldnumber[keys[0]] : cmp(x[fnum], y[fnum])) |
---|
| 211 | totals = {} |
---|
| 212 | for (k, t) in totalize : |
---|
| 213 | totals[k] = { "convert" : t, "value" : 0.0 } |
---|
| 214 | prevkeys = {} |
---|
| 215 | for k in keys : |
---|
| 216 | prevkeys[k] = sortedentries[0][fieldnumber[k]] |
---|
| 217 | for entry in sortedentries : |
---|
| 218 | curval = '-'.join([str(entry[fieldnumber[k]]) for k in keys]) |
---|
| 219 | prevval = '-'.join([str(prevkeys[k]) for k in keys]) |
---|
| 220 | if curval != prevval : |
---|
| 221 | summary = [ "*" ] * nbheaders |
---|
| 222 | for k in keys : |
---|
| 223 | summary[fieldnumber[k]] = prevkeys[k] |
---|
[3413] | 224 | for k in totals.keys() : |
---|
[2295] | 225 | summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) |
---|
| 226 | newentries.append(summary) |
---|
[3413] | 227 | for k in totals.keys() : |
---|
[2295] | 228 | totals[k]["value"] = totals[k]["convert"](entry[fieldnumber[k]]) |
---|
[3413] | 229 | else : |
---|
| 230 | for k in totals.keys() : |
---|
[2664] | 231 | totals[k]["value"] += totals[k]["convert"](entry[fieldnumber[k]] or 0.0) |
---|
[2295] | 232 | for k in keys : |
---|
| 233 | prevkeys[k] = entry[fieldnumber[k]] |
---|
| 234 | summary = [ "*" ] * nbheaders |
---|
| 235 | for k in keys : |
---|
| 236 | summary[fieldnumber[k]] = prevkeys[k] |
---|
[3413] | 237 | for k in totals.keys() : |
---|
[2295] | 238 | summary[fieldnumber[k]] = totals[k]["convert"](totals[k]["value"]) |
---|
| 239 | newentries.append(summary) |
---|
[2289] | 240 | return newentries |
---|
[3413] | 241 | |
---|
| 242 | def dumpWithSeparator(self, separator, allentries) : |
---|
[2016] | 243 | """Dumps datas with a separator.""" |
---|
[2600] | 244 | for entries in allentries : |
---|
| 245 | for entry in entries : |
---|
| 246 | line = [] |
---|
| 247 | for value in entry : |
---|
[3291] | 248 | try : |
---|
| 249 | strvalue = '"%s"' % value.encode(self.charset, \ |
---|
| 250 | "replace").replace(separator, "\\%s" % separator).replace('"', '\\"') |
---|
| 251 | except AttributeError : |
---|
| 252 | if value is None : |
---|
| 253 | strvalue = '"None"' # Double quotes around None to prevent spreadsheet from failing |
---|
[3413] | 254 | else : |
---|
[3291] | 255 | strvalue = str(value) |
---|
| 256 | line.append(strvalue) |
---|
[2600] | 257 | try : |
---|
| 258 | self.outfile.write("%s\n" % separator.join(line)) |
---|
[3413] | 259 | except IOError, msg : |
---|
[3368] | 260 | self.printInfo("%s : %s" % (_("PyKota data dumper failed : I/O error"), msg), "error") |
---|
[2600] | 261 | return -1 |
---|
[3413] | 262 | return 0 |
---|
| 263 | |
---|
| 264 | def dumpCsv(self, allentries, dummy) : |
---|
[2016] | 265 | """Dumps datas with a comma as the separator.""" |
---|
[2600] | 266 | return self.dumpWithSeparator(",", allentries) |
---|
[3413] | 267 | |
---|
| 268 | def dumpSsv(self, allentries, dummy) : |
---|
[2016] | 269 | """Dumps datas with a comma as the separator.""" |
---|
[2600] | 270 | return self.dumpWithSeparator(";", allentries) |
---|
[3413] | 271 | |
---|
| 272 | def dumpTsv(self, allentries, dummy) : |
---|
[2016] | 273 | """Dumps datas with a comma as the separator.""" |
---|
[2600] | 274 | return self.dumpWithSeparator("\t", allentries) |
---|
[3413] | 275 | |
---|
| 276 | def dumpCups(self, allentries, dummy) : |
---|
[2016] | 277 | """Dumps history datas as CUPS' page_log format.""" |
---|
[3121] | 278 | months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] |
---|
[2600] | 279 | entries = allentries[0] |
---|
[2016] | 280 | fieldnames = entries[0] |
---|
| 281 | fields = {} |
---|
| 282 | for i in range(len(fieldnames)) : |
---|
| 283 | fields[fieldnames[i]] = i |
---|
[3413] | 284 | sortindex = fields["jobdate"] |
---|
[2016] | 285 | entries = entries[1:] |
---|
[2830] | 286 | entries.sort(lambda m, n, si=sortindex : cmp(m[si], n[si])) |
---|
[3413] | 287 | for entry in entries : |
---|
[2016] | 288 | printername = entry[fields["printername"]] |
---|
| 289 | username = entry[fields["username"]] |
---|
| 290 | jobid = entry[fields["jobid"]] |
---|
[3050] | 291 | jobdate = DateTime.ISO.ParseDateTime(str(entry[fields["jobdate"]])[:19]) |
---|
[2016] | 292 | gmtoffset = jobdate.gmtoffset() |
---|
[3121] | 293 | jobdate = "%02i/%s/%04i:%02i:%02i:%02i %+03i%02i" % (jobdate.day, |
---|
| 294 | months[jobdate.month - 1], |
---|
| 295 | jobdate.year, |
---|
| 296 | jobdate.hour, |
---|
| 297 | jobdate.minute, |
---|
| 298 | jobdate.second, |
---|
| 299 | gmtoffset.hour, |
---|
| 300 | gmtoffset.minute) |
---|
[2016] | 301 | jobsize = entry[fields["jobsize"]] or 0 |
---|
| 302 | copies = entry[fields["copies"]] or 1 |
---|
| 303 | hostname = entry[fields["hostname"]] or "" |
---|
[2217] | 304 | billingcode = entry[fields["billingcode"]] or "-" |
---|
[2163] | 305 | for pagenum in range(1, jobsize+1) : |
---|
[3368] | 306 | line = "%s %s %s [%s] %s %s %s %s" % (printername, username, jobid, jobdate, pagenum, copies, billingcode, hostname) |
---|
[3413] | 307 | self.outfile.write("%s\n" % line.encode(self.charset, |
---|
[3368] | 308 | "replace")) |
---|
[3413] | 309 | return 0 |
---|
| 310 | |
---|
[2600] | 311 | def dumpXml(self, allentries, datatypes) : |
---|
[2016] | 312 | """Dumps datas as XML.""" |
---|
| 313 | x = jaxml.XML_document(encoding="UTF-8") |
---|
| 314 | x.pykota(version=version.__version__, author=version.__author__) |
---|
[2600] | 315 | for (entries, datatype) in zip(allentries, datatypes) : |
---|
[2016] | 316 | x._push() |
---|
[2600] | 317 | x.dump(storage=self.config.getStorageBackend()["storagebackend"], type=datatype) |
---|
| 318 | headers = entries[0] |
---|
| 319 | for entry in entries[1:] : |
---|
| 320 | x._push() |
---|
| 321 | x.entry() |
---|
| 322 | for (header, value) in zip(headers, entry) : |
---|
[3291] | 323 | try : |
---|
| 324 | strvalue = saxutils.escape(value.encode("UTF-8", \ |
---|
| 325 | "replace"), \ |
---|
| 326 | { "'" : "'", \ |
---|
| 327 | '"' : """ }) |
---|
[3413] | 328 | except AttributeError : |
---|
[3291] | 329 | strvalue = str(value) |
---|
| 330 | # We use 'str' instead of 'unicode' below to be compatible |
---|
| 331 | # with older releases of PyKota. |
---|
[3413] | 332 | # The XML dump will contain UTF-8 encoded strings, |
---|
[3291] | 333 | #�not unicode strings anyway. |
---|
| 334 | x.attribute(strvalue, \ |
---|
| 335 | type=type(value).__name__.replace("unicode", "str"), \ |
---|
| 336 | name=header) |
---|
[3413] | 337 | x._pop() |
---|
| 338 | x._pop() |
---|
[2016] | 339 | x._output(self.outfile) |
---|
[3413] | 340 | return 0 |
---|