|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
# |
|
3
|
|
|
# This file is part of Glances. |
|
4
|
|
|
# |
|
5
|
|
|
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]> |
|
6
|
|
|
# |
|
7
|
|
|
# SPDX-License-Identifier: LGPL-3.0-only |
|
8
|
|
|
# |
|
9
|
|
|
|
|
10
|
|
|
"""Common objects shared by all Glances modules.""" |
|
11
|
|
|
|
|
12
|
|
|
import errno |
|
13
|
|
|
import os |
|
14
|
|
|
import sys |
|
15
|
|
|
import platform |
|
16
|
|
|
import json |
|
17
|
|
|
from operator import itemgetter |
|
18
|
|
|
|
|
19
|
|
|
# OS constants (some libraries/features are OS-dependent) |
|
20
|
|
|
BSD = sys.platform.find('bsd') != -1 |
|
21
|
|
|
LINUX = sys.platform.startswith('linux') |
|
22
|
|
|
MACOS = sys.platform.startswith('darwin') |
|
23
|
|
|
SUNOS = sys.platform.startswith('sunos') |
|
24
|
|
|
WINDOWS = sys.platform.startswith('win') |
|
25
|
|
|
WSL = "linux" in platform.system().lower() and "microsoft" in platform.uname()[3].lower() |
|
26
|
|
|
|
|
27
|
|
|
# Set the AMPs, plugins and export modules path |
|
28
|
|
|
work_path = os.path.realpath(os.path.dirname(__file__)) |
|
29
|
|
|
amps_path = os.path.realpath(os.path.join(work_path, 'amps')) |
|
30
|
|
|
plugins_path = os.path.realpath(os.path.join(work_path, 'plugins')) |
|
31
|
|
|
exports_path = os.path.realpath(os.path.join(work_path, 'exports')) |
|
32
|
|
|
sys_path = sys.path[:] |
|
33
|
|
|
sys.path.insert(1, exports_path) |
|
34
|
|
|
sys.path.insert(1, plugins_path) |
|
35
|
|
|
sys.path.insert(1, amps_path) |
|
36
|
|
|
|
|
37
|
|
|
|
|
38
|
|
|
def safe_makedirs(path): |
|
39
|
|
|
"""A safe function for creating a directory tree.""" |
|
40
|
|
|
try: |
|
41
|
|
|
os.makedirs(path) |
|
42
|
|
|
except OSError as err: |
|
43
|
|
|
if err.errno == errno.EEXIST: |
|
44
|
|
|
if not os.path.isdir(path): |
|
45
|
|
|
raise |
|
46
|
|
|
else: |
|
47
|
|
|
raise |
|
48
|
|
|
|
|
49
|
|
|
|
|
50
|
|
|
def json_dumps(data): |
|
51
|
|
|
"""Return the object data in a JSON format. |
|
52
|
|
|
|
|
53
|
|
|
Manage the issue #815 for Windows OS with UnicodeDecodeError catching. |
|
54
|
|
|
""" |
|
55
|
|
|
try: |
|
56
|
|
|
return json.dumps(data) |
|
57
|
|
|
except UnicodeDecodeError: |
|
58
|
|
|
return json.dumps(data, ensure_ascii=False) |
|
59
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
def json_dumps_dictlist(data, item): |
|
62
|
|
|
if isinstance(data, dict): |
|
63
|
|
|
try: |
|
64
|
|
|
return json_dumps({item: data[item]}) |
|
65
|
|
|
except: |
|
66
|
|
|
return None |
|
67
|
|
|
elif isinstance(data, list): |
|
68
|
|
|
try: |
|
69
|
|
|
# Source: |
|
70
|
|
|
# http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list |
|
71
|
|
|
return json_dumps({item: map(itemgetter(item), data)}) |
|
72
|
|
|
except: |
|
73
|
|
|
return None |
|
74
|
|
|
else: |
|
75
|
|
|
return None |
|
76
|
|
|
|