summaryrefslogtreecommitdiffstats
path: root/glances/compat.py
blob: 00374a1d4c87bbf157784bbb1a2521e39d430c71 (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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# Copyright (C) 2019 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

# flake8: noqa
# pylint: skip-file
"""Python 2/3 compatibility shims."""

from __future__ import print_function, unicode_literals

import operator
import sys
import unicodedata
import types
import subprocess
import os

from glances.logger import logger

PY3 = sys.version_info[0] == 3

if PY3:
    import queue
    from configparser import ConfigParser, NoOptionError, NoSectionError
    from statistics import mean
    from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server
    from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
    from urllib.request import urlopen
    from urllib.error import HTTPError, URLError
    from urllib.parse import urlparse

    input = input
    range = range
    map = map

    text_type = str
    binary_type = bytes
    bool_type = bool
    long = int

    viewkeys = operator.methodcaller('keys')
    viewvalues = operator.methodcaller('values')
    viewitems = operator.methodcaller('items')

    def printandflush(string):
        """Print and flush (used by stdout* outputs modules)"""
        print(string, flush=True)

    def to_ascii(s):
        """Convert the bytes string to a ASCII string
        Usefull to remove accent (diacritics)"""
        if isinstance(s, binary_type):
            return s.decode()
        return s.encode('ascii', 'ignore').decode()

    def listitems(d):
        return list(d.items())

    def listkeys(d):
        return list(d.keys())

    def listvalues(d):
        return list(d.values())

    def iteritems(d):
        return iter(d.items())

    def iterkeys(d):
        return iter(d.keys())

    def itervalues(d):
        return iter(d.values())

    def u(s, errors='replace'):
        if isinstance(s, text_type):
            return s
        return s.decode('utf-8', errors=errors)

    def b(s, errors='replace'):
        if isinstance(s, binary_type):
            return s
        return s.encode('utf-8', errors=errors)

    def n(s):
        '''Only in Python 2...
        from future.utils import bytes_to_native_str as n
        '''
        return s

    def nativestr(s, errors='replace'):
        if isinstance(s, text_type):
            return s
        elif isinstance(s, (int, float)):
            return s.__str__()
        else:
            return s.decode('utf-8', errors=errors)

    def system_exec(command):
        """Execute a system command and return the resul as a str"""
        try:
            res = subprocess.run(command.split(' '),
                                 stdout=subprocess.PIPE).stdout.decode('utf-8')
        except Exception as e:
            logger.debug('Can not evaluate command {} ({})'.format(command, e))
            res = ''
        return res.rstrip()

else:
    from future.utils import bytes_to_native_str as n
    import Queue as queue
    from itertools import imap as map
    from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError, NoSectionError
    from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
    from xmlrpclib import Fault, ProtocolError, ServerProxy, Transport, Server
    from urllib2 import urlopen, HTTPError, URLError
    from urlparse import urlparse

    input = raw_input
    range = xrange
    ConfigParser.read_file = ConfigParser.readfp

    text_type = unicode
    binary_type = str
    bool_type = types.BooleanType
    long = long

    viewkeys = operator.methodcaller('viewkeys')
    viewvalues = operator.methodcaller('viewvalues')
    viewitems = operator.methodcaller('viewitems')

    def printandflush(string):
        """Print and flush (used by stdout* outputs modules)"""
        print(string)
        sys.stdout.flush()

    def mean(numbers):
        return float(sum(numbers)) / max(len(numbers), 1)

    def to_ascii(s):
        """Convert the unicode 's' to a ASCII string
        Usefull to remove accent (diacritics)"""
        if isinstance(s, binary_type):
            return s
        return unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')

    def listitems(d):
        return d.items()

    def listkeys(d):
        return d.keys()

    def listvalues(d):
        return d.values()

    def iteritems(d):
        return d.iteritems()

    def iterkeys(d):
        return d.iterkeys()

    def itervalues(d):
        return d.itervalues()

    def u(s, errors='replace'):
        if isinstance(s, text_type):
            return s.encode('utf-8', errors=errors)
        return s.decode('utf-8', errors=errors)

    def b(s, errors='replace'):
        if isinstance(s, binary_type):
            return s
        return s.encode('utf-8', errors=errors)

    def nativestr(s, errors='replace'):
        if isinstance(s, binary_type):
            return s
        elif isinstance(s, (int, float)):
            return s.__str__()
        else:
            return s.encode('utf-8', errors=errors)

    def system_exec(command):
        """Execute a system command and return the resul as a str"""
        try:
            res = subprocess.check_output(command.split(' '))
        except Exception as e:
            logger.debug('Can not execute command {} ({})'.format(command, e))
            res = ''
        return res.rstrip()


# Globals functions for both Python 2 and 3


def subsample(data, sampling):
    """Compute a simple mean subsampling.

    Data should be a list of numerical itervalues

    Return a subsampled list of sampling lenght
    """
    if len(data) <= sampling:
        return data
    sampling_length = int(round(len(data) / float(sampling)))
    return [mean(data[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]


def time_serie_subsample(data, sampling):
    """Compute a simple mean subsampling.

    Data should be a list of set (time, value)

    Return a subsampled list of sampling lenght
    """
    if len(data) <= sampling:
        return data
    t = [t[0] for t in data]
    v = [t[1] for t in data]
    sampling_length = int(round(len(data) / float(sampling)))
    t_subsampled = [t[s * sampling_length:(s + 1) * sampling_length][0] for s in range(0, sampling)]
    v_subsampled = [mean(v[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
    return list(zip(t_subsampled, v_subsampled))


def to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit."""
    return celsius * 1.8 + 32


def is_admin():
    """
    https://stackoverflow.com/a/19719292
    @return: True if the current user is an 'Admin' whatever that
    means (root on Unix), otherwise False.
    Warning: The inner function fails unless you have Windows XP SP2 or
    higher. The failure causes a traceback to be printed and this
    function to return False.
    """

    if os.name == 'nt':
        import ctypes
        import traceback
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except Exception as e:
            traceback.print_exc()
            return False
    else:
        # Check for root on Posix
        return os.getuid() == 0


def get_stat_from_path(stats, stat_path):
    """
    For a path ['cpu, 'user'] or ['network'] or ['processlist:6174', 'name']
    Get the value in the stats.
    """
    ret = dict()
    if ':' in stat_path[0]:
        plugin, match = stat_path[0].split(':')
    else:
        plugin = stat_path[0]
        match = None
    attributes = stat_path[1:]

    if plugin in stats.getPluginsList() and \
        stats.get_plugin(plugin).is_enable():
        # Get the stat
        stat_export = stats.get_plugin(plugin).get_export()
        if isinstance(stat_export, dict):
            if len(attributes) > 0 and attributes[0] in stat_export:
                ret['{}.{}'.format(plugin, attributes[0])] = stat_export[attributes[0]]
            else:
                for k, v in iteritems(stat_export):
                    ret['{}.{}'.format(plugin, k)] = v
        elif isinstance(stat_export, list):
            for i in stat_export:
                if isinstance(i, dict) and 'key' in i and (not match or (match and str(i[i['key']]) == match)):
                    if len(attributes) > 0 and attributes[0] in i:
                        ret['{}.{}.{}'.format(plugin, i[i['key']], attributes[0])] = i[attributes[0]]
                    else:
                        for k, v in iteritems(i):
                            ret['{}.{}.{}'.format(plugin, i[i['key']], k)] =</