still prettifying
[bootmanager.git] / source / systeminfo.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5 #
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
7 # All rights reserved.
8 # expected /proc/partitions format
9
10
11 #----------------------------------------------------
12 #major minor  #blocks  name
13 #
14 #3     0   40017915 hda
15 #3     1     208813 hda1
16 #3     2   20482875 hda2
17 #3     3     522112 hda3
18 #3     4   18804082 hda4
19 #----------------------------------------------------
20
21 from __future__ import print_function
22
23 import string
24 import sys
25 import os
26 import popen2
27 import re
28 import errno
29 import ModelOptions
30 from pypci import *
31 from Exceptions import *
32
33 """
34 a utility class for finding and returning information about
35 block devices, memory, and other hardware on the system
36 """
37
38 PROC_MEMINFO_PATH = "/proc/meminfo"
39 PROC_PARTITIONS_PATH = "/proc/partitions"
40
41 # set when the sfdisk -l <dev> trick has been done to make
42 # all devices show up
43 DEVICES_SCANNED_FLAG = "/tmp/devices_scanned"
44
45 # a /proc/partitions block is 1024 bytes
46 # a GB to a HDD manufacturer is 10^9 bytes
47 BLOCKS_PER_GB = pow(10, 9) / 1024.0;
48
49
50 MODULE_CLASS_NETWORK = "network"
51 MODULE_CLASS_SCSI = "scsi"
52
53 #PCI_* is now defined in the pypci modules
54 #PCI_BASE_CLASS_NETWORK = 0x02L
55 #PCI_BASE_CLASS_STORAGE = 0x01L
56
57 def get_total_phsyical_mem(vars = {}, log = sys.stderr):
58     """
59     return the total physical memory of the machine, in kilobytes.
60
61     Return None if /proc/meminfo not readable.
62     """
63
64     try:
65         meminfo_file = file(PROC_MEMINFO_PATH, "r")
66     except IOError as e:
67         return
68
69     total_memory = None
70
71     for line in meminfo_file:
72
73         try:
74             fieldname, value = string.split(line, ":")
75         except ValueError as e:
76             # this will happen for lines that don't have two values
77             # (like the first line on 2.4 kernels)
78             continue
79
80         fieldname = string.strip(fieldname)
81         value = string.strip(value)
82         
83         if fieldname == "MemTotal":
84             try:
85                 total_memory, units = string.split(value)
86             except ValueError as e:
87                 return
88
89             if total_memory == "" or total_memory == None or \
90                    units == "" or units == None:
91                 return
92
93             if string.lower(units) != "kb":
94                 return
95
96             try:
97                 total_memory = int(total_memory)
98             except ValueError as e:
99                 return
100
101             break
102
103     meminfo_file.close()
104     return total_memory
105
106 def get_block_device_list(vars = {}, log = sys.stderr):
107     """
108     get a list of block devices from this system.
109     return an associative array, where the device name
110     (full /dev/device path) is the key, and the value
111     is a tuple of (major, minor, numblocks, gb_size, readonly)
112     """
113
114     # make sure we can access to the files/directories in /proc
115     if not os.access(PROC_PARTITIONS_PATH, os.F_OK):
116         return None
117
118     # table with valid scsi/sata/ide/raid block device names
119     valid_blk_names = {}
120     # add in valid sd and hd block device names
121     # also check for vd (virtio devices used with kvm)
122     for blk_prefix in ('sd', 'hd', 'vd'):
123         for blk_num in string.ascii_lowercase:
124             devicename = "{}{}".format(blk_prefix, blk_num)
125             valid_blk_names[devicename] = None
126
127     # add in valid scsi raid block device names
128     for M in range(0, 1+1):
129         for N in range(0, 7+1):
130             devicename = "cciss/c{}d{}".format(M, N)
131             valid_blk_names[devicename] = None
132
133     for devicename in valid_blk_names.keys():
134         # devfs under 2.4 (old boot cds) used to list partitions
135         # in a format such as scsi/host0/bus0/target0/lun0/disc
136         # and /dev/sda, etc. were just symlinks
137         try:
138             devfsname = os.readlink("/dev/{}".format(devicename))
139             valid_blk_names[devfsname] = None
140         except OSError:
141             pass
142
143     # only do this once every system boot
144     if not os.access(DEVICES_SCANNED_FLAG, os.R_OK):
145
146         # this is ugly. under devfs, device
147         # entries in /dev/scsi/.. and /dev/ide/...
148         # don't show up until you attempt to read
149         # from the associated device at /dev (/dev/sda).
150         # so, lets run sfdisk -l (list partitions) against
151         # most possible block devices, that way they show
152         # up when it comes time to do the install.
153
154         # 27.6.2012 - Using parted instead of sfdisk, assuming
155         # that doing so respects the behavior mentioned above.
156
157         devicenames = valid_blk_names.keys()
158         devicenames.sort()
159         for devicename in devicenames:
160             os.system("parted --script --list /dev/{} > /dev/null 2>&1".format(devicename))
161
162         # touch file
163         fb = open(DEVICES_SCANNED_FLAG, "w")
164         fb.close()
165
166     devicelist = {}
167
168     partitions_file = file(PROC_PARTITIONS_PATH, "r")
169     line_count = 0
170     for line in partitions_file:
171         line_count = line_count + 1
172
173         # skip the first two lines always
174         if line_count < 2:
175             continue
176
177         parts = string.split(line)
178
179         if len(parts) < 4:
180             continue
181
182         device = parts[3]
183
184         # skip and ignore any partitions
185         if not valid_blk_names.has_key(device):
186             continue
187
188         try:
189             major = int(parts[0])
190             minor = int(parts[1])
191             blocks = int(parts[2])
192         except ValueError as err:
193             continue
194
195         gb_size = blocks/BLOCKS_PER_GB
196
197         # check to see if the blk device is readonly
198         try:
199             # can we write to it?
200             dev_name = "/dev/{}".format(device)
201             fb = open(dev_name, "w")
202             fb.close()
203             readonly = False
204         except IOError as e:
205             # check if EROFS errno
206             if errno.errorcode.get(e.errno, None) == 'EROFS':
207                 readonly = True
208             else:
209                 # got some other errno, pretend device is readonly
210                 readonly = True
211
212         devicelist[dev_name] = (major, minor, blocks, gb_size, readonly)
213
214     return devicelist
215
216
217 def get_system_modules(vars = {}, log = sys.stderr):
218     """
219     Return a list of kernel modules that this system requires.
220     This requires access to the installed system's root
221     directory, as the following file must exist and is used:
222     <install_root>/lib/modules/(first entry if kernel_version unspecified)/modules.pcimap
223
224     If there are more than one kernels installed, and the kernel
225     version is not specified, then only the first one in
226     /lib/modules is used.
227
228     Returns a dictionary, keys being the type of module:
229         - scsi       MODULE_CLASS_SCSI
230         - network    MODULE_CLASS_NETWORK
231     The value being the kernel module name to load.
232
233     Some sata devices show up under an IDE device class,
234     hence the reason for checking for ide devices as well.
235     If there actually is a match in the pci -> module lookup
236     table, and its an ide device, its most likely sata,
237     as ide modules are built in to the kernel.
238     """
239
240     if not vars.has_key("SYSIMG_PATH"):
241         vars["SYSIMG_PATH"] = "/"
242     SYSIMG_PATH = vars["SYSIMG_PATH"]
243
244     if not vars.has_key("NODE_MODEL_OPTIONS"):
245         vars["NODE_MODEL_OPTIONS"] = 0;
246
247     initrd, kernel_version = getKernelVersion(vars, log)
248
249     # get the kernel version we are assuming
250     if kernel_version is None:
251         try:
252             kernel_version = os.listdir("{}/lib/modules/".format(SYSIMG_PATH))
253         except OSError as e:
254             return
255
256         if len(kernel_version) == 0:
257             return
258
259         if len(kernel_version) > 1:
260             print("WARNING: We may be returning modules for the wrong kernel.")
261
262         kernel_version = kernel_version[0]
263
264     print("Using kernel version {}".format(kernel_version))
265
266     # test to make sure the file we need is present
267     modules_pcimap_path = "{}/lib/modules/{}/modules.pcimap"\
268         .format(SYSIMG_PATH, kernel_version)
269     if not os.access(modules_pcimap_path, os.R_OK):
270         print("WARNING: Unable to read {}".format(modules_pcimap_path))
271         return
272
273     pcimap = pypcimap.PCIMap(modules_pcimap_path)
274
275     # this is the actual data structure we return
276     system_mods = {}
277
278     # these are the lists that will be in system_mods
279     network_mods = []
280     scsi_mods = []
281
282     # XXX: this is really similar to what BootCD/conf_files/pl_hwinit does. merge?
283     pcidevs = get_devices()
284
285     devlist =pcidevs.keys()
286     devlist.sort()
287     for slot in devlist:
288         dev = pcidevs[slot]
289         base = (dev[4] & 0xff0000) >> 16
290         modules = pcimap.get(dev)
291         if base not in (PCI_BASE_CLASS_STORAGE,
292                         PCI_BASE_CLASS_NETWORK):
293             # special exception for forcedeth NICs whose base id
294             # claims to be a Bridge, even though it is clearly a
295             # network device
296             if "forcedeth" in modules: 
297                 base = PCI_BASE_CLASS_NETWORK
298             else:
299                 continue
300
301         if len(modules) > 0:
302             if base == PCI_BASE_CLASS_NETWORK:
303                 network_mods += modules
304             elif base == PCI_BASE_CLASS_STORAGE:
305                 scsi_mods += modules
306
307     system_mods[MODULE_CLASS_SCSI] = scsi_mods
308     system_mods[MODULE_CLASS_NETWORK] = network_mods
309
310     return system_mods
311
312
313 def getKernelVersion(vars = {}, log = sys.stderr):
314     # make sure we have the variables we need
315     try:
316         SYSIMG_PATH = vars["SYSIMG_PATH"]
317         if SYSIMG_PATH == "":
318             raise ValueError("SYSIMG_PATH")
319
320         NODE_MODEL_OPTIONS = vars["NODE_MODEL_OPTIONS"]
321     except KeyError as var:
322         raise BootManagerException("Missing variable in vars: {}\n".format(var))
323     except ValueError as var:
324         raise BootManagerException("Variable in vars, shouldn't be: {}\n".format(var))
325
326     option = ''
327     if NODE_MODEL_OPTIONS & ModelOptions.SMP:
328         option = 'smp'
329         try:
330             os.stat("{}/boot/kernel-boot{}".format(SYSIMG_PATH, option))
331             os.stat("{}/boot/initrd-boot{}".format(SYSIMG_PATH, option))
332         except OSError as e:
333             # smp kernel is not there; remove option from modeloptions
334             # such that the rest of the code base thinks we are just
335             # using the base kernel.
336             NODE_MODEL_OPTIONS = NODE_MODEL_OPTIONS & ~ModelOptions.SMP
337             vars["NODE_MODEL_OPTIONS"] = NODE_MODEL_OPTIONS
338             log.write("WARNING: Couldn't locate smp kernel.\n")
339             option = ''
340     try:
341         initrd = os.readlink("{}/boot/initrd-boot{}".format(SYSIMG_PATH, option))
342         kernel_version = initrd.replace("initrd-", "").replace(".img", "")    
343     except OSError as e:
344         initrd = None
345         kernel_version = None
346         
347     return (initrd, kernel_version)
348
349
350 if __name__ == "__main__":
351     devices = get_block_device_list()
352     print("block devices detected:")
353     if not devices:
354         print("no devices found!")
355     else:
356         for dev in devices.keys():
357             print("{} {}".format(dev, repr(devices[dev])))
358             
359
360     print("")
361     memory = get_total_phsyical_mem()
362     if not memory:
363         print("unable to read /proc/meminfo for memory")
364     else:
365         print("total physical memory: {} kb".format(memory))
366         
367
368     print("")
369
370     kernel_version = None
371     if len(sys.argv) > 2:
372         kernel_version = sys.argv[1]
373         
374     modules = get_system_modules()
375     if not modules:
376         print("unable to list system modules")
377     else:
378         for module_class in (MODULE_CLASS_SCSI, MODULE_CLASS_NETWORK):
379             if len(modules[module_class]) > 0:
380                 module_list = ""
381                 for a_mod in modules[module_class]:
382                     module_list = module_list + "{} ".format(a_mod)
383                 print("all {} modules: {}".format(module_class, module_list))
384