Debian Codegraph @

lib/ansible/module_utils/facts/hardware/freebsd.py

raw
1 # This file is part of Ansible
2 #
3 # Ansible is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # Ansible is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
15
16 from __future__ import annotations
17
18 import os
19 import json
20 import re
21 import struct
22 import time
23
24 from ansible.module_utils.facts.hardware.base import Hardware, HardwareCollector
25 from ansible.module_utils.facts.timeout import TimeoutError, timeout
26 from ansible.module_utils.facts.utils import get_file_content, get_mount_size
27
28
29 class FreeBSDHardware(Hardware):
30 """
31 FreeBSD-specific subclass of Hardware. Defines memory and CPU facts:
32 - memfree_mb
33 - memtotal_mb
34 - swapfree_mb
35 - swaptotal_mb
36 - processor (a list)
37 - processor_cores
38 - processor_count
39 - devices
40 - uptime_seconds
41 """
42 platform = 'FreeBSD'
43 DMESG_BOOT = '/var/run/dmesg.boot'
44
45 def populate(self, collected_facts=None):
46 hardware_facts = {}
47
48 cpu_facts = self.get_cpu_facts()
49 memory_facts = self.get_memory_facts()
50 uptime_facts = self.get_uptime_facts()
51 dmi_facts = self.get_dmi_facts()
52 device_facts = self.get_device_facts()
53
54 mount_facts = {}
55 try:
56 mount_facts = self.get_mount_facts()
57 except TimeoutError:
58 pass
59
60 hardware_facts.update(cpu_facts)
61 hardware_facts.update(memory_facts)
62 hardware_facts.update(uptime_facts)
63 hardware_facts.update(dmi_facts)
64 hardware_facts.update(device_facts)
65 hardware_facts.update(mount_facts)
66
67 return hardware_facts
68
69 def get_cpu_facts(self):
70 cpu_facts = {}
71 cpu_facts['processor'] = []
72 sysctl = self.module.get_bin_path('sysctl')
73 if sysctl:
74 rc, out, err = self.module.run_command("%s -n hw.ncpu" % sysctl, check_rc=False)
75 cpu_facts['processor_count'] = out.strip()
76
77 dmesg_boot = get_file_content(FreeBSDHardware.DMESG_BOOT)
78 if not dmesg_boot:
79 try:
80 rc, dmesg_boot, err = self.module.run_command(self.module.get_bin_path("dmesg"), check_rc=False)
81 except Exception:
82 dmesg_boot = ''
83
84 for line in dmesg_boot.splitlines():
85 if 'CPU:' in line:
86 cpu = re.sub(r'CPU:\s+', r"", line)
87 cpu_facts['processor'].append(cpu.strip())
88 if 'Logical CPUs per core' in line:
89 cpu_facts['processor_cores'] = line.split()[4]
90
91 return cpu_facts
92
93 def get_memory_facts(self):
94 memory_facts = {}
95
96 sysctl = self.module.get_bin_path('sysctl')
97 if sysctl:
98 rc, out, err = self.module.run_command("%s vm.stats" % sysctl, check_rc=False)
99 for line in out.splitlines():
100 data = line.split()
101 if 'vm.stats.vm.v_page_size' in line:
102 pagesize = int(data[1])
103 if 'vm.stats.vm.v_page_count' in line:
104 pagecount = int(data[1])
105 if 'vm.stats.vm.v_free_count' in line:
106 freecount = int(data[1])
107 memory_facts['memtotal_mb'] = pagesize * pagecount // 1024 // 1024
108 memory_facts['memfree_mb'] = pagesize * freecount // 1024 // 1024
109
110 swapinfo = self.module.get_bin_path('swapinfo')
111 if swapinfo:
112 # Get swapinfo. swapinfo output looks like:
113 # Device 1M-blocks Used Avail Capacity
114 # /dev/ada0p3 314368 0 314368 0%
115 #
116 rc, out, err = self.module.run_command("%s -k" % swapinfo)
117 lines = out.splitlines()
118 if len(lines[-1]) == 0:
119 lines.pop()
120 data = lines[-1].split()
121 if data[0] != 'Device':
122 memory_facts['swaptotal_mb'] = int(data[1]) // 1024
123 memory_facts['swapfree_mb'] = int(data[3]) // 1024
124
125 return memory_facts
126
127 def get_uptime_facts(self):
128 # On FreeBSD, the default format is annoying to parse.
129 # Use -b to get the raw value and decode it.
130 sysctl_cmd = self.module.get_bin_path('sysctl')
131 cmd = [sysctl_cmd, '-b', 'kern.boottime']
132
133 # We need to get raw bytes, not UTF-8.
134 rc, out, err = self.module.run_command(cmd, encoding=None)
135
136 # kern.boottime returns seconds and microseconds as two 64-bits
137 # fields, but we are only interested in the first field.
138 struct_format = '@L'
139 struct_size = struct.calcsize(struct_format)
140 if rc != 0 or len(out) < struct_size:
141 return {}
142
143 (kern_boottime, ) = struct.unpack(struct_format, out[:struct_size])
144
145 return {
146 'uptime_seconds': int(time.time() - kern_boottime),
147 }
148
149 @timeout()
150 def get_mount_facts(self):
151 mount_facts = {}
152
153 mount_facts['mounts'] = []
154 fstab = get_file_content('/etc/fstab')
155 if fstab:
156 for line in fstab.splitlines():
157 if line.startswith('#') or line.strip() == '':
158 continue
159 fields = re.sub(r'\s+', ' ', line).split()
160 mount_statvfs_info = get_mount_size(fields[1])
161 mount_info = {'mount': fields[1],
162 'device': fields[0],
163 'fstype': fields[2],
164 'options': fields[3]}
165 mount_info.update(mount_statvfs_info)
166 mount_facts['mounts'].append(mount_info)
167
168 return mount_facts
169
170 def get_device_facts(self):
171 device_facts = {}
172
173 sysdir = '/dev'
174 device_facts['devices'] = {}
175 # TODO: rc, disks, err = self.module.run_command("/sbin/sysctl kern.disks")
176 drives = re.compile(
177 r"""(?x)(
178 (?:
179 ada? # ATA/SATA disk device
180 |da # SCSI disk device
181 |a?cd # SCSI CDROM drive
182 |amrd # AMI MegaRAID drive
183 |idad # Compaq RAID array
184 |ipsd # IBM ServeRAID RAID array
185 |md # md(4) disk device
186 |mfid # LSI MegaRAID SAS array
187 |mlxd # Mylex RAID disk
188 |twed # 3ware ATA RAID array
189 |vtbd # VirtIO Block Device
190 )\d+
191 )
192 """
193 )
194
195 slices = re.compile(
196 r"""(?x)(
197 (?:
198 ada? # ATA/SATA disk device
199 |a?cd # SCSI CDROM drive
200 |amrd # AMI MegaRAID drive
201 |da # SCSI disk device
202 |idad # Compaq RAID array
203 |ipsd # IBM ServeRAID RAID array
204 |md # md(4) disk device
205 |mfid # LSI MegaRAID SAS array
206 |mlxd # Mylex RAID disk
207 |twed # 3ware ATA RAID array
208 |vtbd # VirtIO Block Device
209 )\d+[ps]\d+\w*
210 )
211 """
212 )
213
214 if os.path.isdir(sysdir):
215 dirlist = sorted(os.listdir(sysdir))
216 for device in dirlist:
217 d = drives.match(device)
218 if d and d.group(1) not in device_facts['devices']:
219 device_facts['devices'][d.group(1)] = []
220 s = slices.match(device)
221 if s:
222 device_facts['devices'][d.group(1)].append(s.group(1))
223
224 return device_facts
225
226 def get_dmi_facts(self):
227 """ learn dmi facts from system
228
229 Use dmidecode executable if available"""
230
231 dmi_facts = {}
232
233 # Fall back to using dmidecode, if available
234 dmi_bin = self.module.get_bin_path('dmidecode')
235 DMI_DICT = {
236 'bios_date': 'bios-release-date',
237 'bios_vendor': 'bios-vendor',
238 'bios_version': 'bios-version',
239 'board_asset_tag': 'baseboard-asset-tag',
240 'board_name': 'baseboard-product-name',
241 'board_serial': 'baseboard-serial-number',
242 'board_vendor': 'baseboard-manufacturer',
243 'board_version': 'baseboard-version',
244 'chassis_asset_tag': 'chassis-asset-tag',
245 'chassis_serial': 'chassis-serial-number',
246 'chassis_vendor': 'chassis-manufacturer',
247 'chassis_version': 'chassis-version',
248 'form_factor': 'chassis-type',
249 'product_name': 'system-product-name',
250 'product_serial': 'system-serial-number',
251 'product_uuid': 'system-uuid',
252 'product_version': 'system-version',
253 'system_vendor': 'system-manufacturer',
254 }
255 if dmi_bin is None:
256 dmi_facts = dict.fromkeys(
257 DMI_DICT.keys(),
258 'NA'
259 )
260 return dmi_facts
261
262 for (k, v) in DMI_DICT.items():
263 (rc, out, err) = self.module.run_command('%s -s %s' % (dmi_bin, v))
264 if rc == 0:
265 # Strip out commented lines (specific dmidecode output)
266 # FIXME: why add the fact and then test if it is json?
267 dmi_facts[k] = ''.join([line for line in out.splitlines() if not line.startswith('#')])
268 try:
269 json.dumps(dmi_facts[k])
270 except UnicodeDecodeError:
271 dmi_facts[k] = 'NA'
272 else:
273 dmi_facts[k] = 'NA'
274
275 return dmi_facts
276
277
278 class FreeBSDHardwareCollector(HardwareCollector):
279 _fact_class = FreeBSDHardware
280 _platform = 'FreeBSD'