ec7eca35ce7dc5162f39d594528b5a2323fa6f27
[ta/hw-detector.git] / src / hw_detector / hw_ipmi_lib.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import subprocess
16 import os
17
18 from hw_detector.hw_exception import HWException
19
20 def get_ipmi_info(ipmi_addr, ipmi_user, ipmi_pass, ipmi_priv_level='ADMINISTRATOR'):
21     command = "ipmitool -I lanplus -H %s  -U %s -P %s -L %s fru print 0" % (ipmi_addr, ipmi_user, ipmi_pass, ipmi_priv_level)
22     info = ipmi_info(command)
23
24     command = "ipmitool -I lanplus -H %s  -U %s -P %s -L %s lan print" % (ipmi_addr, ipmi_user, ipmi_pass, ipmi_priv_level)
25     info.update(ipmi_info(command))
26
27     return info
28
29 def _load_ipmi_drivers():
30     with open(os.devnull, 'w') as devnull:
31         subprocess.call('modprobe ipmi_msghandler', stderr=devnull, shell=True)
32         subprocess.call('modprobe ipmi_devintf', stderr=devnull, shell=True)
33         subprocess.call('modprobe ipmi_si', stderr=devnull, shell=True)
34
35 def get_local_ipmi_info():
36     _load_ipmi_drivers()
37     info = ipmi_info("ipmitool fru print 0")
38     info.update(ipmi_info("ipmitool lan print"))
39     return info
40
41 def ipmi_info(command):
42     out = None
43     p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
44     out, _ = p.communicate()
45
46     if p.returncode:
47         raise HWException(out)
48
49     info = {}
50     for line in out.split('\n'):
51         spl = line.find(':')
52         if spl == -1:
53             continue
54         else:
55             key = line[0:spl].strip()
56             if key == '':
57                 continue
58             info[line[0:spl].strip()] = line[spl+1:].strip()
59     return info