This commit is contained in:
nicolargo 2024-05-20 19:35:56 +02:00
parent ba88263b85
commit 60d6be1718
4 changed files with 70 additions and 44 deletions

View File

@ -36,6 +36,7 @@ class GlancesClient:
self.args = args
self.config = config
print(args)
self._quiet = args.quiet
self.refresh_time = args.time

View File

@ -8,13 +8,14 @@
"""Manage the Glances server."""
import json
import socket
import sys
from base64 import b64decode
from glances import __version__
from glances.autodiscover import GlancesAutoDiscoverClient
from glances.globals import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer, json_dumps
from glances.globals import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
from glances.logger import logger
from glances.stats_server import GlancesStatsServer
from glances.timer import Timer
@ -140,39 +141,50 @@ class GlancesInstance:
def getAll(self):
# Update and return all the stats
self.__update__()
return json_dumps(self.stats.getAll())
return json.dumps(self.stats.getAll())
def getAllPlugins(self):
# Return the plugins list
return json_dumps(self.stats.getPluginsList())
return json.dumps(self.stats.getPluginsList())
def getAllLimits(self):
# Return all the plugins limits
return json_dumps(self.stats.getAllLimitsAsDict())
return json.dumps(self.stats.getAllLimitsAsDict())
def getAllViews(self):
# Return all the plugins views
return json_dumps(self.stats.getAllViewsAsDict())
return json.dumps(self.stats.getAllViewsAsDict())
def __getattr__(self, item):
"""Overwrite the getattr method in case of attribute is not found.
def getPlugin(self, plugin):
# Update and return the system stats
self.__update__()
return json.dumps(self.stats.get_plugin(plugin).get_raw())
The goal is to dynamically generate the API get'Stats'() methods.
"""
header = 'get'
# Check if the attribute starts with 'get'
if item.startswith(header):
try:
# Update the stat
self.__update__()
# Return the attribute
return getattr(self.stats, item)
except Exception:
# The method is not found for the plugin
raise AttributeError(item)
else:
# Default behavior
raise AttributeError(item)
# ['alert', 'ports', 'diskio', 'containers', 'processcount', 'gpu',
# 'percpu', 'system', 'network', 'cpu', 'amps', 'processlist',
# 'load', 'sensors', 'uptime', 'now', 'fs', 'wifi', 'ip', 'help',
# 'version', 'psutilversion', 'core', 'mem', 'folders', 'quicklook', 'memswap', 'raid']
# It works...
# def getSystem(self):
# return self._get_plugin('system')
# Do not work...
# def __getattr__(self, item):
# """Overwrite the getattr method in case of attribute is not found.
# The goal is to dynamically generate the API get'Stats'() methods.
# """
# header = 'get'
# # Check if the attribute starts with 'get'
# if item.startswith(header):
# try:
# return self._get_plugin(item[len(header):])
# except Exception:
# # The method is not found for the plugin
# raise AttributeError(item)
# else:
# # Default behavior
# raise AttributeError(item)
class GlancesServer:

View File

@ -52,7 +52,7 @@ class GlancesStats:
# Get the plugin instance
plugin = self._plugins[plugname]
if hasattr(plugin, 'get_json_views'):
# The method get_views exist, return it
# The method get_json_views exist, return it
return getattr(plugin, 'get_json_views')
# The method get_views is not found for the plugin
raise AttributeError(item)
@ -61,9 +61,9 @@ class GlancesStats:
plugname = item[len('get') :].lower()
# Get the plugin instance
plugin = self._plugins[plugname]
if hasattr(plugin, 'get_stats'):
# The method get_stats exist, return it
return getattr(plugin, 'get_stats')
if hasattr(plugin, 'get_json'):
# The method get_json exist, return it
return getattr(plugin, 'get_json')
# The method get_stats is not found for the plugin
raise AttributeError(item)
# Default behavior

View File

@ -17,14 +17,24 @@ import time
import unittest
from glances import __version__
from glances.globals import ServerProxy
from glances.client import GlancesClient
SERVER_HOST = 'localhost'
SERVER_PORT = 61234
URL = f"http://localhost:{SERVER_PORT}"
pid = None
# Init the XML-RPC client
client = ServerProxy(URL)
class args:
client = SERVER_HOST
port = SERVER_PORT
username = ""
password = ""
time = 3
quiet = False
client = GlancesClient(args=args).client
# Unitest class
# ==============
@ -71,14 +81,16 @@ class TestGlances(unittest.TestCase):
print('INFO: [TEST_002] Get plugins list')
print(f"XML-RPC request: {method}")
req = json.loads(client.getAllPlugins())
print(req)
self.assertIsInstance(req, list)
self.assertIn('cpu', req)
def test_003_system(self):
"""System."""
method = "getSystem()"
print(f'INFO: [TEST_003] Method: {method}')
req = json.loads(client.getSystem())
req = json.loads(client.getPlugin('system'))
self.assertIsInstance(req, dict)
@ -87,16 +99,16 @@ class TestGlances(unittest.TestCase):
method = "getCpu(), getPerCpu(), getLoad() and getCore()"
print(f'INFO: [TEST_004] Method: {method}')
req = json.loads(client.getCpu())
req = json.loads(client.getPlugin('cpu'))
self.assertIsInstance(req, dict)
req = json.loads(client.getPerCpu())
req = json.loads(client.getPlugin('percpu'))
self.assertIsInstance(req, list)
req = json.loads(client.getLoad())
req = json.loads(client.getPlugin('load'))
self.assertIsInstance(req, dict)
req = json.loads(client.getCore())
req = json.loads(client.getPlugin('core'))
self.assertIsInstance(req, dict)
def test_005_mem(self):
@ -104,10 +116,10 @@ class TestGlances(unittest.TestCase):
method = "getMem() and getMemSwap()"
print(f'INFO: [TEST_005] Method: {method}')
req = json.loads(client.getMem())
req = json.loads(client.getPlugin('mem'))
self.assertIsInstance(req, dict)
req = json.loads(client.getMemSwap())
req = json.loads(client.getPlugin('memswap'))
self.assertIsInstance(req, dict)
def test_006_net(self):
@ -115,7 +127,7 @@ class TestGlances(unittest.TestCase):
method = "getNetwork()"
print(f'INFO: [TEST_006] Method: {method}')
req = json.loads(client.getNetwork())
req = json.loads(client.getPlugin('network'))
self.assertIsInstance(req, list)
def test_007_disk(self):
@ -123,13 +135,13 @@ class TestGlances(unittest.TestCase):
method = "getFs(), getFolders() and getDiskIO()"
print(f'INFO: [TEST_007] Method: {method}')
req = json.loads(client.getFs())
req = json.loads(client.getPlugin('fs'))
self.assertIsInstance(req, list)
req = json.loads(client.getFolders())
req = json.loads(client.getPlugin('folders'))
self.assertIsInstance(req, list)
req = json.loads(client.getDiskIO())
req = json.loads(client.getPlugin('diskio'))
self.assertIsInstance(req, list)
def test_008_sensors(self):
@ -137,7 +149,7 @@ class TestGlances(unittest.TestCase):
method = "getSensors()"
print(f'INFO: [TEST_008] Method: {method}')
req = json.loads(client.getSensors())
req = json.loads(client.getPlugin('sensors'))
self.assertIsInstance(req, list)
def test_009_process(self):
@ -145,10 +157,10 @@ class TestGlances(unittest.TestCase):
method = "getProcessCount() and getProcessList()"
print(f'INFO: [TEST_009] Method: {method}')
req = json.loads(client.getProcessCount())
req = json.loads(client.getPlugin('processcount'))
self.assertIsInstance(req, dict)
req = json.loads(client.getProcessList())
req = json.loads(client.getPlugin('processlist'))
self.assertIsInstance(req, list)
def test_010_all_limits(self):
@ -187,6 +199,7 @@ class TestGlances(unittest.TestCase):
def test_999_stop_server(self):
"""Stop the Glances Web Server."""
print('INFO: [TEST_999] Stop the Glances Server')
print(client.system.listMethods())
print("Stop the Glances Server")
pid.terminate()