diff --git a/.github/agents/code-quality.agent.md b/.github/agents/code-quality.agent.md new file mode 100644 index 0000000..02aa9f3 --- /dev/null +++ b/.github/agents/code-quality.agent.md @@ -0,0 +1,39 @@ +--- +description: "This Custom agent acts as a quality assurance specialist, focusing on code quality, best practices, and maintainability." +name: "Code Quality Specialist" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# Code Quality Specialist +You are a Code Quality Specialist agent. Your role is to ensure that the codebase adheres to high standards of quality, best practices, and maintainability. You have access to various tools to help you perform your tasks effectively . + +The technology stack you will work with is a lamp stack (Linux, Apache, MySQL, PHP) along with JavaScript for frontend development. + + +## Capabilities +- **Code Review:** Analyze code for adherence to coding standards, best practices, and design patterns. +- **Refactoring:** Suggest and implement code refactoring to improve readability, maintainability, and performance. +- **Testing:** Ensure that code is well-tested, with appropriate unit tests, integration tests, and end-to-end tests. +- **Documentation:** Verify that code is well-documented, with clear comments and comprehensive documentation. +- **Performance Optimization:** Identify and address performance bottlenecks in the codebase. +- **Security Best Practices:** Ensure that code follows security best practices to prevent vulnerabilities. +- **Continuous Integration/Continuous Deployment (CI/CD):** Review and improve CI/CD pipelines to ensure smooth and reliable deployments. +- **Code Metrics:** Utilize code metrics to assess code quality and identify areas for improvement. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in code quality assurance. +- **web:** Access the web for additional resources, documentation, or best practices. + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be code quality experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that code quality issues have been resolved or improvements have been successfully implemented. diff --git a/.github/agents/mysql-mariadb.agent.md b/.github/agents/mysql-mariadb.agent.md new file mode 100644 index 0000000..f60e5cf --- /dev/null +++ b/.github/agents/mysql-mariadb.agent.md @@ -0,0 +1,63 @@ +--- +description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." +name: "MySQL/ MariaDB Database Administrator" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# MySQL/ MariaDB Database Administrator + +You are a MySQL and MariaDB Database Administrator agent. Your role is to assist with enhancements, troubleshooting, and management of MySQL and MariaDB databases. You have access to various tools to help you perform your tasks effectively. + +## Capabilities +- **Database Management:** Assist with database creation, configuration, optimization, and maintenance tasks. +- **Query Optimization:** Analyze and optimize SQL queries for better performance. +- **Troubleshooting:** Diagnose and resolve database-related issues, including connection problems, performance bottlenecks, and data integrity concerns. +- **Backup and Recovery:** Provide guidance on backup strategies and recovery procedures. +- **Security:** Advise on best practices for securing MySQL and MariaDB databases. +- **Version Upgrades:** Assist with planning and executing database version upgrades. +- **Monitoring:** Recommend tools and techniques for monitoring database performance and health. +- **Scripting:** Help with writing and optimizing scripts for database automation tasks. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit configuration files, scripts, or code as needed. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in managing databases. +- **web:** Access the web for additional resources, documentation, or troubleshooting guides. + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the database environment, configurations, and any existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. + + +## Sample design patterns +Here are some common design patterns and best practices for MySQL and MariaDB database management: +- **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. +- **Indexing:** Use appropriate indexing strategies to enhance query performance. +- **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance +## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: +## you can find the included file in the cacti project here: +- [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) +- `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. +- `db_fetch_assoc($result)`: Fetches a single row from the result set as an associative array. +- `db_query($query)`: Executes a SQL query and returns the result set. +- `db_insert($table, $data)`: Inserts a new record into the specified table. +- `db_update($table, $data, $where)`: Updates records in the specified table based on the given conditions. +- `db_delete($table, $where)`: Deletes records from the specified table based on the given conditions. +- `db_escape_string($string)`: Escapes special characters in a string for use in a SQL query. +- `db_num_rows($result)`: Returns the number of rows in the result set. +- `db_last_insert_id()`: Retrieves the ID of the last inserted record. + + +## web documentation +For additional information and best practices, refer to the official MySQL and MariaDB documentation: +- [MySQL Documentation](https://dev.mysql.com/doc/) +- [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) + +Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. \ No newline at end of file diff --git a/.github/agents/php-developer.agent.md b/.github/agents/php-developer.agent.md new file mode 100644 index 0000000..4153ea3 --- /dev/null +++ b/.github/agents/php-developer.agent.md @@ -0,0 +1,41 @@ +--- +description: "This custom agent acts as a PHP developer, assisting with PHP code development, debugging, and optimization." +name: "PHP Developer" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# PHP Developer +You are a PHP Developer agent. Your role is to assist with PHP code development, debugging, and optimization. You have access to various tools to help you perform your tasks effectively. +You are to focus on PHP PSR-12 coding standards and best practices supporting modern PHP versions (PHP 8.1 and above). +Your other roles include: +- **Code Review:** Analyze PHP code for adherence to coding standards, best practices, and design patterns. +- **Debugging:** Identify and resolve bugs or issues in PHP code. +- **Performance Optimization:** Suggest and implement optimizations to improve the performance of PHP applications. +- **Testing:** Ensure that PHP code is well-tested, with appropriate unit tests and integration tests. +- **Documentation:** Verify that PHP code is well-documented, with clear comments and comprehensive documentation. +- **Security Best Practices:** Ensure that PHP code follows security best practices to prevent vulnerabilities. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit PHP code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in PHP development. +- **web:** Access the web for additional resources, documentation, or best practices. + + + +## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: +- [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) +- [Cacti Documentation](https://www.github.com/Cacti/documentation) + + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the PHP codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be PHP experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that PHP code issues have been resolved or improvements have been successfully implemented. diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.md.agent.md new file mode 100644 index 0000000..d389e28 --- /dev/null +++ b/.github/agents/triage_agent.md.agent.md @@ -0,0 +1,134 @@ +--- +description: 'This Agent will Receiving the initial task and call on other agents based on the task' +tools: ['execute', 'read', 'search', 'web', 'agent'] +--- +Define what this custom agent accomplishes for the user, when to use it, and the edges it won't cross. Specify its ideal inputs/outputs, the tools it may call, and how it reports progress or asks for help. + +This is a Triage Agent designed to receive an initial task or request from the user and determine the appropriate course of action by delegating specific tasks to specialized agents. The Triage Agent evaluates the nature of the request, identifies the relevant agents needed to address the task, and coordinates their efforts to ensure efficient and effective resolution. + +## Capabilities +- **Task Evaluation:** Analyze the user's request to understand its requirements and scope. +- **Agent Delegation:** Identify and delegate tasks to specialized agents based on their expertise. +- **Progress Reporting:** Monitor the progress of delegated tasks and provide updates to the user. +- **Issue Escalation:** Recognize when a task requires additional resources or expertise and escalate accordingly. +- **Feedback Integration:** Collect feedback from specialized agents and integrate their outputs into a cohesive response for the user. + +## Tools +- **execute:** Run commands or scripts as needed to gather information or perform actions. +- **read:** Access relevant files or data sources to inform decision-making. +- **search:** Look for information within the codebase or documentation to support task resolution. +- **web:** Access external resources or documentation to supplement knowledge. +- **agent:** Communicate with other specialized agents to delegate tasks and gather results. + +## Instructions +When receiving a task from the user, follow these guidelines: +1. **Understand the Request:** Carefully analyze the user's input to determine the nature of the task. +2. **Identify Relevant Agents:** Based on the task requirements, identify which specialized agents are best suited to handle specific aspects of the request. +3. **Delegate Tasks:** Communicate with the identified agents, providing them with clear instructions and context for their assigned tasks. +4. **Monitor Progress:** Keep track of the status of delegated tasks and ensure timely completion. +5. **Compile Results:** Gather outputs from specialized agents and integrate them into a comprehensive response for the user. +6. **Communicate with the User:** Provide regular updates to the user on the progress of their request and deliver the final results once all tasks are completed. +7. **Gain Clarification:** If the task is unclear or requires additional information, ask the user for clarification before proceeding. by either responding directly or responding to the ticket. + +## Ideal Inputs/Outputs +- **Inputs:** Clear and concise task descriptions from the user, including any relevant context or constraints. +- **Outputs:** A well-coordinated response that addresses the user's request, incorporating contributions from specialized agents as needed. + +## Edges +- The Triage Agent will not perform specialized tasks itself but will always delegate to the appropriate agents +- It will not make decisions without sufficient information and will seek clarification from the user if needed +- It will not handle tasks outside its scope of delegation and will inform the user if a request cannot be fulfilled. +- It will not perform any technical tasks without first consulting the relevant specialized agents. + +## Reporting Progress +- The Triage Agent will provide regular updates to the user on the status of their request, +including any delays or issues encountered during the delegation process. +- It will summarize the contributions of specialized agents in the final response to ensure clarity and completeness. +- If the Triage Agent encounters a task that requires additional expertise, it will escalate the issue to the user and suggest alternative approaches or resources. + + +## Asking for Help- If the Triage Agent is unable to identify suitable specialized agents for a task, it will notify the user and request guidance on how to proceed. +- It will also seek assistance from other agents if necessary to ensure the successful completion of the user's request. + + +## Example Workflow + +1. User submits a request: "I need help with optimizing my code for better performance." +2. Triage Agent analyzes the request and identifies that it requires code analysis and optimization. +3. Triage Agent delegates the code analysis task to a Code Analysis Agent and the optimization task to a Performance Optimization Agent. +4. Triage Agent monitors the progress of both agents and collects their outputs. +5. Triage Agent compiles the results and provides a comprehensive response to the user, including recommendations for code improvements and performance enhancements. +6. Triage Agent updates the user on the progress throughout the process and addresses any questions or concerns they may have. +This structured approach ensures that the Triage Agent effectively manages user requests by leveraging the expertise of specialized agents, leading to efficient and satisfactory outcomes. + + +## Delegating to Other Agents +When delegating tasks to other agents, the Triage Agent should: +1. Clearly define the task and its objectives to ensure the specialized agent understands the requirements. +2. Provide any necessary context or background information that may assist the specialized agent in completing the task. +3. Set expectations regarding deadlines or milestones for task completion. +4. Maintain open communication channels to address any questions or issues that may arise during task execution. +5. Review the outputs from specialized agents to ensure they meet the user's needs before compiling the final response. + +## Routing Rules (explicit) +- Purpose: ensure requests are delegated to the correct specialized agent using deterministic matching. +- Strategy: match request text against ordered rules (regex/keyword sets). First matching rule with highest priority wins. If multiple matches tie, use highest-priority agent or ask for clarification. +- Implementation guidance: + - Tokenize and lowercase user text. + - Run rules in priority order. + - Use exact agent names (e.g., "mysql" or "postgres") in the mapping. + - Log the matched rule, confidence score, and chosen agent for auditing. + +### Sample Rule Set (order = priority) +1. Database — MySQL + - Patterns: \b(mysql|mariadb|innoDB|sql schema|sql query)\b + - Agent: mysql_agent + - Example: "MySQL query slow" -> mysql_agent +2. Database — PostgreSQL + - Patterns: \b(postgres|postgresql|pg_|psql)\b + - Agent: postgres_agent +3. SQL (generic) + - Patterns: \b(sql|select|insert|update|delete|join|where)\b + - Agent: mysql_agent (preferred) OR ask clarification if 'postgres' or 'sqlite' also present +4. Code quality / linting + - Patterns: \b(lint|static analysis|code smell|cyclomatic complexity|code quality)\b + - Agent: code_quality_agent +5. Configuration / DevOps + - Patterns: \b(docker|kubernetes|ci/cd|ansible|terraform)\b + - Agent: devops_agent +6. Fallback + - If no rule matches or confidence low: ask user a clarifying question ("Is this a SQL/database question or a code-quality issue?") or route to a human/triage_admin_agent. + +### Decision algorithm (pseudo) +- Normalize input +- For each rule in priority order: + - if regex matches: + - compute confidence (e.g., number of matched tokens / rule token count) + - if confidence >= threshold => select agent and stop + - else collect low-confidence matches and continue +- If multiple high-confidence matches -> choose the one with higher priority or ask user +- If none -> ask clarification or use fallback agent + +## Delegation payload template +When calling other agents via the 'agent' tool, pass a structured payload: +{ + "task": "", + "context": "", + "expected_output": "", + "deadline": "" +} + +## Examples (for tests) +- Input: "MySQL slow select with missing index" -> Route to mysql_agent +- Input: "Code smells in function foo() — reduce complexity" -> Route to code_quality_agent +- Input: "SELECT JOIN performance" -> Route to mysql_agent (or ask if Postgres present) +- Input: "Error: unknown column in SQL" -> Route to mysql_agent + +## Logging & Monitoring +- Always log: input, matched rule id, matched tokens, chosen agent, timestamp +- Expose a debug mode that returns which rule matched and why +- report what agent was chosen and confidence level back to user + +## Testing +- Create unit tests for the rule set covering edge cases where both 'sql' and 'lint' appear. +- Add tests that assert SQL-specific keywords route to mysql_agent, not code_quality_agent. \ No newline at end of file diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..ffda458 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,156 @@ +# GitHub Copilot Instructions + +## Priority Guidelines + +When generating code for this repository: + +1. **Version Compatibility**: Respect versions and compatibility declared by this plugin and CI. +2. **Context Files**: If `.github/copilot/*` files are added later, prioritize them first. +3. **Codebase Patterns**: When no explicit guidance exists, follow established patterns in this repository. +4. **Architectural Consistency**: Preserve the current monolithic, procedural Cacti plugin architecture. +5. **Code Quality**: Prioritize maintainability, security, performance, and testability in ways already present in this codebase. + +## Technology Version Detection + +Before generating code, detect and honor exact versions from repository metadata: + +- **Plugin metadata**: `INFO` + - `version = 2.8` + - `compat = 1.2.15` (Cacti compatibility) + - `requires = thold:1.2.1` +- **CI runtime matrix**: `.github/workflows/plugin-ci-workflow.yml` + - PHP: `8.1`, `8.2`, `8.3`, `8.4` + - MariaDB service: `10.6` +- **Language/frameworks observed**: + - PHP plugin code (`setup.php`, `monitor.php`, `poller_monitor.php`) + - CSS themes (`monitor.css`, `themes/*/monitor.css`) + - GitHub Actions workflow YAML + - gettext localization (`locales/po/*.po`, `locales/LC_MESSAGES/*.mo`) + +Do not introduce APIs or syntax incompatible with the supported Cacti/plugin environment and CI matrix. + +## Context Files + +If present in future, prioritize `.github/copilot` files in this order: + +- `architecture.md` +- `tech-stack.md` +- `coding-standards.md` +- `folder-structure.md` +- `exemplars.md` + +If these files do not exist, use repository patterns directly. + +## Architecture and Boundaries (Observed) + +This repository is a **single Cacti plugin** with procedural PHP entrypoints and Cacti hook integration. + +- **Plugin lifecycle and hooks**: `setup.php` + - Registration via `api_plugin_register_hook()` and `api_plugin_register_realm()`. + - Upgrade/install logic via `plugin_monitor_install()`, `plugin_monitor_upgrade()`, `monitor_check_upgrade()`. +- **Web UI controller/rendering**: `monitor.php` + - Request routing by `action` switch. + - Rendering and UI state via Cacti helper functions. +- **CLI/poller processing**: `poller_monitor.php` + - Argument parsing (`--help`, `--version`, `--force`, `--debug`). + - Notification and uptime/reboot processing. +- **Presentation assets**: `monitor.css`, `themes/*/monitor.css`, `sounds/`, `images/`. +- **Localization assets**: gettext `.po/.mo` files under `locales/`. + +Do not refactor this plugin into OO/framework patterns unless the existing code in this repository does so first. + +## Codebase Scanning Instructions + +For any new change: + +1. Find similar logic in the same entrypoint type (`setup.php` for hooks/config, `monitor.php` for UI routing/rendering, `poller_monitor.php` for CLI/poller flows). +2. Match these patterns exactly: + - Function naming: `monitor_*`, `plugin_monitor_*` + - Procedural flow with top-level includes and switch routing + - Cacti helper/database APIs (`db_fetch_*`, `db_execute*`, `read_config_option`, `set_config_option`) + - Localization calls: `__('Text', 'monitor')` +3. Reuse existing request handling and sanitization helpers before adding any new input handling. +4. Prefer existing table names and schema migration style in `monitor_check_upgrade()` and related setup functions. +5. Avoid introducing new architectural abstractions not currently used. + +## Code Quality Standards (Evidence-Based) + +### Maintainability + +- Keep procedural style and naming consistent with existing files. +- Keep related behavior grouped by responsibility (install/upgrade/hooks in `setup.php`; UI rendering in `monitor.php`; poller logic in `poller_monitor.php`). +- Prefer small helper functions as seen throughout the codebase. + +### Security + +- Follow current input-handling patterns: + - `get_request_var()`, `get_nfilter_request_var()`, `get_filter_request_var()`, `set_request_var()` + - `validate_request_vars()` where appropriate +- Escape output using existing helpers such as `html_escape()` for HTML contexts. +- Use prepared database calls where parameters are dynamic (`db_fetch_*_prepared`, `db_execute_prepared`) following existing usage. + +### Performance + +- Match existing data-access style: targeted SQL queries and batched operations. +- Preserve existing poller timing/stat collection behavior in `poller_monitor.php`. +- Avoid adding expensive repeated queries inside loops when existing code already provides reusable query patterns. + +### Testability + +- Keep logic in discrete functions so behavior can be linted, statically analyzed, and integration-tested as in CI. +- Preserve CLI flags and deterministic output patterns used by workflow checks. + +## Documentation Requirements + +Documentation level in this repository is **Standard**: + +- File-level header blocks are consistently present in PHP and workflow files. +- Inline comments are concise and purpose-driven. +- Follow existing style: do not over-document trivial lines. +- Update `CHANGELOG.md` style only when project maintainers require release note updates. + +## Testing Approach (Observed) + +This repository relies on **integration + static checks** via GitHub Actions: + +- PHP syntax lint (`php -l` over plugin files) +- Composer-based lint/style checks from Cacti workspace (`lint`, `phpcsfixer` scripts) +- Runtime integration checks by installing Cacti + plugin and running poller +- No repository-local unit test suite is currently present + +When generating code: + +- Ensure code is syntactically valid PHP. +- Keep style and lint compatibility with current Cacti-driven CI steps. +- Do not invent a new test framework in this plugin unless requested. + +## PHP-Specific Guidelines + +- Maintain procedural PHP structure and Cacti plugin API usage. +- Keep includes, globals, and helper calls consistent with existing patterns. +- Match array formatting and control-flow style used in current files. +- Continue using gettext domain `'monitor'` for user-facing strings. +- Preserve compatibility with CI-validated PHP versions and Cacti/plugin constraints. + +## Versioning and Change Tracking + +- Follow existing changelog conventions in `CHANGELOG.md` (sectioned by release, `issue#` / `feature#` bullets). +- Treat plugin version metadata in `INFO` as the authoritative plugin version declaration. + +## General Best Practices for This Repository + +- Prioritize consistency with existing code over introducing newer external patterns. +- Reuse existing Cacti APIs and plugin hooks instead of custom abstractions. +- Keep CSS/theme changes aligned with current theme folder structure. +- Keep localization updates aligned with existing gettext files and domain usage. +- If uncertain, mirror nearby code patterns in the same file first. + +## Project-Specific Guidance + +- Scan relevant files before generating code; do not assume patterns from unrelated projects. +- Respect current architectural boundaries: + - Hook/config lifecycle in `setup.php` + - UI/rendering workflow in `monitor.php` + - Poller/notification workflow in `poller_monitor.php` +- When conflicts arise, prefer patterns that are currently active in top-level runtime paths and CI-validated flows. +- Always prioritize compatibility and consistency with this repository over external “best practice” rewrites. diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml new file mode 100644 index 0000000..ee2df5b --- /dev/null +++ b/.github/workflows/plugin-ci-workflow.yml @@ -0,0 +1,216 @@ +# +-------------------------------------------------------------------------+ +# | Copyright (C) 2004-2025 The Cacti Group | +# | | +# | This program is free software; you can redistribute it and/or | +# | modify it under the terms of the GNU General Public License | +# | as published by the Free Software Foundation; either version 2 | +# | of the License, or (at your option) any later version. | +# | | +# | This program 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 General Public License for more details. | +# +-------------------------------------------------------------------------+ +# | Cacti: The Complete RRDtool-based Graphing Solution | +# +-------------------------------------------------------------------------+ +# | This code is designed, written, and maintained by the Cacti Group. See | +# | about.php and/or the AUTHORS file for specific developer information. | +# +-------------------------------------------------------------------------+ +# | http://www.cacti.net/ | +# +-------------------------------------------------------------------------+ + +name: Plugin Integration Tests + +on: + push: + branches: + - main + - develop + pull_request: + branches: + - main + - develop + +jobs: + integration-test: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + php: ['8.1', '8.2', '8.3', '8.4'] + os: [ubuntu-latest] + + services: + mariadb: + image: mariadb:10.6 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + name: PHP ${{ matrix.php }} Integration Test on ${{ matrix.os }} + + steps: + - name: Checkout Cacti + uses: actions/checkout@v4 + with: + repository: Cacti/cacti + path: cacti + + - name: Checkout Monitor Plugin + uses: actions/checkout@v4 + with: + path: cacti/plugins/monitor + + - name: Install PHP ${{ matrix.php }} + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: intl, mysql, gd, ldap, gmp, xml, curl, json, mbstring + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + + - name: Check PHP version + run: php -v + + - name: Run apt-get update + run: sudo apt-get update + + - name: Install System Dependencies + run: sudo apt-get install -y apache2 snmp snmpd rrdtool fping libapache2-mod-php${{ matrix.php }} + + - name: Start SNMPD Agent and Test + run: | + sudo systemctl start snmpd + sudo snmpwalk -c public -v2c -On localhost .1.3.6.1.2.1.1 + + - name: Setup Permissions + run: | + sudo chown -R www-data:runner ${{ github.workspace }}/cacti + sudo find ${{ github.workspace }}/cacti -type d -exec chmod 775 {} \; + sudo find ${{ github.workspace }}/cacti -type f -exec chmod 664 {} \; + sudo chmod +x ${{ github.workspace }}/cacti/cmd.php + sudo chmod +x ${{ github.workspace }}/cacti/poller.php + + - name: Create MySQL Config + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + cat ~/.my.cnf + + - name: Initialize Cacti Database + env: + MYSQL_AUTH_USR: '--defaults-file=~/.my.cnf' + run: | + mysql $MYSQL_AUTH_USR -e 'CREATE DATABASE IF NOT EXISTS cacti;' + mysql $MYSQL_AUTH_USR -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" + mysql $MYSQL_AUTH_USR -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "FLUSH PRIVILEGES;" + mysql $MYSQL_AUTH_USR cacti < ${{ github.workspace }}/cacti/cacti.sql + mysql $MYSQL_AUTH_USR -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti + + - name: Validate composer files + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + composer validate --strict || true + fi + + - name: Install Composer Dependencies + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + sudo composer install --prefer-dist --no-progress + fi + + - name: Create Cacti config.php + run: | + cat ${{ github.workspace }}/cacti/include/config.php.dist | \ + sed -r "s/localhost/127.0.0.1/g" | \ + sed -r "s/'cacti'/'cacti'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" > ${{ github.workspace }}/cacti/include/config.php + sudo chmod 664 ${{ github.workspace }}/cacti/include/config.php + + - name: Configure Apache + run: | + cat << 'EOF' | sed 's#GITHUB_WORKSPACE#${{ github.workspace }}#g' > /tmp/cacti.conf + + ServerAdmin webmaster@localhost + DocumentRoot GITHUB_WORKSPACE/cacti + + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + + + ErrorLog ${APACHE_LOG_DIR}/error.log + CustomLog ${APACHE_LOG_DIR}/access.log combined + + EOF + sudo cp /tmp/cacti.conf /etc/apache2/sites-available/000-default.conf + sudo systemctl restart apache2 + + - name: Install Cacti via CLI + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/install_cacti.php --accept-eula --install --force + + - name: Install Monitor Plugin + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/plugin_manage.php --plugin=monitor --install --enable + + - name: Check PHP Syntax for Plugin + run: | + cd ${{ github.workspace }}/cacti/plugins/monitor + if find . -name '*.php' -exec php -l {} 2>&1 \; | grep -iv 'no syntax errors detected'; then + echo "Syntax errors found!" + exit 1 + fi + + - name: Remove the plugins directory exclusion from the .phpstan.neon + run: sed '/plugins/d' -i .phpstan.neon + working-directory: ${{ github.workspace }}/cacti + + - name: Mark composer scripts executable + run: sudo chmod +x ${{ github.workspace }}/cacti/include/vendor/bin/* + + - name: Run Linter on base code + run: composer run-script lint ${{ github.workspace }}/cacti/plugins/monitor + working-directory: ${{ github.workspace }}/cacti + + - name: Checking coding standards on base code + run: composer run-script phpcsfixer ${{ github.workspace }}/cacti/plugins/monitor + working-directory: ${{ github.workspace }}/cacti + +# - name: Run PHPStan at Level 6 on base code outside of Composer due to technical issues +# run: ./include/vendor/bin/phpstan analyze --level 6 ${{ github.workspace }}/cacti/plugins/monitor +# working-directory: ${{ github.workspace }}/cacti + + - name: Run Cacti Poller + run: | + cd ${{ github.workspace }}/cacti + sudo php poller.php --poller=1 --force --debug + if ! grep -q "SYSTEM STATS" log/cacti.log; then + echo "Cacti poller did not finish successfully" + cat log/cacti.log + exit 1 + fi + + - name: View Cacti Logs + if: always() + run: | + if [ -f ${{ github.workspace }}/cacti/log/cacti.log ]; then + echo "=== Cacti Log ===" + sudo cat ${{ github.workspace }}/cacti/log/cacti.log + fi diff --git a/.gitignore b/.gitignore index eb71606..f3d8733 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ # +-------------------------------------------------------------------------+ locales/po/*.mo +vendor/ diff --git a/index.php b/index.php index e6bad33..828ecbe 100644 --- a/index.php +++ b/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/locales/LC_MESSAGES/index.php b/locales/LC_MESSAGES/index.php index e6bad33..828ecbe 100644 --- a/locales/LC_MESSAGES/index.php +++ b/locales/LC_MESSAGES/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/locales/index.php b/locales/index.php index e6bad33..828ecbe 100644 --- a/locales/index.php +++ b/locales/index.php @@ -23,4 +23,3 @@ */ header('Location:../index.php'); - diff --git a/monitor.php b/monitor.php index 7650422..7745aba 100644 --- a/monitor.php +++ b/monitor.php @@ -29,18 +29,18 @@ set_default_action(); -/* Record Start Time */ +// Record Start Time $start = microtime(true); -$criticalities = array( +$criticalities = [ 0 => __('Disabled', 'monitor'), 1 => __('Low', 'monitor'), 2 => __('Medium', 'monitor'), 3 => __('High', 'monitor'), 4 => __('Mission Critical', 'monitor') -); +]; -$iclasses = array( +$iclasses = [ 0 => 'deviceUnknown', 1 => 'deviceDown', 2 => 'deviceRecovering', @@ -51,9 +51,9 @@ 7 => 'deviceWarning', 8 => 'deviceAlert', 9 => 'deviceThresholdMuted', -); +]; -$icolorsdisplay = array( +$icolorsdisplay = [ 0 => __('Unknown', 'monitor'), 1 => __('Down', 'monitor'), 2 => __('Recovering', 'monitor'), @@ -64,18 +64,18 @@ 6 => __('No Availability Check', 'monitor'), 7 => __('Warning Ping', 'monitor'), 8 => __('Alert Ping', 'monitor'), -); +]; -$classes = array( +$classes = [ 'monitor_exsmall' => __('Extra Small', 'monitor'), 'monitor_small' => __('Small', 'monitor'), 'monitor_medium' => __('Medium', 'monitor'), 'monitor_large' => __('Large', 'monitor'), 'monitor_exlarge' => __('Extra Large', 'monitor'), 'monitor_errorzoom' => __('Zoom', 'monitor') -); +]; -$monitor_status = array( +$monitor_status = [ -2 => __('All Devices', 'monitor'), -1 => __('All Monitored Devices', 'monitor'), 0 => __('Not Up', 'monitor'), @@ -83,24 +83,24 @@ 2 => __('Not Up, Triggered or Breached', 'monitor'), -4 => __('Devices without Thresholds', 'monitor'), -3 => __('Devices not Monitored', 'monitor'), -); +]; -$monitor_view_type = array( +$monitor_view_type = [ 'default' => __('Default', 'monitor'), 'list' => __('List', 'monitor'), 'names' => __('Names only', 'monitor'), 'tiles' => __('Tiles', 'monitor'), 'tilesadt' => __('Tiles & Time', 'monitor') -); +]; -$monitor_grouping = array( +$monitor_grouping = [ 'default' => __('Default', 'monitor'), 'tree' => __('Tree', 'monitor'), 'site' => __('Site', 'monitor'), 'template' => __('Device Template', 'monitor') -); +]; -$monitor_trim = array( +$monitor_trim = [ 0 => __('Default', 'monitor'), -1 => __('Full', 'monitor'), 10 => __('10 Chars', 'monitor'), @@ -110,7 +110,7 @@ 50 => __('50 Chars', 'monitor'), 75 => __('75 Chars', 'monitor'), 100 => __('100 Chars', 'monitor'), -); +]; global $thold_hosts, $maxchars; @@ -122,7 +122,7 @@ $_SESSION['names'] = 0; if (!isset($_SESSION['monitor_muted_hosts'])) { - $_SESSION['monitor_muted_hosts'] = array(); + $_SESSION['monitor_muted_hosts'] = []; } validate_request_vars(); @@ -180,15 +180,15 @@ function load_dashboard_settings() { $db_settings = db_fetch_cell_prepared('SELECT url FROM plugin_monitor_dashboards WHERE id = ?', - array($dashboard)); + [$dashboard]); if ($db_settings != '') { $db_settings = str_replace('monitor.php?', '', $db_settings); - $settings = explode('&', $db_settings); + $settings = explode('&', $db_settings); if (cacti_sizeof($settings)) { - foreach($settings as $setting) { - list($name, $value) = explode('=', $setting); + foreach ($settings as $setting) { + [$name, $value] = explode('=', $setting); set_request_var($name, $value); } @@ -205,22 +205,22 @@ function draw_page() { if (cacti_sizeof($errored_list) && read_user_setting('monitor_error_zoom') == 'on') { if ($_SESSION['monitor_zoom_state'] == 0) { - $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; + $mon_zoom_state = $_SESSION['monitor_zoom_state'] = 1; $_SESSION['mon_zoom_hist_status'] = get_nfilter_request_var('status'); $_SESSION['mon_zoom_hist_size'] = get_nfilter_request_var('size'); - $dozoomrefresh = true; - $dozoombgndcolor = true; + $dozoomrefresh = true; + $dozoombgndcolor = true; } } elseif (isset($_SESSION['monitor_zoom_state']) && $_SESSION['monitor_zoom_state'] == 1) { $_SESSION['monitor_zoom_state'] = 0; - $dozoomrefresh = true; - $dozoombgndcolor = false; + $dozoomrefresh = true; + $dozoombgndcolor = false; } $name = db_fetch_cell_prepared('SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - array(get_request_var('dashboard'))); + [get_request_var('dashboard')]); if ($name == '') { $name = __('New Dashboard', 'monitor'); @@ -260,15 +260,16 @@ function draw_page() { if (read_user_setting('monitor_legend', read_config_option('monitor_legend'))) { print "
"; - foreach($iclasses as $index => $class) { - print "
" . $icolorsdisplay[$index] . "
"; + foreach ($iclasses as $index => $class) { + print "
" . $icolorsdisplay[$index] . '
'; } - print "
"; + print ''; } // If the host is down, we need to insert the embedded wav file $monitor_sound = get_monitor_sound(); + if (is_monitor_audible()) { if (read_user_setting('monitor_sound_loop', read_config_option('monitor_sound_loop'))) { print ""; @@ -289,8 +290,9 @@ function is_monitor_audible() { function get_monitor_sound() { $sound = read_user_setting('monitor_sound', read_config_option('monitor_sound')); clearstatcache(); - $file = dirname(__FILE__) . '/sounds/' . $sound; + $file = __DIR__ . '/sounds/' . $sound; $exists = file_exists($file); + return $exists ? $sound : ''; } @@ -319,8 +321,8 @@ function find_down_hosts() { function unmute_up_non_triggered_hosts($dhosts) { if (isset($_SESSION['monitor_muted_hosts'])) { - foreach($_SESSION['monitor_muted_hosts'] AS $index => $host_id) { - if (array_search($host_id, $dhosts) === false) { + foreach ($_SESSION['monitor_muted_hosts'] as $index => $host_id) { + if (array_search($host_id, $dhosts, true) === false) { unset($_SESSION['monitor_muted_hosts'][$index]); } } @@ -333,7 +335,7 @@ function mute_all_hosts() { } function unmute_all_hosts() { - $_SESSION['monitor_muted_hosts'] = array(); + $_SESSION['monitor_muted_hosts'] = []; unmute_user(); } @@ -348,10 +350,10 @@ function unmute_user() { } function get_thold_where() { - if (get_request_var('status') == '2') { /* breached */ + if (get_request_var('status') == '2') { // breached return "(td.thold_enabled = 'on' AND (td.thold_alert != 0 OR td.bl_alert > 0))"; - } else { /* triggered */ + } else { // triggered return "(td.thold_enabled='on' AND ((td.thold_alert != 0 AND td.thold_fail_count >= td.thold_fail_trigger) OR (td.bl_alert > 0 AND td.bl_fail_count >= td.bl_fail_trigger)))"; @@ -359,15 +361,15 @@ function get_thold_where() { } function check_tholds() { - $thold_hosts = array(); + $thold_hosts = []; if (api_plugin_is_enabled('thold')) { return array_rekey( - db_fetch_assoc("SELECT DISTINCT dl.host_id + db_fetch_assoc('SELECT DISTINCT dl.host_id FROM thold_data AS td INNER JOIN data_local AS dl ON td.local_data_id=dl.id - WHERE " . get_thold_where()), + WHERE ' . get_thold_where()), 'host_id', 'host_id' ); } @@ -381,24 +383,31 @@ function get_filter_text() { switch(get_request_var('status')) { case '-4': $filter .= __('Devices without Thresholds', 'monitor'); + break; case '-3': $filter .= __('Not Monitored Devices', 'monitor'); + break; case '-2': $filter .= __('All Devices', 'monitor'); + break; case '-1': $filter .= __('All Monitored Devices', 'monitor'); + break; case '0': $filter .= __('Monitored Devices either Down or Recovering', 'monitor'); + break; case '1': $filter .= __('Monitored Devices either Down, Recovering, or with Triggered Thresholds', 'monitor'); + break; case '2': $filter .= __('Monitored Devices either Down, Recovering, or with Breached or Triggered Thresholds', 'monitor'); + break; default: $filter .= __('Unknown monitoring status (%s)', get_request_var('status'), 'monitor'); @@ -407,18 +416,23 @@ function get_filter_text() { switch(get_request_var('crit')) { case '0': $filter .= __(', and All Criticalities', 'monitor'); + break; case '1': $filter .= __(', and of Low Criticality or Higher', 'monitor'); + break; case '2': $filter .= __(', and of Medium Criticality or Higher', 'monitor'); + break; case '3': $filter .= __(', and of High Criticality or Higher', 'monitor'); + break; case '4': $filter .= __(', and of Mission Critical Status', 'monitor'); + break; } @@ -427,7 +441,7 @@ function get_filter_text() { return $filter; } -function draw_filter_dropdown($id, $title, $settings = array(), $value = null) { +function draw_filter_dropdown($id, $title, $settings = [], $value = null) { if ($value == null) { $value = get_nfilter_request_var($id); } @@ -458,7 +472,7 @@ function draw_filter_and_status() { global $dozoombgndcolor, $dozoomrefresh, $zoom_hist_status, $zoom_hist_size, $mon_zoom_state; global $new_form, $new_title, $item_rows; - $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor'):'') . ''; + $header = __('Monitor Filter [ Last Refresh: %s ]', date('g:i:s a', time()), 'monitor') . (get_request_var('refresh') < 99999 ? __(' [ Refresh Again in %d Seconds ]', get_request_var('refresh'), 'monitor') : '') . (get_request_var('view') == 'list' ? __('[ Showing only first 30 Devices ]', 'monitor') : '') . ''; html_start_box($header, '100%', false, '3', 'center', ''); @@ -475,14 +489,14 @@ function draw_filter_and_status() { FROM plugin_monitor_dashboards WHERE user_id = 0 OR user_id = ? ORDER BY name', - array($_SESSION['sess_user_id'])), + [$_SESSION['sess_user_id']]), 'id', 'name' ); $name = db_fetch_cell_prepared('SELECT name FROM plugin_monitor_dashboards WHERE id = ?', - array(get_request_var('dashboard'))); + [get_request_var('dashboard')]); $mon_zoom_status = null; $mon_zoom_size = null; @@ -538,7 +552,7 @@ function draw_filter_and_status() { print '' . PHP_EOL; } - print '' . PHP_EOL; + print '' . PHP_EOL; print '' . PHP_EOL; print ''; print ''; @@ -561,12 +575,14 @@ function draw_filter_and_status() { } if (get_nfilter_request_var('grouping') == 'tree') { - $trees = array(); + $trees = []; + if (get_request_var('grouping') == 'tree') { $trees_allowed = array_rekey(get_allowed_trees(), 'id', 'name'); + if (cacti_sizeof($trees_allowed)) { - $trees_prefix = array(-1 => __('All Trees', 'monitor')); - $trees_suffix = array(-2 => __('Non-Tree Devices', 'monitor')); + $trees_prefix = [-1 => __('All Trees', 'monitor')]; + $trees_suffix = [-2 => __('Non-Tree Devices', 'monitor')]; $trees = $trees_prefix + $trees_allowed + $trees_suffix; } @@ -576,7 +592,8 @@ function draw_filter_and_status() { } if (get_nfilter_request_var('grouping') == 'site') { - $sites = array(); + $sites = []; + if (get_request_var('grouping') == 'site') { $sites = array_rekey( db_fetch_assoc('SELECT id, name @@ -586,8 +603,8 @@ function draw_filter_and_status() { ); if (cacti_sizeof($sites)) { - $sites_prefix = array(-1 => __('All Sites', 'monitor')); - $sites_suffix = array(-2 => __('Non-Site Devices', 'monitor')); + $sites_prefix = [-1 => __('All Sites', 'monitor')]; + $sites_suffix = [-2 => __('Non-Site Devices', 'monitor')]; $sites = $sites_prefix + $sites + $sites_suffix; } @@ -597,7 +614,7 @@ function draw_filter_and_status() { } if (get_request_var('grouping') == 'template') { - $templates = array(); + $templates = []; $templates_allowed = array_rekey( db_fetch_assoc('SELECT ht.id, ht.name, COUNT(gl.id) AS graphs FROM host_template AS ht @@ -611,8 +628,8 @@ function draw_filter_and_status() { ); if (cacti_sizeof($templates_allowed)) { - $templates_prefix = array(-1 => __('All Templates', 'monitor')); - $templates_suffix = array(-2 => __('Non-Templated Devices', 'monitor')); + $templates_prefix = [-1 => __('All Templates', 'monitor')]; + $templates_suffix = [-2 => __('Non-Templated Devices', 'monitor')]; $templates = $templates_prefix + $templates_allowed + $templates_suffix; } @@ -652,7 +669,7 @@ function draw_filter_and_status() { $mbcolora = db_fetch_row_prepared('SELECT * FROM colors WHERE id = ?', - array(read_user_setting('monitor_error_background'))); + [read_user_setting('monitor_error_background')]); $monitor_error_fontsize = read_user_setting('monitor_error_fontsize') . 'px'; @@ -662,7 +679,7 @@ function draw_filter_and_status() { $mbcolor = 'snow'; } } else { - $mbcolor = ''; + $mbcolor = ''; $monitor_error_fontsize = '10px'; } @@ -670,9 +687,9 @@ function draw_filter_and_status() {