diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6dfb9ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,168 @@ +.coverage* +pip-wheel-metadata/ +site/ +.venv/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# pycharm project settings +.idea/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..32eb70d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,24 @@ +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-yaml + - id: check-json + - id: check-toml + - id: check-xml + - id: forbid-new-submodules + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-merge-conflict + - id: no-commit-to-branch # blocks main commits. To bypass do git commit --allow-empty + - id: pretty-format-json + +- repo: https://github.com/google/yapf + rev: v0.40.2 # Use the sha / tag you want to point at + hooks: + - id: yapf + name: yapf + description: "A formatter for Python files." + entry: yapf + language: python + types: [ python ] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ed6ae32 --- /dev/null +++ b/LICENSE @@ -0,0 +1,216 @@ +Copyright 2024 Battelle Memorial Institute + +Licensed under the Apache License, Version 2.0 (the "License"); you may not +use this file except in compliance with the License. You may obtain a copy +of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations +under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 2885ad1..085bb27 100644 --- a/README.md +++ b/README.md @@ -1 +1,432 @@ -# volttron-sysmon \ No newline at end of file +# volttron-sysmon + +The System Monitoring Agent (colloquially “SysMon”) can be installed on the platform to monitor system resource metrics, +including but not limited to percent CPU utilization, percent system memory (RAM) utilization, and percent storage (disk) utilization based +on disk path. + +## Requires + +* python >= 3.10 +* volttron >= 10.0 + +## Installation + +Before installing, VOLTTRON should be installed and running. Its virtual environment should be active. +Information on how to install of the VOLTTRON platform can be found +[here](https://github.com/eclipse-volttron/volttron-core). + +Create a directory called `config` and use the change directory command to enter it. + +```shell +mkdir config +cd config +``` + +After entering the config directory, create a file named `sysmon_agent_config.json`, use the below JSON to populate your new file. + +For simplicity, copy all of the JSON below and switch the key `"poll": false,` to `"poll": true,` for each system resource you want to monitor. + +```json +{ + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": true, + "capture_interval": null + } + }, + "cpu_times": { + "point_name": "CPU/Times", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "sub_points": { + "user": false, + "nice": false, + "system": false, + "idle": false, + "iowait": false, + "irq": false, + "softirq": false, + "steal": false, + "guest": false, + "guest_nice": false + } + } + }, + "cpu_times_percent": { + "point_name": "CPU/TimePercentages", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "capture_interval": null, + "sub_points": { + "user": false, + "nice": false, + "system": false, + "idle": false, + "iowait": false, + "irq": false, + "softirq": false, + "steal": false, + "guest": false, + "guest_nice": false + } + } + }, + "cpu_statistics": { + "point_name": "CPU/Statistics", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "ctx_switches": false, + "interrupts": false, + "soft_interrupts": false + } + } + }, + "cpu_frequency": { + "point_name": "CPU/Frequencies", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "sub_points": { + "current": false, + "min": false, + "max": false + } + } + }, + "memory": { + "point_name": "Memory", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "total": false, + "available": true, + "percent": true, + "used": true, + "free": false, + "active": false, + "inactive": false, + "buffers": false, + "cached": false, + "shared": false, + "slab": false + } + } + }, + "disk_usage": { + "point_name": "Disk/Usage", + "check_interval": 3600, + "poll": true, + "params": { + "disk_path": ["/"], + "sub_points": { + "total": false, + "used": true, + "free": true, + "percent": true + } + } + }, + "load_average": { + "point_name": "CPU/LoadAverage", + "check_interval": 5, + "poll": true, + "params": { + "sub_points": { + "OneMinute": true, + "FiveMinute": true, + "FifteenMinute": true + } + } + }, + "swap": { + "point_name": "Swap", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "total": false, + "used": true, + "free": true, + "percent": true, + "sin": false, + "sout": false + } + } + }, + "path_usage": { + "point_name": "Disk/Path/Usage", + "check_interval": 3600, + "poll": false, + "params": { + "path_name": "/var/log/journal" + } + }, + "path_usage_rate": { + "point_name": "Disk/Path/Rate", + "check_interval": 3600, + "poll": false, + "params": { + "path_name": "/var/log/journal" + } + }, + "disk_io": { + "point_name": "Disk/IO", + "check_interval": 5, + "poll": false, + "params": { + "per_disk": false, + "included_disks": [], + "no_wrap": true, + "sub_points": { + "read_count": false, + "write_count": false, + "read_bytes": true, + "write_bytes": true, + "read_time": true, + "write_time": true, + "read_merged_count": false, + "write_merged_count": false, + "busy_time": true, + "read_throughput": true, + "write_throughput": true + } + } + }, + "network_io": { + "point_name": "Network/IO", + "check_interval": 5, + "poll": false, + "params": { + "per_nic": true, + "included_nics": [], + "no_wrap": true, + "sub_points": { + "bytes_sent": true, + "bytes_recv": true, + "packets_sent": true, + "packets_recv": true, + "errin": true, + "errout": true, + "dropin": true, + "dropout": true, + "receive_throughput": true, + "send_throughput": true + } + } + }, + "network_connections": { + "point_name": "Network/Connections", + "check_interval": 5, + "poll": false, + "params": { + "kind": "inet", + "sub_points": { + "fd": false, + "family": false, + "type": false, + "laddr": false, + "raddr": false, + "status": false, + "pid": false + } + } + }, + "network_interface_addresses": { + "point_name": "Network/Interface/Addresses", + "check_interval": 5, + "poll": false, + "params": { + "included_interfaces": [], + "sub_points": { + "family": false, + "address": false, + "netmask": false, + "broadcast": false, + "ptp": false + } + } + }, + "network_interface_statistics": { + "point_name": "Network/Interface/Addresses", + "check_interval": 5, + "poll": false, + "params": { + "included_interfaces": [], + "sub_points": { + "isup": false, + "duplex": false, + "speed": false, + "mtu": false + } + } + }, + "sensors_temperatures": { + "point_name": "Sensors/Temperatures", + "check_interval": 5, + "poll": false, + "params": { + "fahrenheit": false, + "included_sensors": [], + "sub_points": { + "label": true, + "current": true, + "high": true, + "critical": true + } + } + }, + "sensors_fans": { + "point_name": "Sensors/Fans", + "check_interval": 5, + "poll": false, + "params": { + "included_sensors": [], + "sub_points": { + "label": false, + "current": false + } + } + }, + "sensors_battery": { + "point_name": "Sensors/Battery", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "percent": false, + "secsleft": false, + "power_plugged": false + } + } + }, + "boot_time": { + "point_name": "BootTime", + "check_interval": 5, + "poll": false, + "params": {} + }, + "users": { + "point_name": "Users", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "name": false, + "terminal": false, + "host": false, + "started": false, + "pid": false + } + } + } + } +} + +``` + +Besides `poll`, there are four other important options in sysmons configuration. + +- `default_publish_type` only needs to be specified once in the configuration, this is the default publish type. +- `base_topic` also only needs to be specified once. This is the base topic. +- `point_name` changes the point name for the specific system monitor. In combination with publish_type and base_topic our data for cpu_precent would be published to volttron with a topic of: **datalogger/Log/Platform/CPU/Percent** using the below json as an example. +- `check_interval` adjusts the time in seconds to poll for new system data. This can be modified for each system resource. + +The Sysmon agent serves as a wrapper for psutil. You can adjust resource specific options by adjusting false to true in the configuration file. For detailed insights into these options and their impact, you can read the [psutil documentation](https://psutil.readthedocs.io/en/latest/) + +You may also delete any unused fields if desired. For example, a configuration to monitor just cpu_precent could look like this. + +```json +{ + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": true, + "capture_interval": null + } + } + } +} +``` + +Install and start the sysmon agent + +```bash +vctl install volttron-sysmon --vip-identity agent.sysmon --start +``` + +Add `sysmon_agent_config.json` to the configuration store + +```bash +vctl config store agent.sysmon config sysmon_agent_config.json +``` + +Observe Data + +To see data being published to the bus, install a [Listener Agent](https://pypi.org/project/volttron-listener/): + +```bash +vctl install volttron-listener --start +``` + +Periodic Publish + +At the interval specified by the configuration option for each resource, the agent will automatically query the system +for the resource utilization statistics and publish it to the message bus using the topic as previously described. The +message content for each publish will contain only a single numeric value for that specific topic. Currently, +“scrape_all” style publishes are not supported. + +The following is an example of the LoadAverage publish captured by the Listener agent in the VOLTTRON log: + +```log +2024-01-02 12:03:50,435 (volttron-listener-0.2.0rc0 2404) listener.agent(104) INFO: Peer: pubsub, Sender: volttron-sysmon-0.1.0_1:, Bus: , Topic: datalogger/Log/Platform/CPU/LoadAverage, Headers: {'Date': '2024-01-02T20:03:50.426814+00:00', 'min_compatible_version': '3.0', 'max_compatible_version': ''}, Message: +{'FifteenMinute': {'Readings': ['2024-01-02T20:03:50.426814+00:00', + 0.009765625], + 'Units': 'load_average', + 'data_type': 'float', + 'tz': 'UTC'}, + 'FiveMinute': {'Readings': ['2024-01-02T20:03:50.426814+00:00', 0.05517578125], + 'Units': 'load_average', + 'data_type': 'float', + 'tz': 'UTC'}, + 'OneMinute': {'Readings': ['2024-01-02T20:03:50.426814+00:00', 0.14404296875], + 'Units': 'load_average', + 'data_type': 'float', + 'tz': 'UTC'}} +``` + +## Disclaimer Notice + +This material was prepared as an account of work sponsored by an agency of the +United States Government. Neither the United States Government nor the United +States Department of Energy, nor Battelle, nor any of their employees, nor any +jurisdiction or organization that has cooperated in the development of these +materials, makes any warranty, express or implied, or assumes any legal +liability or responsibility for the accuracy, completeness, or usefulness or any +information, apparatus, product, software, or process disclosed, or represents +that its use would not infringe privately owned rights. + +Reference herein to any specific commercial product, process, or service by +trade name, trademark, manufacturer, or otherwise does not necessarily +constitute or imply its endorsement, recommendation, or favoring by the United +States Government or any agency thereof, or Battelle Memorial Institute. The +views and opinions of authors expressed herein do not necessarily state or +reflect those of the United States Government or any agency thereof. diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..269cadc --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000..521fb17 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- {{{ +# ===----------------------------------------------------------------------=== +# +# Installable Component of Eclipse VOLTTRON +# +# ===----------------------------------------------------------------------=== +# +# Copyright 2022 Battelle Memorial Institute +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy +# of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# ===----------------------------------------------------------------------=== +# }}} + +# Configuration file for the Sphinx documentation builder. + +# -- Project information + +project = 'VOLTTRON Sysmon Agent' +copyright = '2024, Pacific Northwest National Lab' +author = 'Pacific Northwest National Lab' + +release = '0.1' +version = '0.1.0' + +# -- General configuration + +extensions = [ + 'sphinx.ext.duration', + 'sphinx.ext.doctest', + 'sphinx.ext.autodoc', + 'sphinx.ext.autosummary', + 'sphinx.ext.intersphinx', +] + +intersphinx_mapping = { + 'python': ('https://docs.python.org/3/', None), + 'sphinx': ('https://www.sphinx-doc.org/en/master/', None), +} +intersphinx_disabled_domains = ['std'] + +templates_path = ['_templates'] + +# -- Options for HTML output + +html_theme = 'sphinx_rtd_theme' + +# -- Options for EPUB output +# epub_show_urls = 'footnote' diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000..c1ed762 --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,418 @@ +volttron-sysmon +=============== + +The System Monitoring Agent (colloquially “SysMon”) can be installed on the platform to monitor system resource metrics, including but not limited to percent CPU utilization, percent system memory (RAM) utilization, and percent storage (disk) utilization based on disk path. + +Requires +-------- + +* python >= 3.10 +* volttron >= 10.0 + +Installation +------------ + +Before installing, VOLTTRON should be installed and running. Its virtual environment should be active. Information on how to install the VOLTTRON platform can be found `here `_. + +Create a directory called ``config`` and use the change directory command to enter it. + +.. code-block:: shell + + mkdir config + cd config + +After entering the config directory, create a file named ``sysmon_agent_config.json``, use the below JSON to populate your new file. + +For simplicity, copy all of the JSON from below and switch the key ``"poll": false,`` to ``"poll": true,`` for each system resource you want to monitor. + +.. code-block:: json + + { + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": true, + "capture_interval": null + } + }, + "cpu_times": { + "point_name": "CPU/Times", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "sub_points": { + "user": false, + "nice": false, + "system": false, + "idle": false, + "iowait": false, + "irq": false, + "softirq": false, + "steal": false, + "guest": false, + "guest_nice": false + } + } + }, + "cpu_times_percent": { + "point_name": "CPU/TimePercentages", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "capture_interval": null, + "sub_points": { + "user": false, + "nice": false, + "system": false, + "idle": false, + "iowait": false, + "irq": false, + "softirq": false, + "steal": false, + "guest": false, + "guest_nice": false + } + } + }, + "cpu_statistics": { + "point_name": "CPU/Statistics", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "ctx_switches": false, + "interrupts": false, + "soft_interrupts": false + } + } + }, + "cpu_frequency": { + "point_name": "CPU/Frequencies", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "sub_points": { + "current": false, + "min": false, + "max": false + } + } + }, + "memory": { + "point_name": "Memory", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "total": false, + "available": true, + "percent": true, + "used": true, + "free": false, + "active": false, + "inactive": false, + "buffers": false, + "cached": false, + "shared": false, + "slab": false + } + } + }, + "disk_usage": { + "point_name": "Disk/Usage", + "check_interval": 3600, + "poll": true, + "params": { + "disk_path": ["/"], + "sub_points": { + "total": false, + "used": true, + "free": true, + "percent": true + } + } + }, + "load_average": { + "point_name": "CPU/LoadAverage", + "check_interval": 5, + "poll": true, + "params": { + "sub_points": { + "OneMinute": true, + "FiveMinute": true, + "FifteenMinute": true + } + } + }, + "swap": { + "point_name": "Swap", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "total": false, + "used": true, + "free": true, + "percent": true, + "sin": false, + "sout": false + } + } + }, + "path_usage": { + "point_name": "Disk/Path/Usage", + "check_interval": 3600, + "poll": false, + "params": { + "path_name": "/var/log/journal" + } + }, + "path_usage_rate": { + "point_name": "Disk/Path/Rate", + "check_interval": 3600, + "poll": false, + "params": { + "path_name": "/var/log/journal" + } + }, + "disk_io": { + "point_name": "Disk/IO", + "check_interval": 5, + "poll": false, + "params": { + "per_disk": false, + "included_disks": [], + "no_wrap": true, + "sub_points": { + "read_count": false, + "write_count": false, + "read_bytes": true, + "write_bytes": true, + "read_time": true, + "write_time": true, + "read_merged_count": false, + "write_merged_count": false, + "busy_time": true, + "read_throughput": true, + "write_throughput": true + } + } + }, + "network_io": { + "point_name": "Network/IO", + "check_interval": 5, + "poll": false, + "params": { + "per_nic": true, + "included_nics": [], + "no_wrap": true, + "sub_points": { + "bytes_sent": true, + "bytes_recv": true, + "packets_sent": true, + "packets_recv": true, + "errin": true, + "errout": true, + "dropin": true, + "dropout": true, + "receive_throughput": true, + "send_throughput": true + } + } + }, + "network_connections": { + "point_name": "Network/Connections", + "check_interval": 5, + "poll": false, + "params": { + "kind": "inet", + "sub_points": { + "fd": false, + "family": false, + "type": false, + "laddr": false, + "raddr": false, + "status": false, + "pid": false + } + } + }, + "network_interface_addresses": { + "point_name": "Network/Interface/Addresses", + "check_interval": 5, + "poll": false, + "params": { + "included_interfaces": [], + "sub_points": { + "family": false, + "address": false, + "netmask": false, + "broadcast": false, + "ptp": false + } + } + }, + "network_interface_statistics": { + "point_name": "Network/Interface/Addresses", + "check_interval": 5, + "poll": false, + "params": { + "included_interfaces": [], + "sub_points": { + "isup": false, + "duplex": false, + "speed": false, + "mtu": false + } + } + }, + "sensors_temperatures": { + "point_name": "Sensors/Temperatures", + "check_interval": 5, + "poll": false, + "params": { + "fahrenheit": false, + "included_sensors": [], + "sub_points": { + "label": true, + "current": true, + "high": true, + "critical": true + } + } + }, + "sensors_fans": { + "point_name": "Sensors/Fans", + "check_interval": 5, + "poll": false, + "params": { + "included_sensors": [], + "sub_points": { + "label": false, + "current": false + } + } + }, + "sensors_battery": { + "point_name": "Sensors/Battery", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "percent": false, + "secsleft": false, + "power_plugged": false + } + } + }, + "boot_time": { + "point_name": "BootTime", + "check_interval": 5, + "poll": false, + "params": {} + }, + "users": { + "point_name": "Users", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "name": false, + "terminal": false, + "host": false, + "started": false, + "pid": false + } + } + } + } + } + +Besides ``poll``, there are four other important options in sysmon's configuration. + +- ``default_publish_type`` only needs to be specified once in the configuration, this is the default publish type. +- ``base_topic`` also only needs to be specified once. This is the base topic. +- ``point_name`` changes the point name for the specific system monitor. In combination with publish_type and base_topic, our data for cpu_percent would be published to volttron with a topic of: **datalogger/Log/Platform/CPU/Percent** using the below JSON as an example. +- ``check_interval`` adjusts the time in seconds to poll for new system data. This can be modified for each system resource. + +The Sysmon agent serves as a wrapper for psutil. You can adjust resource specific options by adjusting false to true in the configuration file. For detailed insights into these options and their impact, you can read the `psutil documentation `_. + +You may also delete any unused fields if desired. For example, a configuration to monitor just cpu_percent could look like this. + +.. code-block:: json + + { + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": true, + "capture_interval": null + } + } + } + } + +Install and start the sysmon agent + +.. code-block:: bash + + vctl install volttron-sysmon --vip-identity agent.sysmon --start + +Add ``sysmon_agent_config.json`` to the configuration store + +.. code-block:: bash + + vctl config store agent.sysmon config sysmon_agent_config.json + +Observe Data +------------ + +To see data being published to the bus, install a `Listener Agent `_: + +.. code-block:: bash + + vctl install volttron-listener --start + +Periodic Publish +---------------- + +At the interval specified by the configuration option for each resource, the agent will automatically query the system for the resource utilization statistics and publish it to the message bus using the topic as previously described. The message content for each publish will contain only a single numeric value for that specific topic. Currently, “scrape_all” style publishes are not supported. + +The following is an example of the LoadAverage publish captured by the Listener agent in the VOLTTRON log: + +.. code-block:: none + + 2024-01-02 12:03:50,435 (volttron-listener-0.2.0rc0 2404) listener.agent(104) INFO: Peer: pubsub, Sender: volttron-sysmon-0.1.0_1:, Bus: , Topic: datalogger/Log/Platform/CPU/LoadAverage, Headers: {'Date': '2024-01-02T20:03:50.426814+00:00', 'min_compatible_version': '3.0', 'max_compatible_version': ''}, Message: + {'FifteenMinute': {'Readings': ['2024-01-02T20:03:50.426814+00:00', + 0.009765625], + 'Units': 'load_average', + 'data_type': 'float', + 'tz': 'UTC'}, + 'FiveMinute': {'Readings': ['2024-01-02T20:03:50.426814+00:00', 0.05517578125], + 'Units': 'load_average', + 'data_type': 'float', + 'tz': 'UTC'}, + 'OneMinute': {'Readings': ['2024-01-02T20:03:50.426814+00:00', 0.14404296875], + 'Units': 'load_average', + 'data_type': 'float', + 'tz': 'UTC'}} + +Disclaimer Notice +----------------- + +This material was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the United States Department of Energy, nor Battelle, nor any of their employees, nor any jurisdiction or organization that has cooperated in the development of these materials, makes any warranty, express or implied, or assumes any legal liability or responsibility for the accuracy, completeness, or usefulness or any information, apparatus, product, software, or process disclosed, or represents that its use would not infringe privately owned rights. + +Reference herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government or any agency thereof, or Battelle Memorial Institute. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or any agency thereof. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..007f2aa --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,65 @@ +[build-system] +requires = ["poetry-core>=1.2.2"] +build-backend = "poetry.core.masonry.api" + +[tool.poetry.scripts] +volttron-sysmon = "sysmon.agent:main" + +[tool.isort] +profile = "black" + +[tool.poetry] +include = ["src/sysmon", "sysmonagent.config"] + +name = "volttron-sysmon" +version = "0.1.0" +description = "" +authors = ["VOLTTRON Team "] +license = "Apache License 2.0" +readme = "README.md" +repository = "https://github.com/eclipse-volttron/volttron-sysmon" +homepage = "https://github.com/eclipse-volttron/volttron-sysmon" +keywords = [] +packages = [ { include = "sysmon", from = "src" } ] +classifiers = [ + "Programming Language :: Python :: 3 :: Only", + "Intended Audience :: Science/Research", + "Intended Audience :: Information Technology", + "Intended Audience :: Developers", + "Intended Audience :: Other Audience", + "License :: OSI Approved :: Apache Software License" +] + +[tool.poetry.dependencies] +python = ">=3.10,<4.0" +volttron = "^10.0.4rc1" + +[tool.poetry.group.dev.dependencies] +volttron-testing = "^0.4.0rc0" +pytest = "^6.2.5" +pytest-cov = "^3.0.0" +mock = "^4.0.3" +pre-commit = "^2.17.0" +yapf = "^0.32.0" +toml = "^0.10.2" +mypy = "^0.942" +coverage = "^6.3.2" +isort = "^5.10.1" + +[tool.poetry.dev-dependencies] +Sphinx = "^6.0.0" +sphinx-rtd-theme = "^1.2.0" + +[tool.yapf] +based_on_style = "pep8" +spaces_before_comment = 4 +column_limit = 120 +split_before_logical_operator = true + +[tool.yapfignore] +ignore_patterns = [ + ".venv/**", + ".pytest_cache/**", + "dist/**", + "docs/**" +] diff --git a/src/sysmon/agent.py b/src/sysmon/agent.py new file mode 100644 index 0000000..3b0d15d --- /dev/null +++ b/src/sysmon/agent.py @@ -0,0 +1,652 @@ +# -*- coding: utf-8 -*- {{{ +# ===----------------------------------------------------------------------=== +# +# Installable Component of Eclipse VOLTTRON +# +# ===----------------------------------------------------------------------=== +# +# Copyright 2024 Battelle Memorial Institute +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy +# of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# ===----------------------------------------------------------------------=== +# }}} + +import logging +import sys +from collections import namedtuple +from os import R_OK, access, path, walk + +import psutil +from gevent import sleep +from volttron import utils +from volttron.client.vip.agent import RPC, Agent +from volttron.utils.scheduling import periodic + +utils.setup_logging() +_log = logging.getLogger(__name__) +__version__ = '4.0' + +class SysMonAgent(Agent): + """Monitor utilization of system resources (CPU, memory, swap, disk, network) + + Statistics for each system resource can be queried via + RPC and they are published periodically to configured topics. + + :param config: Configuration dict + :type config: dict + """ + + IMPLEMENTED_METHODS = ('cpu_percent', 'cpu_times', 'cpu_times_percent', 'cpu_statistics', 'cpu_frequency', + 'cpu_count', 'load_average', 'memory', 'memory_percent', 'swap', 'disk_partitions', + 'disk_usage', 'disk_percent', 'disk_io', 'path_usage', 'path_usage_rate', 'network_io', + 'network_connections', 'network_interface_addresses', 'network_interface_statistics', + 'sensors_temperatures', 'sensors_fans', 'sensors_battery', 'boot_time', 'users') + + RECORD_ONLY_PUBLISH_METHODS = ('disk_partitions', 'network_connections', 'network_interface_address', + 'sensors_temperatures', 'users') + + UNITS = { + 'boot_time': 's', + 'cpu_count': 'count', + 'cpu_frequency': 'MHz', + 'cpu_percent': 'percent', + 'cpu_stats': 'count', + 'cpu_times': 's', + 'cpu_times_percent': 'percent', + 'disk_io': { + 'read_count': 'reads', + 'write_count': 'writes', + 'read_bytes': 'bytes', + 'write_bytes': 'bytes', + 'read_time': 'ms', + 'write_time': 'ms', + 'read_merged_count': 'reads', + 'write_merged_count': 'writes', + 'busy_time': 'ms', + 'read_throughput': 'bytes/s', + 'write_throughput': 'bytes/s' + }, + 'disk_partitions': None, + 'disk_percent': 'percent', + 'disk_usage': { + 'total': 'bytes', + 'used': 'bytes', + 'free': 'bytes', + 'percent': 'percent' + }, + 'load_average': 'load_average', + 'memory': { + 'total': 'bytes', + 'available': 'bytes', + 'percent': 'percent', + 'used': 'bytes', + 'free': 'bytes', + 'active': 'bytes', + 'inactive': 'bytes', + 'buffers': 'bytes', + 'cached': 'bytes', + 'shared': 'bytes', + 'slab': 'bytes' + }, + 'memory_percent': 'percent', + 'network_connections': None, + 'network_interface_address': None, + 'network_interface_statitics': { + 'isup': 'bool', + 'duplex': 'enum', + 'speed': 'Mbps', + 'mtu': 'bytes' + }, + 'network_io': { + 'bytes_sent': 'bytes', + 'bytes_recv': 'bytes', + 'packets_sent': 'packets', + 'packets_recv': 'packets', + 'errin': 'errors', + 'errout': 'errors', + 'dropin': 'packets', + 'dropout': 'packets', + "receive_throughput": 'bytes/s', + "send_throughput": 'bytes/s' + }, + 'path_usage': 'bytes', + 'path_usage_rate': 'bytes/s', + 'sensors_battery': { + 'percent': 'percent', + 'secsleft': 's', + 'power_plugged': 'bool' + }, + 'sensors_fans': 'rpm', + 'sensors_temperatures': 'degrees', + 'swap': { + 'total': 'bytes', + 'used': 'bytes', + 'free': 'bytes', + 'percent': 'bytes', + 'sin': 'bytes', + 'sout': 'bytes' + }, + 'users': None + } + + publish_data = namedtuple('publish_data', ['value', 'units', 'data_type', 'now']) + + def __init__(self, config_path, **kwargs): + super(SysMonAgent, self).__init__(**kwargs) + self.default_publish_type = None + self.base_topic = None + self._scheduled = [] + + # Tracking variables. + # Initial value for last_path_sizes is set in on_configure for configured paths. + self.last_path_sizes = {} # Used by path_usage_rate: {path: {usage, dt}} + self.last_disk_read_bytes = {} # Used by disk_io: {disk: {bytes, dt}} + self.last_disk_write_bytes = {} # Used by disk_io: {disk: {bytes, dt}} + # Set initial values for self.last_disk_read_bytes and self.last_disk_write_bytes. + self.disk_io(per_disk=False) + self.disk_io(per_disk=True) + self.last_network_received_bytes = {} # Used by network_io: {disk: {bytes, dt}} + self.last_network_sent_bytes = {} # Used by network_io: {disk: {bytes, dt}} + # Set initial values for self.last_network_received_bytes and self.last_network_sent_bytes + self.network_io(per_nic=False) + self.network_io(per_nic=True) + + default_config = utils.load_config(config_path) + self.vip.config.set_default('config', default_config) + self.vip.config.subscribe(self.on_configure, actions=['NEW', 'UPDATE'], pattern='config') + + def on_configure(self, config_name, action, contents): + _log.info(f'Received configuration store event of type: {action}. Loading configuration from config://{config_name}') + + # Stop any currently scheduled monitors. + for sched in self._scheduled: + sched.cancel() + self._scheduled = [] + + self.default_publish_type = contents.pop('default_publish_type', None) + if self.default_publish_type: + self.base_topic = contents.pop('base_topic', 'Log/Platform') + else: # TODO: Deprecated configuration block. Make if block unconditional in future release: + # BEGIN DEPRECATED CONFIGURATION BLOCK. + self.default_publish_type, self.base_topic = contents.pop('base_topic', + 'datalogger/log/platform').split('/', 1) + _log.warning('No "default_publish_type" configuration found, using deprecated configuration method:' + 'default_publish_type: "datalogger", base_topic: default_publish_type + "log/platform".' + 'See SysMonAgent/README.md for information on new configuration format.') + # END DEPRECATED CONFIGURATION BLOCK. + + monitors = contents.pop('monitor', {}) + + # TODO: Deprecated configuration block. Remove block between 'begin' and 'end' in future release: + # BEGIN DEPRECATED CONFIGURATION BLOCK. + for dep in [('cpu_interval', 'cpu_check_interval'), ('memory', 'memory_check_interval'), + ('disk_usage', 'disk_check_interval')]: + deprecated_interval = contents.pop(dep[1], None) + if monitors.get(dep[0]) and deprecated_interval: + _log.warning( + f"Ignoring deprecated configuration {dep[1]}, using provided monitor['{dep[0]}']['check_interval']" + "See SysMonAgent/README.md for information on new configuration format.") + + elif deprecated_interval: + monitors[dep[0]] = {'point_name': dep[0], 'check_interval': dep[1], 'poll': True} + _log.warning('Starting cpu_percent monitor using deprecated configuration "cpu_check_interval".' + ' Update configuration to use monitor["cpu_percent"]["check_interval"].' + 'See SysMonAgent/README.md for information on new configuration format.') + # END DEPRECATED CONFIGURATION BLOCK. + + # Start Monitors: + sleep(1) # Wait for a second to pass to avoid divide by zero errors from tracking variables. + for method in self.IMPLEMENTED_METHODS: + item = monitors.pop(method, None) + if method == 'path_usage_rate' and item.get('path_name', None): + # Set initial value(s) of self.last_path_sizes for any configured path names. + self.path_usage_rate(item.get('path_name')) + if item and item.pop('poll', None) is True: + item_publish_type = item.get('publish_type', None) + item_publish_type = 'record' if method in self.RECORD_ONLY_PUBLISH_METHODS else item_publish_type + item_publish_type = item_publish_type if item_publish_type else self.default_publish_type + self._periodic_pub(getattr(self, method), item_publish_type, item['check_interval'], item['point_name'], + item['params']) + + for key in contents: + _log.warning('Ignoring unrecognized configuration parameter %s', key) + for key in monitors: + _log.warning(f'Ignoring unimplemented monitor method: {key}') + + def _periodic_pub(self, func, publish_type, check_interval, point_name, params): + """Periodically call func and publish its return value""" + + def _unpack(topic, item, now, entries=None): + data_type = type(item) + entries = entries if entries else {} + if data_type in [int, float, str, bool, None]: + units = self.UNITS[func.__name__] + topic = path.normpath(topic) + if type(units) == dict: + units = units[topic.split('/')[-1]] + entries[topic] = self.publish_data(item, units, type(item).__name__, now) + elif data_type is dict: + for k, v in item.items(): + entries = _unpack(topic + '/' + str(k), v, now, entries) + else: + _log.warning(f'Unexpected return type from method: {func.__name__}') + return entries + + def _datalogger_publish(parameters): + data = func(**parameters) + now = utils.get_aware_utc_now() + tz = now.tzname() + now = utils.format_timestamp(now) + entries = _unpack(point_name, data, now) + point_base = path.dirname(path.commonprefix(list(entries.keys()))) + entries = {path.relpath(topic, point_base): value for topic, value in entries.items()} + message = {} + header = {'Date': now} + for k, v in entries.items(): + message[k] = {'Readings': [v.now, v.value], 'Units': v.units, 'tz': tz, 'data_type': v.data_type} + self.vip.pubsub.publish(peer='pubsub', + topic=publish_type + '/' + self.base_topic + '/' + point_base, + headers=header, + message=message) + + def _all_type_publish(parameters): + data = func(**parameters) + now = utils.format_timestamp(utils.get_aware_utc_now()) + entries = _unpack(point_name, data, now) + point_base = path.dirname(path.commonprefix(list(entries.keys()))) + entries = {path.relpath(topic, point_base): value for topic, value in entries.items()} + val, meta = {}, {} + for k, v in entries.items(): + val[k] = v + meta[k] = {'Units': v.units, 'data_type': v.data_type} + message = [val, meta] + header = {'Date': now} + topic = publish_type + '/' + self.base_topic + '/' + point_base + '/all' + self.vip.pubsub.publish(peer='pubsub', topic=topic, headers=header, message=message) + + def _record_publish(parameters): + data = func(**parameters) + now = utils.format_timestamp(utils.get_aware_utc_now()) + header = {'Date': now} + self.vip.pubsub.publish(peer='pubsub', + topic=publish_type + '/' + self.base_topic + '/' + point_name, + headers=header, + message=data) + + if publish_type == 'record': + pub_wrapper = _record_publish + elif publish_type == 'datalogger': + pub_wrapper = _datalogger_publish + else: + pub_wrapper = _all_type_publish + + sched = self.core.schedule(periodic(check_interval), pub_wrapper, params) + self._scheduled.append(sched) + + @RPC.export('cpu_percent') + def cpu_percent(self, per_cpu=False, capture_interval=None): + """Return CPU usage percentage""" + cpu_stats = psutil.cpu_percent(percpu=per_cpu, interval=capture_interval) + if per_cpu: + return dict(enumerate(cpu_stats)) + else: + return cpu_stats + + @RPC.export('cpu_times') + def cpu_times(self, per_cpu=False, sub_points=None): + """Return percentage of time the CPU has spent in a given mode.""" + times = psutil.cpu_times_percent(percpu=per_cpu) + times = self._process_statistics(times, sub_points=sub_points) + return times + + @RPC.export('cpu_times_percent') + def cpu_times_percent(self, per_cpu=False, sub_points=None, capture_interval=None): + """Return percentage of time the CPU has spent in a given mode during a certain interval.""" + percentages = psutil.cpu_times_percent(interval=capture_interval, percpu=per_cpu) + percentages = self._process_statistics(percentages, sub_points=sub_points) + return percentages + + @RPC.export('cpu_count') + def cpu_count(self, logical=True): + """Return the number of CPU cores if logical=True or the number of physical CPUs if logical=False""" + return psutil.cpu_count(logical) + + @RPC.export('cpu_stats') + def cpu_stats(self, sub_points=None): + """Return various CPU statistics.""" + stats = psutil.cpu_stats() + stats = self._process_statistics(stats, sub_points=sub_points) + return stats + + @RPC.export('cpu_frequency') + def cpu_frequency(self, per_cpu=False, sub_points=None): + """Return current frequency of the CPU cores.""" + freq = psutil.cpu_freq(percpu=per_cpu) + freq = self._process_statistics(freq, sub_points=sub_points) + return freq + + @RPC.export('memory_percent') + def memory_percent(self): + """Return memory usage percentage""" + _log.warning('Method "memory_percent" is deprecated. Use "memory" instead.') + return self.memory()['percent'] + + @RPC.export('memory') + def memory(self, sub_points=None): + """Return memory usage statistics""" + virtual_memory = psutil.virtual_memory() + return self._process_statistics(virtual_memory, sub_points) + + @RPC.export('swap') + def swap(self, sub_points=None): + """Return swap usage statistics""" + swap_memory = psutil.swap_memory() + return self._process_statistics(swap_memory, sub_points) + + # TODO: Should includes allow filtering by mount_point, device, etc, rather than enumeration? + @RPC.export('disk_partitions') + def disk_partitions(self, all_partitions=False, included_partitions=None, sub_points=None): + """Returns information about disk partitions""" + partitions = psutil.disk_partitions(all_partitions) + partitions = self._process_statistics(partitions, sub_points=sub_points, includes=included_partitions) + return partitions + + @RPC.export('disk_percent') + def disk_percent(self, disk_path='/'): + """Return usage of disk mounted at configured path""" + _log.warning('Method "disk_percent" is deprecated. Use "disk_usage" instead.') + return self.disk_usage(disk_path)[disk_path]['percent'] + + @RPC.export('disk_usage') + def disk_usage(self, disk_path='/', sub_points=None): + """Return disk usage statistics.""" + usage = {} + if type(disk_path) is not list: + disk_path = [disk_path] + for d_path in disk_path: + usage[d_path] = psutil.disk_usage(d_path) + return self._process_statistics(usage, sub_points) + + @RPC.export('load_average') + def load_average(self, sub_points=None): + """Return load averages.""" + las = namedtuple('las', ('OneMinute', 'FiveMinute', 'FifteenMinute')) + averages = las(*psutil.getloadavg()) + # noinspection PyTypeChecker + return self._process_statistics(averages, sub_points) + + @RPC.export('path_usage') + def path_usage(self, path_name): + """Return storage used within a filesystem path.""" + path_size = {} + if type(path_name) is not list: + path_name = [path_name] + for path_n in path_name: + try: + if path.isfile(path_n): + path_size[path_n] = path.getsize(path_n) + elif path.isdir(path_n): + if not access(path_n, R_OK): + raise PermissionError('Inaccessible path: path_n. Check read permissions and that path exists.') + path_size[path_n] = sum( + path.getsize(path.join(dir_path, filename)) for dir_path, dir_names, filenames in walk(path_n) + for filename in filenames) + else: + raise Exception(f'Path is neither a file nor a directory: {path_n}') + except Exception as e: + _log.error(f'Exception in path_usage: {e}') + path_size[path_n] = -1 # Error code -1 indicates path exception. + return path_size + + @RPC.export('path_usage_rate') + def path_usage_rate(self, path_name, interval=None): + """Return rate of change in storage used within a filesystem path in bytes per second.""" + current_path_sizes = {} + rates = {} + if type(path_name) is not list: + path_name = [path_name] + for path_n in path_name: + current_usage = self.path_usage(path_n)[path_n] + now = utils.get_aware_utc_now() + if current_usage > 0: # Don't use or store error codes as a usage value. + current_path_sizes[path_n] = {'value': current_usage, 'dt': now} + if path_n in self.last_path_sizes: + rates[path_n] = (current_usage - self.last_path_sizes[path_n]['value']) \ + / (now - self.last_path_sizes[path_n]['dt']).seconds + else: + rates[ + path_n] = -2 # Error code -2 indicates no prior tracking data. Call again for valid response. + else: + rates[path_n] = current_usage # Return error code from self.path_usage. + self.last_path_sizes.update(current_path_sizes) + return rates + + @RPC.export('disk_io') + def disk_io(self, per_disk=False, no_wrap=True, included_disks=None, sub_points=None): + """Return disk input/output statistics.""" + if included_disks and not per_disk: + per_disk = True + io_stats = psutil.disk_io_counters(perdisk=per_disk, nowrap=no_wrap) + retval = self._process_statistics(io_stats, sub_points, includes=included_disks) + self._get_throughput(io_stats, retval, per_disk, sub_points, 'read_throughput', 'write_throughput', + 'read_bytes', 'write_bytes', self.last_disk_read_bytes, self.last_disk_write_bytes) + retval = self._format_return(retval) + return retval + + @RPC.export('network_io') + def network_io(self, per_nic=False, no_wrap=True, included_nics=None, sub_points=None): + """Return network input/output statistics.""" + if included_nics and not per_nic: + per_nic = True + io_stats = psutil.net_io_counters(pernic=per_nic, nowrap=no_wrap) + retval = self._process_statistics(io_stats, sub_points, includes=included_nics) + self._get_throughput(io_stats, retval, per_nic, sub_points, 'receive_throughput', 'send_throughput', + 'bytes_recv', 'bytes_sent', self.last_network_received_bytes, self.last_network_sent_bytes) + retval = self._format_return(retval) + return retval + + @RPC.export('network_connections') + def network_connections(self, kind='inet', sub_points=None): + """Return system-wide socket connections""" + connections = psutil.net_connections(kind) + connections = self._process_statistics(connections, sub_points=sub_points, format_return=False) + for k, v in connections.items(): + if 'family' in v: + v['family'] = v['family'].name + if 'type' in v: + v['type'] = v['type'].name + if 'laddr' in v: + v['laddr'] = v['laddr'].ip + ':' + str(v['laddr'].port) \ + if type(v['laddr']) is psutil._common.addr else '' + if 'raddr' in v: + v['raddr'] = v['raddr'].ip + ':' + str(v['raddr'].port) \ + if type(v['raddr']) is psutil._common.addr else '' + connections = self._format_return(connections) + return connections + + @RPC.export('network_interface_addresses') + def network_interface_addresses(self, included_interfaces=None, sub_points=None): + """Return addresses associated with network interfaces.""" + addresses = psutil.net_if_addrs() + addresses = self._process_statistics(addresses, sub_points, includes=included_interfaces, format_return=False) + for k, v in addresses.items(): + for item in v: + if 'family' in item: + item['family'] = item['family'].name + addresses = self._format_return(addresses) + return addresses + + @RPC.export('network_interface_statistics') + def network_interface_statistics(self, included_interfaces=None, sub_points=None): + """Return information about each network interface.""" + stats = psutil.net_if_stats() + stats = self._process_statistics(stats, sub_points, includes=included_interfaces, format_return=False) + for k, v in stats.items(): + if 'duplex' in v: + v['duplex'] = v['duplex'].name + stats = self._format_return(stats) + return stats + + @RPC.export('sensors_temperatures') + def sensors_temperatures(self, fahrenheit=False): + """Return hardware temperatures.""" + temps = psutil.sensors_temperatures(fahrenheit=fahrenheit) + + if not temps: + return "No hardware to read" + + formatted_temps = {} + for sensor_type, readings in temps.items(): + formatted_readings = [] + for reading in readings: + # Use the sensor label if available, otherwise, use the sensor type as the label + label = reading.label if reading.label else sensor_type + + unit = 'F' if fahrenheit else 'C' + current_temperature = f"{reading.current}°{unit}" + + formatted_readings.append({ + 'label': label, + 'current': current_temperature, + }) + formatted_temps[sensor_type] = formatted_readings + + return formatted_temps + + + @RPC.export('sensors_fans') + def sensors_fans(self, sub_points=None, included_sensors=None): + """Return fan speed in RPM.""" + fans = psutil.sensors_fans() + fans = self._process_statistics(fans, sub_points, includes=included_sensors) + return fans + + @RPC.export('sensors_battery') + def sensors_battery(self, sub_points=None): + """Return battery status information.""" + battery = psutil.sensors_battery() + battery = self._process_statistics(battery, sub_points) + return battery + + @RPC.export('boot_time') + def boot_time(self): + """Return time of last system boot as seconds since the epoch.""" + return psutil.boot_time() + + @RPC.export('users') + def users(self, sub_points=None): + """Return user session data for users currently connected to the system.""" + users = psutil.users() + users = self._process_statistics(users, sub_points) + return users + + def _process_statistics(self, stats, sub_points, includes=None, format_return=True): + if type(stats).__bases__[0] == tuple: # Case: stats is a named tuple. + retval = {0: stats} + elif type(stats) == list: # Case: stats is a list of values or named tuples. + retval = dict(enumerate(stats)) + elif type(stats) == dict: + retval = stats.copy() + elif stats is None: + retval = {} + else: # Case: stats is a single value + retval = {'total': stats} + if includes: + retval = self._filter_includes(includes, retval) + for k, v in retval.items(): + if type(v) is list: # Handle nested lists of named tuples + for index, item in enumerate(v): + retval[k][index] = self._filter_sub_points(item, sub_points) + else: + retval[k] = self._filter_sub_points(v, sub_points) + if format_return: + retval = self._format_return(retval) + return retval + + @staticmethod + def _filter_includes(includes, stats): + includes = includes if type(includes) is list else [includes] + return {key: value for (key, value) in stats.items() if key in includes} + + @staticmethod + def _format_return(stats): + keys = list(stats.keys()) + # TODO: This leads to odd behavior for disk_partitions, where if only 0 is requested it has a different output + # format than if only 1 is requested. + if len(keys + ) == 1 and keys[0] == 0: # TODO: Do we care if it is an enumerated list or do this for single dicts? + stats = stats[0] # TODO: Does this need another [0] at the end? + return stats + + @staticmethod + def _filter_sub_points(item, sub_points): + if type(sub_points) is list: + return {key: value for (key, value) in item._asdict().items() if key in sub_points} + elif type(sub_points) is str: + return {key: value for (key, value) in item._asdict().items() if key == sub_points} + elif type(sub_points) is dict: + return {key: value for (key, value) in item._asdict().items() if sub_points.get(key, False) is True} + else: + return {key: value for (key, value) in item._asdict().items()} + + # TODO: The tracking variables for this should us a look back buffer, not just last value as currently used. + @staticmethod + def _get_throughput(io_stats, retval, per_device, sub_points, in_ret_label, out_ret_label, in_label, out_label, + last_in, last_out): + now = utils.get_aware_utc_now() + current_in_bytes = {} + current_out_bytes = {} + if per_device is False: + current_in_bytes = {'not_per_device': {'value': getattr(io_stats, in_label), 'dt': now}} + current_out_bytes = {'not_per_device': {'value': getattr(io_stats, out_label), 'dt': now}} + else: + for device in io_stats: + current_in_bytes[device] = {'value': getattr(io_stats[device], in_label), 'dt': now} + current_out_bytes[device] = {'value': getattr(io_stats[device], out_label), 'dt': now} + + for device, in_bytes in current_in_bytes.items(): + if device in last_in: + throughput = (in_bytes['value'] - last_in[device]['value']) / (now - last_in[device]['dt']).seconds + else: + throughput = -2 + if not sub_points or in_ret_label in sub_points: + if not per_device: + retval[in_ret_label] = throughput + elif device in retval: + retval[device][in_ret_label] = throughput + last_in.update(current_in_bytes) + for device, out_bytes in current_out_bytes.items(): + if device in last_out: + throughput = (out_bytes['value'] - last_out[device]['value']) / (now - last_out[device]['dt']).seconds + else: + throughput = -2 + if not sub_points or out_ret_label in sub_points: + if not per_device: + retval[out_ret_label] = throughput + elif device in retval: + retval[device][out_ret_label] = throughput + last_out.update(current_out_bytes) + + +def main(): + """Main method called by the platform.""" + utils.vip_main(SysMonAgent, identity='platform.sysmon', version=__version__) + + +if __name__ == '__main__': + # Entry point for script + try: + sys.exit(main()) + except KeyboardInterrupt: + pass diff --git a/sysmon_agent_config.json b/sysmon_agent_config.json new file mode 100644 index 0000000..47c39d3 --- /dev/null +++ b/sysmon_agent_config.json @@ -0,0 +1,308 @@ +{ + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": true, + "capture_interval": null + } + }, + "cpu_times": { + "point_name": "CPU/Times", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "sub_points": { + "user": false, + "nice": false, + "system": false, + "idle": false, + "iowait": false, + "irq": false, + "softirq": false, + "steal": false, + "guest": false, + "guest_nice": false + } + } + }, + "cpu_times_percent": { + "point_name": "CPU/TimePercentages", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "capture_interval": null, + "sub_points": { + "user": false, + "nice": false, + "system": false, + "idle": false, + "iowait": false, + "irq": false, + "softirq": false, + "steal": false, + "guest": false, + "guest_nice": false + } + } + }, + "cpu_statistics": { + "point_name": "CPU/Statistics", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "ctx_switches": false, + "interrupts": false, + "soft_interrupts": false + } + } + }, + "cpu_frequency": { + "point_name": "CPU/Frequencies", + "check_interval": 5, + "poll": false, + "params": { + "per_cpu": false, + "sub_points": { + "current": false, + "min": false, + "max": false + } + } + }, + "memory": { + "point_name": "Memory", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "total": false, + "available": true, + "percent": true, + "used": true, + "free": false, + "active": false, + "inactive": false, + "buffers": false, + "cached": false, + "shared": false, + "slab": false + } + } + }, + "disk_usage": { + "point_name": "Disk/Usage", + "check_interval": 3600, + "poll": true, + "params": { + "disk_path": ["/"], + "sub_points": { + "total": false, + "used": true, + "free": true, + "percent": true + } + } + }, + "load_average": { + "point_name": "CPU/LoadAverage", + "check_interval": 5, + "poll": true, + "params": { + "sub_points": { + "OneMinute": true, + "FiveMinute": true, + "FifteenMinute": true + } + } + }, + "swap": { + "point_name": "Swap", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "total": false, + "used": true, + "free": true, + "percent": true, + "sin": false, + "sout": false + } + } + }, + "path_usage": { + "point_name": "Disk/Path/Usage", + "check_interval": 3600, + "poll": false, + "params": { + "path_name": "/var/log/journal" + } + }, + "path_usage_rate": { + "point_name": "Disk/Path/Rate", + "check_interval": 3600, + "poll": false, + "params": { + "path_name": "/var/log/journal" + } + }, + "disk_io": { + "point_name": "Disk/IO", + "check_interval": 5, + "poll": false, + "params": { + "per_disk": false, + "included_disks": [], + "no_wrap": true, + "sub_points": { + "read_count": false, + "write_count": false, + "read_bytes": true, + "write_bytes": true, + "read_time": true, + "write_time": true, + "read_merged_count": false, + "write_merged_count": false, + "busy_time": true, + "read_throughput": true, + "write_throughput": true + } + } + }, + "network_io": { + "point_name": "Network/IO", + "check_interval": 5, + "poll": false, + "params": { + "per_nic": true, + "included_nics": [], + "no_wrap": true, + "sub_points": { + "bytes_sent": true, + "bytes_recv": true, + "packets_sent": true, + "packets_recv": true, + "errin": true, + "errout": true, + "dropin": true, + "dropout": true, + "receive_throughput": true, + "send_throughput": true + } + } + }, + "network_connections": { + "point_name": "Network/Connections", + "check_interval": 5, + "poll": false, + "params": { + "kind": "inet", + "sub_points": { + "fd": false, + "family": false, + "type": false, + "laddr": false, + "raddr": false, + "status": false, + "pid": false + } + } + }, + "network_interface_addresses": { + "point_name": "Network/Interface/Addresses", + "check_interval": 5, + "poll": false, + "params": { + "included_interfaces": [], + "sub_points": { + "family": false, + "address": false, + "netmask": false, + "broadcast": false, + "ptp": false + } + } + }, + "network_interface_statistics": { + "point_name": "Network/Interface/Addresses", + "check_interval": 5, + "poll": false, + "params": { + "included_interfaces": [], + "sub_points": { + "isup": false, + "duplex": false, + "speed": false, + "mtu": false + } + } + }, + "sensors_temperatures": { + "point_name": "Sensors/Temperatures", + "check_interval": 5, + "poll": false, + "params": { + "fahrenheit": false, + "included_sensors": [], + "sub_points": { + "label": true, + "current": true, + "high": true, + "critical": true + } + } + }, + "sensors_fans": { + "point_name": "Sensors/Fans", + "check_interval": 5, + "poll": false, + "params": { + "included_sensors": [], + "sub_points": { + "label": false, + "current": false + } + } + }, + "sensors_battery": { + "point_name": "Sensors/Battery", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "percent": false, + "secsleft": false, + "power_plugged": false + } + } + }, + "boot_time": { + "point_name": "BootTime", + "check_interval": 5, + "poll": false, + "params": {} + }, + "users": { + "point_name": "Users", + "check_interval": 5, + "poll": false, + "params": { + "sub_points": { + "name": false, + "terminal": false, + "host": false, + "started": false, + "pid": false + } + } + } + } +} diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..f867f81 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- {{{ +# ===----------------------------------------------------------------------=== +# +# Installable Component of Eclipse VOLTTRON +# +# ===----------------------------------------------------------------------=== +# +# Copyright 2022 Battelle Memorial Institute +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy +# of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# ===----------------------------------------------------------------------=== +# }}} + +"""Configuration for the pytest test suite.""" + +import pytest + +import sys +if "src" not in sys.path: + sys.path.insert(0, "src") + +from volttrontesting.fixtures.volttron_platform_fixtures import volttron_instance + + +@pytest.fixture() +def publish_agent(volttron_instance): + assert volttron_instance.is_running() + yield volttron_instance.build_agent(identity="publish_agent") \ No newline at end of file diff --git a/tests/test_agent_integ.py b/tests/test_agent_integ.py new file mode 100644 index 0000000..6c9023d --- /dev/null +++ b/tests/test_agent_integ.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- {{{ +# ===----------------------------------------------------------------------=== +# +# Installable Component of Eclipse VOLTTRON +# +# ===----------------------------------------------------------------------=== +# +# Copyright 2024 Battelle Memorial Institute +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy +# of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# ===----------------------------------------------------------------------=== +# }}} + +import gevent +from pathlib import Path + +from volttron.client.messaging.health import STATUS_GOOD +from volttron.client.vip.agent import Agent +from volttrontesting.platformwrapper import PlatformWrapper + +def test_sysmon_agent_successful_install_on_volttron_platform( + publish_agent: Agent, volttron_instance: PlatformWrapper): + # Agent install path based upon root of this repository + agent_dir = Path(__file__).parent.parent.resolve().as_posix() + sysmon_config = { + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": True, + "params": { + "per_cpu": True, + "capture_interval": None + } + } + } + } + pdriver_id = "agent.sysmon" + + pdriver_uuid = volttron_instance.install_agent(agent_dir=agent_dir, + config_file=sysmon_config, + start=False, + vip_identity=pdriver_id) + assert pdriver_uuid is not None + gevent.sleep(1) + started = volttron_instance.start_agent(pdriver_uuid) + assert started + assert volttron_instance.is_agent_running(pdriver_uuid) + + assert publish_agent.vip.rpc.call( + pdriver_id, "health.get_status").get(timeout=10).get('status') == STATUS_GOOD diff --git a/tests/test_agent_unit.py b/tests/test_agent_unit.py new file mode 100644 index 0000000..fc9232b --- /dev/null +++ b/tests/test_agent_unit.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- {{{ +# ===----------------------------------------------------------------------=== +# +# Installable Component of Eclipse VOLTTRON +# +# ===----------------------------------------------------------------------=== +# +# Copyright 2022 Battelle Memorial Institute +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy +# of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +# ===----------------------------------------------------------------------=== +# }}} + +import pytest +import gevent +import os +from pathlib import Path + +from volttron.client.known_identities import PLATFORM_DRIVER +from volttrontesting.platformwrapper import PlatformWrapper +from volttrontesting.fixtures.volttron_platform_fixtures import volttron_instance + +def test_get_point_set_point(publish_agent): + result = publish_agent.vip.rpc.call('agent.sysmon', 'cpu_times_percent', per_cpu=False, sub_points=None, capture_interval=5).get(timeout=10) + assert type(result) == dict, "Result should be a dictionary" + assert len(result) > 0, "Dictionary should not be empty" + +@pytest.fixture(scope="module") +def publish_agent(volttron_instance: PlatformWrapper): + assert volttron_instance.is_running() + vi = volttron_instance + assert vi is not None + assert vi.is_running() + + # install platform driver + config = { + "default_publish_type": "datalogger", + "base_topic": "Log/Platform", + "monitor": { + "cpu_percent": { + "point_name": "CPU/Percent", + "check_interval": 5, + "poll": True, + "params": { + "per_cpu": True, + "capture_interval": None + } + } + } + } + puid = vi.install_agent(agent_dir=str(Path(__file__).parent.parent.resolve()), + config_file=config, + start=False, + vip_identity="agent.sysmon") + assert puid is not None + gevent.sleep(1) + assert vi.start_agent(puid) + assert vi.is_agent_running(puid) + + # create the publish agent + publish_agent = volttron_instance.build_agent() + assert publish_agent.core.identity + gevent.sleep(1) + + capabilities = {"edit_config_store": {"identity": PLATFORM_DRIVER}} + volttron_instance.add_capabilities(publish_agent.core.publickey, capabilities) + + gevent.sleep(10) + + yield publish_agent + + volttron_instance.stop_agent(puid) + publish_agent.core.stop() \ No newline at end of file