Home » #Technology » Real-Time Production Analytics Dashboard on PHP and Bash

Real-Time Production Analytics Dashboard on PHP and Bash

With over 18 years of experience building enterprise-level applications and now as an entrepreneur and tech advisor, I’ve learned firsthand how crucial it is to closely monitor system performance in production environments. Ensuring everything runs smoothly is vital for maintaining operational efficiency and preventing disruptions. Whether you’re managing a fleet of servers or monitoring a single critical machine, having real-time insights into CPU usage, memory consumption, disk space, and running processes is indispensable. In this tech concept, we’ll walk through the creation of a real-time system analytics dashboard using PHP and Bash scripts, allowing you to monitor these vital metrics directly from a web page.

Why Build a System Analytics Dashboard?

Monitoring system performance is a foundational task for any IT professional. It helps in preemptively identifying potential issues, optimizing resource allocation, and ensuring that critical processes remain uninterrupted. While there are many tools available for system monitoring, building your own dashboard offers several advantages:

  1. Customization: Tailor the dashboard to your specific needs and display only the metrics that matter most to you.
  2. Simplicity: Integrate the dashboard seamlessly into your existing infrastructure without the overhead of installing and configuring third-party software.
  3. Real-Time Insights: Get real-time data that is refreshed automatically, providing you with up-to-the-minute information.

Use Case: Monitoring a Production Server

Imagine you’re managing a production server that handles critical tasks for your business. Any disruption in service could result in significant downtime, impacting your operations. By setting up a real-time system analytics dashboard, you can keep a close eye on resource utilization, ensuring that you can respond to potential issues before they escalate.

The Dashboard: What It Displays

The system analytics dashboard we’ll build displays the following metrics:

  1. CPU Usage: Percentage of CPU load on the system.
  2. Memory Usage: Percentage of RAM currently in use.
  3. Disk Usage: Detailed information on disk space usage across all mounted filesystems, akin to the df -h command.
  4. Top Running Processes: The top 10 processes consuming the most CPU, similar to what you see with the top or ps commands.

These metrics are refreshed every minute to provide a near real-time view of your system’s performance.

Building the Dashboard

Let’s dive into the code. The following sections will walk you through the PHP and Bash scripts that power the dashboard.

Step 1: Gathering System Metrics with PHP and Bash

We start by creating a PHP script (get_system_info.php) that gathers system metrics. This script leverages Bash commands to fetch the necessary data.

<?php
// Get CPU usage
function getCpuUsage() {
    $load = sys_getloadavg();
    return $load[0];
}

// Get memory usage
function getMemoryUsage() {
    $memoryInfo = file_get_contents("/proc/meminfo");
    preg_match("/^MemTotal:\s+(\d+)\skB$/m", $memoryInfo, $total);
    preg_match("/^MemAvailable:\s+(\d+)\skB$/m", $memoryInfo, $available);
    $used = $total[1] - $available[1];
    return round(($used / $total[1]) * 100, 2);
}

// Get disk usage (similar to df -h)
function getDiskUsage() {
    $output = shell_exec('df -h');
    return nl2br($output);
}

// Get top running processes
function getTopProcesses() {
    $output = shell_exec('ps aux --sort=-%cpu | head -n 10');
    return nl2br($output);
}

?>

<!-- 1st Row: CPU and Memory Usage -->
<div class="card">
    <h2><?php echo getCpuUsage(); ?>%</h2>
    <p>CPU Usage</p>
</div>
<div class="card">
    <h2><?php echo getMemoryUsage(); ?>%</h2>
    <p>Memory Usage</p>
</div>

<!-- 2nd Row: Disk Usage -->
<div class="card full-width-card">
    <h2>Disk Usage</h2>
    <pre><?php echo getDiskUsage(); ?></pre>
</div>

<!-- 3rd Row: Top Running Processes -->
<div class="card full-width-card">
    <h2>Top Running Processes</h2>
    <pre><?php echo getTopProcesses(); ?></pre>
</div>

This script collects data on CPU and memory usage, disk space utilization, and the top running processes. It outputs this data in a format suitable for display on a web page.

Step 2: Displaying the Dashboard

Next, we create the main index.php file, which will display the system metrics in a clean, organized layout.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Analytics Dashboard #AskDushyant #NextStruggle (www.nextstruggle.com)</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }
        .dashboard {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            text-align: center;
        }
        .card {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            width: 300px;
            text-align: left;
            flex: 1 1 45%; /* Flex basis for 2 cards in the first row */
        }
        .full-width-card {
            flex: 1 1 90%; /* Flex basis for single cards in the 2nd and 3rd rows */
            margin: 0 auto; /* Center the card */
        }
        .card h2 {
            margin: 0 0 10px;
            font-size: 1.5em;
            text-align: center;
        }
        pre {
            background-color: #f9f9f9;
            padding: 10px;
            border-radius: 5px;
            overflow: auto;
            max-height: 200px;
        }
    </style>
</head>
<body>

    <h1>System Analytics Dashboard</h1>
    <div class="dashboard">
        <?php include 'get_system_info.php'; ?>
    </div>

    <script>
        function refreshData() {
            fetch('get_system_info.php')
                .then(response => response.text())
                .then(data => {
                    document.querySelector('.dashboard').innerHTML = data;
                })
                .catch(error => console.error('Error:', error));
        }

        setInterval(refreshData, 60000); // Refresh every 60 seconds (1 minute)
    </script>

</body>
</html>

This code defines the structure and style of the dashboard. It arranges the metrics in three rows: the first row displays two cards (CPU and Memory Usage), while the second and third rows display one full-width card each (Disk Usage and Top Running Processes, respectively).

My Tech Advice: Building your own system analytics dashboard offers unparalleled flexibility and control over how you monitor your systems. With this setup, you can keep a close eye on critical metrics, allowing you to make informed decisions and respond to potential issues before they become problems. Deploy this on your production servers, and you’ll have a robust, real-time monitoring solution at your fingertips, all while understanding every detail of its implementation.

#AskDushyant
#CodeSnippet #Analytics #OperatingSystem #Production #PHP #Bash #Shell
Note: The code provided is a starting point for Linux server—feel free to expand it with additional metrics or customize it to better fit your requirement. 

Leave a Reply

Your email address will not be published. Required fields are marked *