summaryrefslogtreecommitdiffstats
path: root/commands/system/lmi/scripts/system/__init__.py
blob: 861713803314ede681f2ecfaec58177af5619c61 (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
# Copyright (C) 2013-2014 Red Hat, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of the FreeBSD Project.
#
# Author: Peter Schiffer <pschiffe@redhat.com>
#
"""
LMI system client library.
"""

from lmi.scripts.common import get_computer_system
from lmi.scripts.service import get_service
from lmi.shell.LMIExceptions import LMIClassNotFound

def _cache_replies(ns, class_name, method):
    """
    Get the reply from cimom and cache it. Cache is cleared
    once the namespace object changes.

    :param str class_name: Name of class to operate on.
    :param str method_name: Name of method to invoke on lmi class object.
    :returns: Whatever the requested method returns.
    """
    if not hasattr(_cache_replies, 'cache'):
        _cache_replies.cache = (ns, {})
    old_ns, cache = _cache_replies.cache
    if old_ns is not ns:
        # keep the cache until namespace object changes
        cache.clear()
        _cache_replies.cache = (ns, cache)
    if not (class_name, method) in cache:
        i = getattr(ns, class_name)
        cache[(class_name, method)] = getattr(i, method)()
    return cache[(class_name, method)]

def get_single_instance(ns, class_name):
    """
    Returns single instance of instance_name.

    :param instance_name: Instance name
    :type instance_name: String
    :returns: Instance of instance_name
    :rtype: :py:class:`lmi.shell.LMIInstance`
    """
    return _cache_replies(ns, class_name, 'first_instance')

def get_all_instances(ns, class_name):
    """
    Returns all instances of instance_name.

    :param instance_name: Instance name
    :type instance_name: String
    :returns: List of instances of instance_name
    :rtype: List of :py:class:`lmi.shell.LMIInstance`
    """
    return _cache_replies(ns, class_name, 'instances')

def format_memory_size(size):
    """
    Returns formatted memory size.

    :param size: Size in bytes
    :type size: Number
    :returns: Formatted size string.
    :rtype: String
    """
    if not size:
        return 'N/A GB'
    if size >= 1099511627776:
        sizestr = '%.1f TB' % (float(size) / 1099511627776.0)
    elif size >= 1073741824:
        sizestr = '%.1f GB' % (float(size) / 1073741824.0)
    elif size >= 1048576:
        sizestr = '%d MB' % (int(size) / 1048576)
    elif size >= 1024:
        sizestr = '%d KB' % (int(size) / 1024)
    else:
        sizestr = '%d B' % int(size)
    return sizestr

def get_system_info(ns):
    """
    :returns: Tabular data of all general system information.
    :rtype: List of tuples
    """
    result = get_hostname(ns)
    result += get_hwinfo(ns)
    result += get_osinfo(ns)
    result += get_servicesinfo(ns)
    result += get_networkinfo(ns)
    return result

def get_hostname(ns):
    """
    :returns: Tabular data of system hostname.
    :rtype: List of tuples
    """
    i = get_computer_system(ns)
    return [('Computer Name:', i.Name)]

def get_hwinfo(ns):
    """
    :returns: Tabular data of system hw info.
    :rtype: List of tuples
    """
    # Chassis
    try:
        chassis = get_single_instance(ns, 'LMI_Chassis')
    except LMIClassNotFound:
        chassis = None
    if chassis:
        hwinfo = chassis.Manufacturer
        if chassis.Model and chassis.Model != 'Not Specified' \
                and chassis.Model != chassis.Manufacturer:
            hwinfo += ' ' + chassis.Model
        elif chassis.ProductName and chassis.ProductName != 'Not Specified' \
                and chassis.ProductName != chassis.Manufacturer:
            hwinfo += ' ' + chassis.ProductName
        virt = getattr(chassis, 'VirtualMachine', None)
        if virt and virt != 'No':
            hwinfo += ' (%s virtual machine)' % virt
    else:
        hwinfo = 'N/A'
    # CPUs
    try:
        cpus = get_all_instances(ns, 'LMI_Processor')
    except LMIClassNotFound:
        cpus = None
    if cpus:
        cpus_str = '%dx %s' % (len(cpus), cpus[0].Name)
    else:
        cpus_str = 'N/A'
    # Memory
    try:
        memory = get_single_instance(ns, 'LMI_Memory')
    except LMIClassNotFound:
        memory = None
    if memory:
        memory_size = format_memory_size(memory.NumberOfBlocks)
    else:
        memory_size = 'N/A GB'
    # Result
    result = [
        ('Hardware:', hwinfo),
        ('Processors:', cpus_str),
        ('Memory:', memory_size)]
    return result

def get_osinfo(ns):
    """
    :returns: Tabular data of system OS info.
    :rtype: List of tuples
    """
    # OS
    try:
        os = get_single_instance(ns, 'PG_OperatingSystem')
    except LMIClassNotFound:
        os = None
    os_str = ''
    kernel_str = ''
    if os:
        os_str = os.Caption
        kernel_str = os.Version
    if not os_str:
        os_str = 'N/A'
    if not kernel_str:
        kernel_str = 'N/A'
    # Result
    result = [
        ('OS:', os_str),
        ('Kernel:', kernel_str)]
    return result

def get_servicesinfo(ns):
    """
    :returns: Tabular data of some system services.
    :rtype: List of tuples
    """
    # Firewall
    try:
        fw = ''
        firewalld = get_service(ns, 'firewalld.service')
        if firewalld and firewalld.Status == 'OK':
            fw = 'on (firewalld)'
        else:
            iptables = get_service(ns, 'iptables.service')
            if iptables and iptables.Status == 'OK':
                fw = 'on (iptables)'
        if not fw:
            fw = 'off'
    except LMIClassNotFound:
        fw = 'N/A'
    # Logging
    try:
        logging = ''
        journald = get_service(ns, 'systemd-journald.service')
        if journald and journald.Status == 'OK':
            logging = 'on (journald)'
        else:
            rsyslog = get_service(ns, 'rsyslog.service')
            if rsyslog and rsyslog.Status == 'OK':
                logging = 'on (rsyslog)'
        if not logging:
            logging = 'off'
    except LMIClassNotFound:
        logging = 'N/A'
    # Result
    result = [
        ('Firewall:', fw),
        ('Logging:', logging)]
    return result

def get_networkinfo(ns):
    """
    :returns: Tabular data of networking status.
    :rtype: List of tuples
    """
    result = [('', ''), ('Networking', '')]
    try:
        lan_endpoints = get_all_instances(ns, 'LMI_LANEndpoint')
    except LMIClassNotFound:
        result.append(('  N/A', ''))
        return result
    nic = 1
    for lan_endpoint in lan_endpoints:
        if lan_endpoint.Name == 'lo':
            continue
        result += [
            ('  NIC %d' % nic, ''),
            ('    Name:', lan_endpoint.Name)]
        try:
            ip_net_con = lan_endpoint.associators(
                ResultClass='LMI_IPNetworkConnection')[0]
            result.append(('    Status:',
                ns.LMI_IPNetworkConnection.OperatingStatusValues.value_name(
                ip_net_con.OperatingStatus)))
        except LMIClassNotFound:
            pass
        try:
            for ip_protocol_endpoint in lan_endpoint.associators(
                    ResultClass='LMI_IPProtocolEndpoint'):
                if ip_protocol_endpoint.ProtocolIFType == \
                        ns.LMI_IPProtocolEndpoint.ProtocolIFTypeValues.IPv4:
                    result.append(('    IPv4 Address:',
                        ip_protocol_endpoint.IPv4Address))
                elif ip_protocol_endpoint.ProtocolIFType == \
                        ns.LMI_IPProtocolEndpoint.ProtocolIFTypeValues.IPv6:
                    result.append(('    IPv6 Address:',
                        ip_protocol_endpoint.IPv6Address))
        except LMIClassNotFound:
            pass
        result += [
            ('    MAC Address:', lan_endpoint.MACAddress)]
        nic += 1
    return result