Skip to content

Commit

Permalink
Merge pull request #6 from saeedvaziry/migrate-to-google-charts
Browse files Browse the repository at this point in the history
Migrate to google charts
  • Loading branch information
saeedvaziry authored Feb 6, 2022
2 parents 286ed41 + bb40233 commit a2f5bb9
Show file tree
Hide file tree
Showing 11 changed files with 193 additions and 157 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ composer require saeedvaziry/laravel-monitoring
**2)** Publish vendors

```shell
php artisan vendor:publish --provider="SaeedVaziry\Monitoring\MonitoringServiceProvider"
php artisan monitoring:publish
```

**3)** Run migrations
Expand Down
2 changes: 2 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
<server name="APP_ENV" value="testing"/>
<env name="APP_KEY" value="AckfSECXIvnK5r28GVIWUAxmbBSjTsmF"/>
<server name="MONITORING_INSTANCE_NAME" value="test"/>
<!-- <server name="DB_DATABASE" value="laravel"/> -->
<!-- <server name="DB_USERNAME" value="root"/> -->
</php>
</phpunit>
2 changes: 1 addition & 1 deletion public/js/app.js

Large diffs are not rendered by default.

7 changes: 0 additions & 7 deletions public/js/app.js.LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
/*!
* Chart.js v2.9.4
* https://www.chartjs.org
* (c) 2020 Chart.js Contributors
* Released under the MIT License
*/

//! Copyright (c) JS Foundation and other contributors

//! github.com/moment/moment-timezone
Expand Down
2 changes: 1 addition & 1 deletion public/mix-manifest.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"/js/app.js": "/js/app.js?id=3ee64901dfc7c91aa6bf",
"/js/app.js": "/js/app.js?id=74f6221d994c8a941a42",
"/css/app.css": "/css/app.css?id=72db21d04a6f1275979b"
}
91 changes: 55 additions & 36 deletions resources/js/components/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
<div class="max-w-5xl flex items-center justify-between mx-auto py-7 px-5">
<h2 class="text-2xl dark:text-gray-300">Monitoring Dashboard</h2>
<div class="flex items-center">
<v-select class="mr-2" v-model="duration">
<v-select class="mr-2" v-model="duration" @change="getData">
<option value="hour">Hour</option>
<option value="day" disabled>Day</option>
<option value="day">Day</option>
</v-select>
<v-icon-button type="button" @click="getData" :class="{'opacity-50': loading}" :disabled="loading">
<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="sync-alt" class="w-4 h-4 fill-current text-white" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M370.72 133.28C339.458 104.008 298.888 87.962 255.848 88c-77.458.068-144.328 53.178-162.791 126.85-1.344 5.363-6.122 9.15-11.651 9.15H24.103c-7.498 0-13.194-6.807-11.807-14.176C33.933 94.924 134.813 8 256 8c66.448 0 126.791 26.136 171.315 68.685L463.03 40.97C478.149 25.851 504 36.559 504 57.941V192c0 13.255-10.745 24-24 24H345.941c-21.382 0-32.09-25.851-16.971-40.971l41.75-41.749zM32 296h134.059c21.382 0 32.09 25.851 16.971 40.971l-41.75 41.75c31.262 29.273 71.835 45.319 114.876 45.28 77.418-.07 144.315-53.144 162.787-126.849 1.344-5.363 6.122-9.15 11.651-9.15h57.304c7.498 0 13.194 6.807 11.807 14.176C478.067 417.076 377.187 504 256 504c-66.448 0-126.791-26.136-171.315-68.685L48.97 471.03C33.851 486.149 8 475.441 8 454.059V320c0-13.255 10.745-24 24-24z"></path></svg>
Expand Down Expand Up @@ -49,7 +49,7 @@
</div>
</div>
<div class="col-span-3 bg-white dark:bg-gray-800 dark:text-gray-300 rounded-md shadow p-3" style="height: 329px">
<canvas :id="`${instance}-chart`" height="304" width="700" class="mx-auto"></canvas>
<div :id="`${instance}-chart`" style="height: 304px" class="chart mx-auto"></div>
</div>
</div>
</div>
Expand All @@ -64,7 +64,6 @@
<script>
import axios from 'axios';
import moment from "moment-timezone";
import Chart from 'chart.js';
import VIconButton from "@/components/IconButton";
import VLoader from "@/components/Loader";
import VAlert from "@/components/Alert";
Expand All @@ -83,7 +82,8 @@
chartsData: {},
charts: {},
alerts: [],
duration: 'hour'
duration: 'hour',
theme: window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}
},
mounted() {
Expand All @@ -98,43 +98,62 @@
this.records = res.data.records;
this.chartsData = res.data.charts;
this.alerts = res.data.alerts;
setTimeout(() => {
this.instances.map((instance) => {
this.chartsData[instance].labels.map((value, i) => {
this.chartsData[instance].labels[i] = moment(value).tz(moment.tz.guess()).format('hh:mm')
});
this.generateChart(instance);
})
}, 100)
this.instances.map(item => {
this.generateChart(item);
});
}).then(() => {
this.loading = false;
});
},
generateChart(instance) {
if (this.charts[instance]) {
this.charts[instance].destroy();
}
let ctx = document.getElementById(instance + '-chart').getContext('2d');
this.charts[instance] = new Chart(ctx, {
type: 'line',
data: {
labels: this.chartsData[instance].labels,
datasets: this.chartsData[instance].datasets,
},
options: {
responsive: false,
scales: {
yAxes: [{
grid: {
color: '#f1f5f9'
},
min: 0,
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
let _this = this;
function drawChart() {
let chartData = [['Date', 'CPU', 'Memory', 'Disk']];
_this.chartsData[instance].map(item => {
chartData.push([
new Date(moment(item.created_at).tz(moment.tz.guess()).format()),
item.cpu,
item.memory,
item.disk,
])
})
let data = google.visualization.arrayToDataTable(chartData);
let options = {
curveType: 'function',
displayExactValues: true,
groupByRowLabel: true,
colors: ['#2563eb', '#5d25eb', '#16af93'],
chartArea: {
width: '90%'
},
vAxis: {
viewWindow: {
max: 100,
beginAtZero: true
}]
}
}
});
min: 0
},
textStyle: {
color: _this.theme === 'dark' ? '#ffffff' : '#111729',
}
},
hAxis: {
textStyle: {
color: _this.theme === 'dark' ? '#ffffff' : '#111729',
}
},
legend: {
position: 'bottom',
textStyle: {
color: _this.theme === 'dark' ? '#ffffff' : '#111729',
}
},
backgroundColor: _this.theme === 'dark' ? '#111729' : '#ffffff'
};
let chart = new google.visualization.LineChart(document.getElementById(instance + '-chart'));
chart.draw(data, options);
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions resources/views/index.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
prefix: '{{ config('monitoring.routes.prefix') }}'
}
</script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body class="bg-gray-100 dark:bg-gray-900 min-h-screen text-gray-700 min-w-max">
<div id="app" class="min-h-screen">
Expand Down
45 changes: 45 additions & 0 deletions src/Commands/PublishCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace SaeedVaziry\Monitoring\Commands;

use Illuminate\Console\Command;

class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monitoring:publish {--force : Overwrite any existing files}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish all of the resources';

/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$this->call('vendor:publish', [
'--tag' => 'monitoring-config',
'--force' => $this->option('force'),
]);

$this->call('vendor:publish', [
'--tag' => 'monitoring-assets',
'--force' => true,
]);

$this->call('vendor:publish', [
'--tag' => 'monitoring-migrations',
'--force' => $this->option('force'),
]);
}
}
91 changes: 19 additions & 72 deletions src/HasRecords.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace SaeedVaziry\Monitoring;

use Illuminate\Support\Collection;

trait HasRecords
{
/**
Expand All @@ -25,23 +23,38 @@ protected function getInstances()

/**
* @param array $instances
* @param $duration
*
* @return array
*/
protected function getRecords(array $instances)
protected function getRecords(array $instances, $duration)
{
$records = [];
foreach ($instances as $instance) {
$records[$instance] = app(config('monitoring.models.monitoring_record'))
->where('instance_name', $instance)
->orderByDesc('id')
->take(60)
->get();
->where('created_at', '>', $this->getDurationInTime($duration))
->select(['created_at', 'cpu', 'memory', 'disk'])
->get()
->toArray();
}

return $records;
}

/**
* @param string|null $duration
*
* @return mixed
*/
private function getDurationInTime($duration = null)
{
return match ($duration) {
'day' => now()->subDay(),
default => now()->subHour(),
};
}

/**
* @param array $instances
*
Expand All @@ -59,70 +72,4 @@ protected function getLastRecords(array $instances)

return $records;
}

/**
* @param Collection $records
*
* @return array
*/
protected function getRecordsChart(Collection $records)
{
$labels = [];
$cpu = [];
$memory = [];
$disk = [];
for ($i = $records->count() - 1; $i >= 0; $i--) {
$cpu[] = $records[$i]->cpu;
$memory[] = $records[$i]->memory;
$disk[] = $records[$i]->disk;
$labels[] = $records[$i]->created_at;
}

return [
'labels' => $labels,
'datasets' => [
[
'label' => 'CPU',
'data' => $cpu,
'borderWidth' => 1.5,
'fill' => false,
'borderColor' => config('monitoring.chart_colors.cpu.border_color'),
'backgroundColor' => config('monitoring.chart_colors.cpu.background_color'),
],
[
'label' => 'Memory',
'data' => $memory,
'borderWidth' => 1.5,
'fill' => false,
'borderColor' => config('monitoring.chart_colors.memory.border_color'),
'backgroundColor' => config('monitoring.chart_colors.memory.background_color'),
],
[
'label' => 'Disk',
'data' => $disk,
'borderWidth' => 1.5,
'fill' => false,
'borderColor' => config('monitoring.chart_colors.disk.border_color'),
'backgroundColor' => config('monitoring.chart_colors.disk.background_color'),
],
],
];
}

/**
* @param array $records
*
* @throws \Exception
*
* @return array
*/
protected function getCharts(array $records)
{
$charts = [];
foreach ($records as $key => $record) {
$charts[$key] = $this->getRecordsChart($record);
}

return $charts;
}
}
4 changes: 2 additions & 2 deletions src/Http/MonitoringRecordController.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ class MonitoringRecordController extends Controller
public function records(Request $request)
{
$request->validate([
'duration' => 'in:hour',
'duration' => 'in:hour,day',
]);

$instances = $this->getInstances();
$charts = $this->getCharts($this->getRecords($instances));
$charts = $this->getRecords($instances, $request->duration);

return response()->json([
'instances' => $instances,
Expand Down
Loading

0 comments on commit a2f5bb9

Please sign in to comment.