Debian Codegraph @

lib/ansible/module_utils/facts/hardware/sunos.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 re
19 import time
20
21 from functools import reduce
22
23 from ansible.module_utils.common.locale import get_best_parsable_locale
24 from ansible.module_utils.common.text.formatters import bytes_to_human
25 from ansible.module_utils.facts.utils import get_file_content, get_mount_size
26 from ansible.module_utils.facts.hardware.base import Hardware, HardwareCollector
27 from ansible.module_utils.facts import timeout
28
29
30 class SunOSHardware(Hardware):
31 """
32 In addition to the generic memory and cpu facts, this also sets
33 swap_reserved_mb and swap_allocated_mb that is available from *swap -s*.
34 """
35 platform = 'SunOS'
36
37 def populate(self, collected_facts=None):
38 hardware_facts = {}
39
40 # FIXME: could pass to run_command(environ_update), but it also tweaks the env
41 # of the parent process instead of altering an env provided to Popen()
42 # Use C locale for hardware collection helpers to avoid locale specific number formatting (#24542)
43 locale = get_best_parsable_locale(self.module)
44 self.module.run_command_environ_update = {'LANG': locale, 'LC_ALL': locale, 'LC_NUMERIC': locale}
45
46 cpu_facts = self.get_cpu_facts()
47 memory_facts = self.get_memory_facts()
48 dmi_facts = self.get_dmi_facts()
49 device_facts = self.get_device_facts()
50 uptime_facts = self.get_uptime_facts()
51
52 mount_facts = {}
53 try:
54 mount_facts = self.get_mount_facts()
55 except timeout.TimeoutError:
56 pass
57
58 hardware_facts.update(cpu_facts)
59 hardware_facts.update(memory_facts)
60 hardware_facts.update(dmi_facts)
61 hardware_facts.update(device_facts)
62 hardware_facts.update(uptime_facts)
63 hardware_facts.update(mount_facts)
64
65 return hardware_facts
66
67 def get_cpu_facts(self, collected_facts=None):
68 physid = 0
69 sockets = {}
70
71 cpu_facts = {}
72 collected_facts = collected_facts or {}
73
74 rc, out, err = self.module.run_command("/usr/bin/kstat cpu_info")
75
76 cpu_facts['processor'] = []
77
78 for line in out.splitlines():
79 if len(line) < 1:
80 continue
81
82 data = line.split(None, 1)
83 key = data[0].strip()
84
85 # "brand" works on Solaris 10 & 11. "implementation" for Solaris 9.
86 if key == 'module:':
87 brand = ''
88 elif key == 'brand':
89 brand = data[1].strip()
90 elif key == 'clock_MHz':
91 clock_mhz = data[1].strip()
92 elif key == 'implementation':
93 processor = brand or data[1].strip()
94 # Add clock speed to description for SPARC CPU
95 # FIXME
96 if collected_facts.get('ansible_machine') != 'i86pc':
97 processor += " @ " + clock_mhz + "MHz"
98 if 'ansible_processor' not in collected_facts:
99 cpu_facts['processor'] = []
100 cpu_facts['processor'].append(processor)
101 elif key == 'chip_id':
102 physid = data[1].strip()
103 if physid not in sockets:
104 sockets[physid] = 1
105 else:
106 sockets[physid] += 1
107
108 # Counting cores on Solaris can be complicated.
109 # https://blogs.oracle.com/mandalika/entry/solaris_show_me_the_cpu
110 # Treat 'processor_count' as physical sockets and 'processor_cores' as
111 # virtual CPUs visible to Solaris. Not a true count of cores for modern SPARC as
112 # these processors have: sockets -> cores -> threads/virtual CPU.
113 if len(sockets) > 0:
114 cpu_facts['processor_count'] = len(sockets)
115 cpu_facts['processor_cores'] = reduce(lambda x, y: x + y, sockets.values())
116 else:
117 cpu_facts['processor_cores'] = 'NA'
118 cpu_facts['processor_count'] = len(cpu_facts['processor'])
119
120 return cpu_facts
121
122 def get_memory_facts(self):
123 memory_facts = {}
124
125 rc, out, err = self.module.run_command(["/usr/sbin/prtconf"])
126
127 for line in out.splitlines():
128 if 'Memory size' in line:
129 memory_facts['memtotal_mb'] = int(line.split()[2])
130
131 rc, out, err = self.module.run_command("/usr/sbin/swap -s")
132
133 allocated = int(out.split()[1][:-1])
134 reserved = int(out.split()[5][:-1])
135 used = int(out.split()[8][:-1])
136 free = int(out.split()[10][:-1])
137
138 memory_facts['swapfree_mb'] = free // 1024
139 memory_facts['swaptotal_mb'] = (free + used) // 1024
140 memory_facts['swap_allocated_mb'] = allocated // 1024
141 memory_facts['swap_reserved_mb'] = reserved // 1024
142
143 return memory_facts
144
145 @timeout.timeout()
146 def get_mount_facts(self):
147 mount_facts = {}
148 mount_facts['mounts'] = []
149
150 # For a detailed format description see mnttab(4)
151 # special mount_point fstype options time
152 fstab = get_file_content('/etc/mnttab')
153
154 if fstab:
155 for line in fstab.splitlines():
156 fields = line.split('\t')
157 mount_statvfs_info = get_mount_size(fields[1])
158 mount_info = {'mount': fields[1],
159 'device': fields[0],
160 'fstype': fields[2],
161 'options': fields[3],
162 'time': fields[4]}
163 mount_info.update(mount_statvfs_info)
164 mount_facts['mounts'].append(mount_info)
165
166 return mount_facts
167
168 def get_dmi_facts(self):
169 dmi_facts = {}
170
171 # On Solaris 8 the prtdiag wrapper is absent from /usr/sbin,
172 # but that's okay, because we know where to find the real thing:
173 rc, platform, err = self.module.run_command('/usr/bin/uname -i')
174 platform_sbin = '/usr/platform/' + platform.rstrip() + '/sbin'
175
176 prtdiag_path = self.module.get_bin_path(
177 "prtdiag",
178 opt_dirs=[platform_sbin]
179 )
180 if prtdiag_path is None:
181 return dmi_facts
182
183 rc, out, err = self.module.run_command(prtdiag_path)
184 # rc returns 1
185 if out:
186 system_conf = out.split('\n')[0]
187
188 # If you know of any other manufacturers whose names appear in
189 # the first line of prtdiag's output, please add them here:
190 vendors = [
191 "Fujitsu",
192 "Oracle Corporation",
193 "QEMU",
194 "Sun Microsystems",
195 "VMware, Inc.",
196 ]
197 vendor_regexp = "|".join(map(re.escape, vendors))
198 system_conf_regexp = (r'System Configuration:\s+'
199 + r'(' + vendor_regexp + r')\s+'
200 + r'(?:sun\w+\s+)?'
201 + r'(.+)')
202
203 found = re.match(system_conf_regexp, system_conf)
204 if found:
205 dmi_facts['system_vendor'] = found.group(1)
206 dmi_facts['product_name'] = found.group(2)
207
208 return dmi_facts
209
210 def get_device_facts(self):
211 # Device facts are derived for sdderr kstats. This code does not use the
212 # full output, but rather queries for specific stats.
213 # Example output:
214 # sderr:0:sd0,err:Hard Errors 0
215 # sderr:0:sd0,err:Illegal Request 6
216 # sderr:0:sd0,err:Media Error 0
217 # sderr:0:sd0,err:Predictive Failure Analysis 0
218 # sderr:0:sd0,err:Product VBOX HARDDISK 9
219 # sderr:0:sd0,err:Revision 1.0
220 # sderr:0:sd0,err:Serial No VB0ad2ec4d-074a
221 # sderr:0:sd0,err:Size 53687091200
222 # sderr:0:sd0,err:Soft Errors 0
223 # sderr:0:sd0,err:Transport Errors 0
224 # sderr:0:sd0,err:Vendor ATA
225
226 device_facts = {}
227 device_facts['devices'] = {}
228
229 disk_stats = {
230 'Product': 'product',
231 'Revision': 'revision',
232 'Serial No': 'serial',
233 'Size': 'size',
234 'Vendor': 'vendor',
235 'Hard Errors': 'hard_errors',
236 'Soft Errors': 'soft_errors',
237 'Transport Errors': 'transport_errors',
238 'Media Error': 'media_errors',
239 'Predictive Failure Analysis': 'predictive_failure_analysis',
240 'Illegal Request': 'illegal_request',
241 }
242
243 cmd = ['/usr/bin/kstat', '-p']
244
245 for ds in disk_stats:
246 cmd.append('sderr:::%s' % ds)
247
248 d = {}
249 rc, out, err = self.module.run_command(cmd)
250 if rc != 0:
251 return device_facts
252
253 sd_instances = frozenset(line.split(':')[1] for line in out.split('\n') if line.startswith('sderr'))
254 for instance in sd_instances:
255 lines = (line for line in out.split('\n') if ':' in line and line.split(':')[1] == instance)
256 for line in lines:
257 text, value = line.split('\t')
258 stat = text.split(':')[3]
259
260 if stat == 'Size':
261 d[disk_stats.get(stat)] = bytes_to_human(float(value))
262 else:
263 d[disk_stats.get(stat)] = value.rstrip()
264
265 diskname = 'sd' + instance
266 device_facts['devices'][diskname] = d
267 d = {}
268
269 return device_facts
270
271 def get_uptime_facts(self):
272 uptime_facts = {}
273 # sample kstat output:
274 # unix:0:system_misc:boot_time 1548249689
275 rc, out, err = self.module.run_command('/usr/bin/kstat -p unix:0:system_misc:boot_time')
276
277 if rc != 0:
278 return
279
280 # uptime = $current_time - $boot_time
281 uptime_facts['uptime_seconds'] = int(time.time() - int(out.split('\t')[1]))
282
283 return uptime_facts
284
285
286 class SunOSHardwareCollector(HardwareCollector):
287 _fact_class = SunOSHardware
288 _platform = 'SunOS'
289
290 required_facts = set(['platform'])