summaryrefslogtreecommitdiffstats
path: root/src/utils/hw_inventory.py
blob: dff1c7a9d4dd622da7178c1fb411527b12afe44e (plain)
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
#
# Copyright (C) 2023 Soleta Networks <info@soleta.eu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

import json
import os.path
import shlex
import subprocess

from collections import namedtuple
from enum import Enum, auto


SYSFS_EFI_PATH = '/sys/firmware/efi'


class HardwareType(Enum):
    MULTIMEDIA = 1
    BOOTMODE = 2
    FIRMWARE = 3
    GRAPHICS = 4
    STORAGE = 5
    NETWORK = 6
    CHASSIS = 7
    MEMORY = 8
    MODEL = 9
    DISK = 10
    CPU = 11
    USB = 12
    CD = 13


class HardwareElement():
    """
    Simple container of a hardware type and its name
    """
    def __init__(self, hwtype, name):
        self.type = hwtype
        self.name = name

    def __str__(self):
        return f'Hardware element {self.type}: {self.name}'


class HardwareInventory():
    """
    Collection of hardware elements
    """
    def __init__(self):
        self.elements = list()

    def add_element(self, elem):
        if elem.type not in HardwareType:
            raise ValueError('Unsupported hardware type')
        if not elem.name:
            raise ValueError('Empty hardware element name')
        self.elements.append(elem)


def _bytes_to_human(size):
    suffixes = ['B', 'MiB', 'GiB', 'TiB']
    if type(size) is not int:
        raise TypeError(f'Invalid type in _bytes_to_human, got: {size} {type(size)}')
    for exponent, suffix in enumerate(suffixes, start=1):
        conv = size / (1024**exponent)
        if conv < 1024:
            return f'{conv:.2f} {suffix}'

# Utility methods for lshw json output processing

def _fill_computer_model(inventory, root):
    model = ' '.join([root.get('vendor', 'Unknown vendor'),
                      root.get('product', 'Unknown prouct'),
                      root.get('version', 'Unknown version')])
    elem = HardwareElement(HardwareType.MODEL, model)
    inventory.add_element(elem)


def _fill_chassis_type(inventory, root):
    chassis = root['configuration']['chassis']
    elem = HardwareElement(HardwareType.CHASSIS, chassis)
    inventory.add_element(elem)


def _fill_bootmode(inventory):
    bootmode = 'UEFI' if os.path.exists(SYSFS_EFI_PATH) else 'BIOS'
    elem = HardwareElement(HardwareType.BOOTMODE, bootmode)
    inventory.add_element(elem)


def _process_core_firmware(inventory, obj):
    desc = ' '.join([obj.get('description', ''), obj.get('vendor', ''), obj.get('version', '')])
    firmware_elem = HardwareElement(HardwareType.FIRMWARE, desc)
    inventory.add_element(firmware_elem)


def _process_core_cpu(inventory, obj):
    cpu = obj.get('product', 'Unknown product')
    cpu_elem = HardwareElement(HardwareType.CPU, cpu)
    inventory.add_element(cpu_elem)


def _process_core_mem_bank(inventory, obj):
    slot = obj.get('slot', 'Unknown slot')
    if 'size' in obj:
        size = obj['size']
        human_size = _bytes_to_human(size)
        mem = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product'), human_size, f'({slot})'])
    else:
        mem = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product'), 'Empty slot', f'({slot})'])
    mem_elem = HardwareElement(HardwareType.MEMORY, mem)
    inventory.add_element(mem_elem)


def _process_core_mem(inventory, obj):
    banks = obj.get('children', [])
    for bank in banks:
        _process_core_mem_bank(inventory, bank)


def _process_core_pci_usb(inventory, obj):
    name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    usb_elem = HardwareElement(HardwareType.USB, name)
    inventory.add_element(usb_elem)


def _process_core_pci_display(inventory, obj):
    name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    display_elem = HardwareElement(HardwareType.GRAPHICS, name)
    inventory.add_element(display_elem)


def _process_core_pci_network(inventory, obj):
    link = obj.get('size', 'Unknown link speed')
    if type(link) == int:
        if link >= 1e9:
            link_human = f'{link/1e9} Gbit/s'
        else:
            link_human = f'{link/1e6} Mbit/s'
        name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product'), f'({link_human})'])
    else:
        name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    elem = HardwareElement(HardwareType.NETWORK, name)
    inventory.add_element(elem)


def _process_core_pci_storage_child(inventory, obj):
    obj_id = obj.get('id', '')
    if obj_id.startswith('disk') or obj_id.startswith('nvme'):
        size = _bytes_to_human(obj.get('size', 'Unknown size'))
        name = ' '.join([obj.get('description', ''), obj.get('product', 'Unknown product'), size])
        elem = HardwareElement(HardwareType.DISK, name)
        inventory.add_element(elem)


def _process_core_pci_storage(inventory, obj):
    name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    elem = HardwareElement(HardwareType.STORAGE, name)
    inventory.add_element(elem)
    # Disks follow a storage section
    for storage_child in obj.get('children', []):
        _process_core_pci_storage_child(inventory, storage_child)


def _process_core_pci_disk(inventory, obj):
    name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    elem = HardwareElement(HardwareType.DISK, name)
    inventory.add_element(elem)


def _process_core_pci_multimedia(inventory, obj):
    name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    elem = HardwareElement(HardwareType.MULTIMEDIA, name)
    inventory.add_element(elem)


def _process_core_pci_child(inventory, obj):
    obj_id = obj.get('id', '')
    if obj_id.startswith('usb'):
        _process_core_pci_usb(inventory, obj)
    elif obj_id.startswith('display'):
        _process_core_pci_display(inventory, obj)
    elif obj_id.startswith('network'):
        _process_core_pci_network(inventory, obj)
    elif obj_id.startswith('sata') or obj_id.startswith('storage'):
        _process_core_pci_storage(inventory, obj)
    elif obj_id.startswith('multimedia'):
        _process_core_pci_multimedia(inventory, obj)
    elif obj_id.startswith('pci'):  # PCI bridge
        bridge_children = obj.get('children', [])
        for bridge_child in bridge_children:
            _process_core_pci_child(inventory, bridge_child)


def _process_core_pci(inventory, obj):
    children = obj.get('children', [])
    for child in children:
        _process_core_pci_child(inventory, child)


def _process_core_scsi_disk(inventory, obj):
    vendor = obj.get('vendor', 'Unknown vendor')
    name = ' '.join([vendor, obj.get('product', 'Unknown product')])
    elem = HardwareElement(HardwareType.DISK, name)
    inventory.add_element(elem)


def _process_core_scsi_cdrom(inventory, obj):
    name = ' '.join([obj.get('vendor', 'Unknown vendor'), obj.get('product', 'Unknown product')])
    elem = HardwareElement(HardwareType.CD, name)
    inventory.add_element(elem)


def _process_core_scsi_child(inventory, obj):
    obj_id = obj.get('id', '')
    if obj_id.startswith('disk'):
        _process_core_scsi_disk(inventory, obj)
    elif obj_id.startswith('cdrom'):
        _process_core_scsi_cdrom(inventory, obj)


def _process_core_scsi(inventory, obj):
    children = obj.get('children', [])
    for child in children:
        _process_core_scsi_child(inventory, child)

def _process_core(inventory, core):
    for element in core['children']:
        element_id = element['id']
        if element_id.startswith('firmware'):
            _process_core_firmware(inventory, element)
        elif element_id.startswith('cpu'):
            _process_core_cpu(inventory, element)
        elif element_id.startswith('memory'):
            _process_core_mem(inventory, element)
        elif element_id.startswith('pci'):
            _process_core_pci(inventory, element)
        elif element_id.startswith('scsi'):
            _process_core_scsi(inventory, element)

def legacy_hardware_element(element):
    """
    Legacy string representation of a hardware element.

    For example, a graphics card named "Foo" would be
    represented as "vga=Foo"
    """
    if type(element) is not HardwareElement:
        raise TypeError('Invalid type')
    elif element.type is HardwareType.MULTIMEDIA:
        nemonic = 'mul'
    elif element.type is HardwareType.BOOTMODE:
        nemonic = 'boo'
    elif element.type is HardwareType.FIRMWARE:
        nemonic = 'bio'
    elif element.type is HardwareType.GRAPHICS:
        nemonic = 'vga'
    elif element.type is HardwareType.CHASSIS:
        nemonic = 'cha'
    elif element.type is HardwareType.STORAGE:
        nemonic = 'sto'
    elif element.type is HardwareType.NETWORK:
        nemonic = 'net'
    elif element.type is HardwareType.MEMORY:
        nemonic = 'mem'
    elif element.type is HardwareType.MODEL:
        nemonic = 'mod'
    elif element.type is HardwareType.DISK:
        nemonic = 'dis'
    elif element.type is HardwareType.CPU:
        nemonic = 'cpu'
    elif element.type is HardwareType.USB:
        nemonic = 'usb'
    elif element.type is HardwareType.CD:
        nemonic = 'cdr'
    return f'{nemonic}={element.name}'

def legacy_list_hardware_inventory(inventory):
    """
    Return a hardware inventory as a legacy string.  Map each hardware
    component to its legacy string representation and concatenate using a new
    line.

    This is the same output as legacy script ogListHardware.
    """
    return '\n'.join([legacy_hardware_element(elem) for elem in inventory.elements])


def get_hardware_inventory():
    proc = subprocess.run(['lshw', '-json'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    j = json.loads(proc.stdout)

    if type(j) is list:
        root = j[0]
    if type(root) is not dict:
        raise ValueError('Unvalid lshw json output')

    inventory = HardwareInventory()
    _fill_computer_model(inventory, root)
    _fill_chassis_type(inventory, root)
    _fill_bootmode(inventory)
    # Process 'children' node
    # Usually there are two type of children from lshw json root:
    # 'core' and 'power'.
    # We are only interested in 'core'.
    children = root['children']
    for child in children:
        child_id = child['id']
        if child_id == 'core':
            _process_core(inventory, child)

    return inventory