1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
|
# Copyright 2010-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
__all__ = [
"create_from_file",
]
try:
import xml.etree.cElementTree as etree
except ImportError:
import cElementTree as etree
from StringIO import StringIO
from logging import getLogger
from pkg_resources import resource_string
from lpresults.registry.formatters import string_to_datetime
from lpresults import xunit
from lpresults.xunit.dispatcher import DispatcherQueue
from lpresults.xunit.parsers.cpuinfo import CpuinfoParser
from lpresults.xunit.parsers.cputable import CputableParser
from lpresults.xunit.parsers.deferred import DeferredParser
from lpresults.xunit.parsers.dmesg import DmesgParser
from lpresults.xunit.parsers.dmidecode import DmidecodeParser
from lpresults.xunit.parsers.dmisys import DmiSysParser
from lpresults.xunit.parsers.udevadm import UdevadmParser
from lpresults.xunit.protocol import Protocol
from lpresults.xunit.status import Status
CHECKBOX_HEADER = """<?xml version="1.0" ?>"""
class CheckboxResult:
def __init__(self, test_run_factory, **kwargs):
self.test_run_factory = test_run_factory
self.test_run_kwargs = kwargs
self.dispatcher = DispatcherQueue()
# Register handlers to incrementally add information
register = self.dispatcher.registerHandler
register(("cpu", "architecture",), self.addCpuArchitecture)
register(("identifier",), self.addIdentifier)
register(("system_unit", "device",), self.addDeviceState)
register(("test_run", "test_result",), self.addTestResult)
# Register handlers to set information once
register(("architecture",), self.setArchitecture, count=1)
register(
("cpuinfo", "machine", "cpuinfo_result",),
self.setCpuinfo, count=1)
register(
("project", "series",),
self.setTestRun, count=1)
register(
("system_unit", "processor",),
self.setProcessorState, count=1)
register(
("test_run", "model", "make", "version", "identifiers",),
self.setSystemUnit, count=1)
register(
("udevadm", "bits", "udevadm_result",),
self.setUdevadm, count=1)
# Publish events passed as keyword arguments
if "project" in kwargs:
self.dispatcher.publishEvent("project", kwargs.pop("project"))
self.dispatcher.publishEvent("series", kwargs.pop("series", None))
def addAddress(self, address):
self.dispatcher.publishEvent("identifier", address)
def addContext(self, text, command=None):
if text.strip() == "Command not found.":
return
parsers = {
"cat /proc/cpuinfo": self.parseCpuinfo,
"cat /var/log/dmesg | ansi_parser": DmesgParser,
"dmidecode": DmidecodeParser,
"grep -r . /sys/class/dmi/id/ 2>/dev/null": DmiSysParser,
"udevadm info --export-db": self.parseUdevadm,
}
parser = parsers.get(command)
if parser:
if not isinstance(text, unicode):
text = text.decode("utf-8")
stream = StringIO(text)
p = parser(stream)
p.run(self)
def addCpu(self, cpu):
self.dispatcher.publishEvent("cpu", cpu)
def addCpuArchitecture(self, cpu, architecture):
if cpu["debian_name"] == architecture:
self.dispatcher.publishEvent("machine", cpu["gnu_name"])
self.dispatcher.publishEvent("bits", cpu["bits"])
def addDevice(self, device):
self.dispatcher.publishEvent("device", device)
def addDeviceState(self, system_unit, device):
system_unit.addDeviceState(
bus_name=device.bus, category_name=device.category,
product_name=device.product, vendor_name=device.vendor,
product_id=device.product_id, vendor_id=device.vendor_id,
subproduct_id=device.subproduct_id,
subvendor_id=device.subvendor_id,
driver_name=device.driver)
def addDmiDevice(self, device):
if device.serial:
self.dispatcher.publishEvent("identifier", device.serial)
if device.category in ("BOARD", "SYSTEM") \
and device.vendor != device.product \
and device.product is not None:
self.dispatcher.publishEvent("model", device.product)
self.dispatcher.publishEvent("make", device.vendor)
self.dispatcher.publishEvent("version", device.version)
def addIdentifier(self, identifier):
try:
self.identifiers.append(identifier)
except AttributeError:
self.identifiers = [identifier]
self.dispatcher.publishEvent("identifiers", self.identifiers)
def addLSBRelease(self, name, value):
pass
def addQuestion(self, question):
answer_to_status = {
"fail": Status.FAIL,
"no": Status.FAIL,
"pass": Status.PASS,
"skip": Status.UNTESTED,
"uninitiated": Status.UNINITIATED,
"unresolved": Status.UNRESOLVED,
"unsupported": Status.UNSUPPORTED,
"untested": Status.UNTESTED,
"yes": Status.PASS,
}
test_result = dict(
name=question["name"],
output=question["comment"],
status=answer_to_status[question["answer"]["value"]],
)
test_result.update(self.test_run_kwargs)
self.dispatcher.publishEvent("test_result", test_result)
def addTestResult(self, test_run, test_result):
test_run.addTestResult(**test_result)
def addSummary(self, name, value):
if name == "architecture":
self.dispatcher.publishEvent("architecture", value)
elif name == "distribution":
self.dispatcher.publishEvent("project", value)
elif name == "distroseries":
self.dispatcher.publishEvent("series", value)
def parseCpuinfo(self, cpuinfo):
self.dispatcher.publishEvent("cpuinfo", cpuinfo)
return DeferredParser(self.dispatcher, "cpuinfo_result")
def parseSysfs(self, sysfs):
return DeferredParser(self.dispatcher)
def parseUdevadm(self, udevadm):
self.dispatcher.publishEvent("udevadm", udevadm)
return DeferredParser(self.dispatcher, "udevadm_result")
def setArchitecture(self, architecture):
string = resource_string(xunit.__name__, "cputable")
stream = StringIO(string.decode("utf-8"))
parser = CputableParser(stream)
parser.run(self)
def setCpuinfo(self, cpuinfo, machine, cpuinfo_result):
parser = CpuinfoParser(cpuinfo, machine)
parser.run(cpuinfo_result)
def setProcessor(self, processor):
self.dispatcher.publishEvent("processor", processor)
def setProcessorState(self, system_unit, processor):
system_unit.setProcessorState(
platform_name=processor["platform"],
make=processor["type"], model=processor["model"],
model_number=processor["model_number"],
model_version=processor["model_version"],
model_revision=processor["model_revision"],
cache=processor["cache"], other=processor["other"],
bogomips=processor["bogomips"], speed=processor["speed"],
count=processor["count"])
def setSystemUnit(self, test_run, model, make, version, identifiers):
test_run.setSystemUnit(
model=model, make=make, version=version,
identifiers=identifiers, **self.test_run_kwargs)
self.dispatcher.publishEvent("system_unit", test_run.system_unit)
def setTestRun(self, project, series):
test_run = self.test_run_factory(
project=project, series=series, **self.test_run_kwargs)
self.dispatcher.publishEvent("test_run", test_run)
def setUdevadm(self, udevadm, bits, udevadm_result):
parser = UdevadmParser(udevadm, bits)
parser.run(udevadm_result)
class CheckboxProtocol(Protocol):
def __init__(self, *args, **kwargs):
super(CheckboxProtocol, self).__init__(*args, **kwargs)
self.logger = getLogger()
def _getClient(self, node):
"""Return a dictionary with the name and version of the client."""
return {
"name": node.get("name"),
"version": node.get("version"),
}
def _getProperty(self, node):
"""Return the (name, value) of a property."""
return (node.get("name"), self._getValueAsType(node))
def _getProperties(self, node):
"""Return a dictionary of properties."""
properties = {}
for child in node.getchildren():
assert child.tag == "property", \
"Unexpected tag <%s>, expected <property>" % child.tag
name, value = self._getProperty(child)
properties[name] = value
return properties
def _getValueAsType(self, node):
"""Return value of a node as the type attribute."""
type_ = node.get("type")
if type_ in ("bool",):
value = node.text.strip()
assert value in ("True", "False",), \
"Unexpected boolean value '%s' in <%s>" % (value, node.tag)
return value == "True"
elif type_ in ("str",):
return unicode(node.text.strip())
elif type_ in ("int", "long",):
return int(node.text.strip())
elif type_ in ("float",):
return float(node.text.strip())
elif type_ in ("list",):
return list(self._getValueAsType(child)
for child in node.getchildren())
elif type_ in ("dict",):
return dict((child.get("name"), self._getValueAsType(child))
for child in node.getchildren())
else:
raise AssertionError(
"Unexpected type '%s' in <%s>" % (type_, node.tag))
def _getValueAsBoolean(self, node):
"""Return the value of the attribute "value" as a boolean."""
value = node.attrib["value"]
assert value in ("True", "False",), \
"Unexpected boolean value '%s' in tag <%s>" % (value, node.tag)
return value == "True"
def _getValueAsDatetime(self, node):
"""Return the value of the attribute "value" as a datetime."""
string = node.attrib["value"]
return string_to_datetime(string)
def _getValueAsString(self, node):
"""Return the value of the attribute "value"."""
return node.attrib["value"].decode("utf-8")
def parseContext(self, result, node):
"""Parse the <context> part of a submission."""
duplicates = set()
for child in node.getchildren():
assert child.tag == "info", \
"Unexpected tag <%s>, expected <info>" % child.tag
command = child.get("command")
if command not in duplicates:
duplicates.add(command)
text = child.text
if text is None:
text = ""
result.addContext(text, command)
else:
self.logger.debug(
"Duplicate command found in tag <info>: %s" % command)
def parseHardware(self, result, node):
"""Parse the <hardware> section of a submission."""
parsers = {
"dmi": DmidecodeParser,
"processors": self.parseProcessors,
"sysfs-attributes": result.parseSysfs,
"udev": result.parseUdevadm,
}
for child in node.getchildren():
parser = parsers.get(child.tag)
if parser:
if child.getchildren():
parser(result, child)
else:
text = child.text
if not isinstance(text, unicode):
text = text.decode("utf-8")
stream = StringIO(text)
p = parser(stream)
p.run(result)
else:
self.logger.debug(
"Unsupported tag <%s> in <hardware>" % child.tag)
def parseLSBRelease(self, result, node):
"""Parse the <lsb_release> part of a submission."""
for name, value in self._getProperties(node).iteritems():
result.addLSBRelease(name, value)
def parsePackages(self, result, node):
"""Parse the <packages> part of a submission."""
pass
def parseProcessors(self, result, node):
"""Parse the <processors> part of a submission."""
processors = []
for child in node.getchildren():
assert child.tag == "processor", \
"Unexpected tag <%s>, expected <processor>" % child.tag
# Convert lists to space separated strings.
properties = self._getProperties(child)
for key, value in properties.iteritems():
if key in ("bogomips", "cache", "count", "speed",):
properties[key] = int(value)
elif isinstance(value, list):
properties[key] = u" ".join(value)
processors.append(properties)
# Check if /proc/cpuinfo was parsed already.
if any("platform" in processor for processor in processors):
result.setProcessor(processors[0])
else:
lines = []
for processor in processors:
# Convert some keys with underscores to spaces instead.
for key, value in processor.iteritems():
if "_" in key and key != "vendor_id":
key = key.replace("_", " ")
lines.append(u"%s: %s" % (key, value))
lines.append(u"")
stream = StringIO(u"\n".join(lines))
parser = result.parseCpuinfo(stream)
parser.run(result)
def parseQuestions(self, result, node):
"""Parse the <questions> part of a submission."""
for child in node.getchildren():
assert child.tag == "question", \
"Unexpected tag <%s>, expected <question>" % child.tag
question = {
"name": child.get("name").decode("utf-8"),
"targets": [],
}
plugin = child.get("plugin", None)
if plugin is not None:
question["plugin"] = plugin
answer_choices = []
for sub_node in child.getchildren():
sub_tag = sub_node.tag
if sub_tag == "answer":
question["answer"] = answer = {}
answer["type"] = sub_node.get("type")
if answer["type"] == "multiple_choice":
question["answer_choices"] = answer_choices
unit = sub_node.get("unit", None)
if unit is not None:
answer["unit"] = unit
answer["value"] = sub_node.text.strip()
elif sub_tag == "answer_choices":
for value_node in sub_node.getchildren():
answer_choices.append(
self._getValueAsType(value_node))
elif sub_tag == "target":
# The Relax NG schema ensures that the attribute
# id exists and that it is an integer
target = {"id": int(sub_node.get("id"))}
target["drivers"] = drivers = []
for driver_node in sub_node.getchildren():
drivers.append(driver_node.text.strip())
question["targets"].append(target)
elif sub_tag in ("comment", "command",):
text = sub_node.text
if text is None:
text = u""
elif not isinstance(text, unicode):
text = text.decode("utf-8")
question[sub_tag] = text.strip()
else:
raise AssertionError(
"Unexpected tag <%s> in <question>" % sub_tag)
result.addQuestion(question)
def parseSoftware(self, result, node):
"""Parse the <software> section of a submission."""
parsers = {
"lsbrelease": self.parseLSBRelease,
"packages": self.parsePackages,
}
for child in node.getchildren():
parser = parsers.get(child.tag)
if parser:
parser(result, child)
else:
self.logger.debug(
"Unsupported tag <%s> in <software>" % child.tag)
def parseSummary(self, result, node):
"""Parse the <summary> section of a submission."""
parsers = {
"architecture": self._getValueAsString,
"client": self._getClient,
"contactable": self._getValueAsBoolean,
"date_created": self._getValueAsDatetime,
"distribution": self._getValueAsString,
"distroseries": self._getValueAsString,
"kernel-release": self._getValueAsString,
"live_cd": self._getValueAsBoolean,
"private": self._getValueAsBoolean,
"system_id": self._getValueAsString,
}
for child in node.getchildren():
parser = parsers.get(child.tag)
if parser:
value = parser(child)
result.addSummary(child.tag, value)
else:
self.logger.debug(
"Unsupported tag <%s> in <summary>" % child.tag)
def parseRoot(self, result, node):
"""Parse the <system> root of a submission."""
parsers = {
"context": self.parseContext,
"hardware": self.parseHardware,
"questions": self.parseQuestions,
"software": self.parseSoftware,
"summary": self.parseSummary,
}
# Iterate over the root children, "summary" first
for child in node.getchildren():
parser = parsers.get(child.tag)
if parser:
parser(result, child)
else:
self.logger.debug(
"Unsupported tag <%s> in <system>" % child.tag)
def run(self, test_run_factory, **kwargs):
parser = etree.XMLParser()
tree = etree.parse(self.file, parser=parser)
root = tree.getroot()
if root.tag != "system":
raise AssertionError(
"Unexpected tag <%s> at root, expected <system>" % root.tag)
result = CheckboxResult(test_run_factory, **kwargs)
self.parseRoot(result, root)
return result
def create_from_file(file):
line = file.readline()
file.seek(0)
if line.strip() == CHECKBOX_HEADER:
return CheckboxProtocol(file)
return None
|