Laravel 9中的资源监控入门
大多数系统已经存在,为我们提供了一个监测系统的CPU和内存使用情况的方法。然而,他们可能不是很灵活,无法支持我们的日常需求。
开发人员更多的是面临着资源管理的问题,当所有可用的资源都被消耗掉时,机器就会冻结或挂起。
尽管有可能使用Windows任务管理器和Linux的系统监视器来监控这些资源,但这在共享主机中被证明是一个障碍。
在本教程中, 我们将学习如何建立一个Laravel系统,它有能力监测共享主机服务器的资源使用情况。
前提条件
为了能够理解和学习本教程, 读者至少应该具备以下知识:
- Laravel的基本知识.在本教程中, 我们将使用Laravel 9.
- PHP中面向对象编程的基本知识.
- 应该在本地安装Composer,以便能够下载和安装第三方软件包。
目标
在本教程结束时, 你应该能够为你的系统建立一个资源管理器.
设置Laravel 9应用程序
Laravel是一个PHP框架,用于构建Web应用程序。它在开发者中是一个很受欢迎的选择,用于构建网络应用。
要在你的本地机器上安装Laravel, 你有多种选择.
- 使用官方的Laravel安装程序来安装Laravel.
- 使用 composer 软件包管理器.
让我们开始运行以下命令,使安装程序在我的项目根目录下可见。
export PATH="$PATH:$HOME/.config/composer/vendor/bin"
注意, 路径是相对于用户的主目录的, 这可能会根据你的安装设置而改变.
接下来,通过执行以下安装程序命令来安装资源管理器应用程序。
laravel new resource-manager
安装可能需要一些时间,这取决于你的互联网连接。一旦完成,cd 进入项目根目录并运行以下命令来启动应用程序:
php artisan serve
上述命令启动Laravel应用程序的默认端口为http://localhost:8000 。
需要注意的是, 上述端口只有在不使用的情况下才有效.
你可以通过运行下面的命令来改变这个端口:
php artisan serve --port=<PORT>
配置资源管理器包
现在我们的Laravel应用程序正在运行, 我们需要安装资源管理器包.
让我们先安装一个名为Spatie server monitor 的软件包.这个包将给我们提供所有的功能, 以确保我们可以运行资源扫描.
composer require spatie/laravel-server-monitor:^1.0
输出。
Discovered Package: laravel/sail
Discovered Package: laravel/sanctum
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Discovered Package: spatie/laravel-blink
Discovered Package: spatie/laravel-ignition
Discovered Package: spatie/laravel-server-monitor
Package manifest generated successfully.
...
一旦完成,新包将被添加到composer.json 文件上,如下图所示。
"spatie/laravel-server-monitor": "^1.0"
接下来,更新config/app.php 文件,包括以下一行。
'providers' => [
...
Spatie\ServerMonitor\ServerMonitorServiceProvider::class,
...
],
我们添加提供者阵列,以确保软件包被加载。
现在我们已经安装了软件包,我们需要发布资产。这可以通过运行以下命令来完成。
php artisan vendor:publish --all # to publish all the assets
# use this command if you want to publish only the assets for the given tag
php artisan vendor:publish --provider="Spatie\ServerMonitor\ServerMonitorServiceProvider" --tag="migrations"
成功后,将创建以下数据库表。
...
// hosts table
Schema::create('hosts', function (Blueprint $table) {
// unique identifier for the table
$table->increments('id');
// name of the host
$table->string('name');
//
$table->string('ssh_user')->nullable();
$table->integer('port')->nullable();
// ip address of the host
$table->string('ip')->nullable();
// custom properties for the host
$table->json('custom_properties')->nullable();
$table->timestamps();
});
上面的表将被用来存储我们将被监控的主机。
另一个创建的表是checks 表。这个表将被用来存储我们将在主机上运行的检查。
...
Schema::create('checks', function (Blueprint $table) {
// unique identifier for the table
$table->increments('id');
// host id
$table->integer('host_id')->unsigned();
// using host id as foreign key
$table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade');
// type
$table->string('type');
// status
$table->string('status')->nullable();
// is enabled
$table->boolean('enabled')->default(true);
// last run message
$table->text('last_run_message')->nullable();
// last run output
$table->json('last_run_output')->nullable();
// last time it ran
$table->timestamp('last_ran_at')->nullable();
// next time it will run
$table->integer('next_run_in_minutes')->nullable();
// notification
$table->timestamp('started_throttling_failing_notifications_at')->nullable();
// custom properties for the check
$table->json('custom_properties')->nullable();
// the check will be created when the host is created
$table->timestamps();
});
换句话说,hosts 将存储关于被监控的计算机或服务器的所有必要细节,而checks 表存储关于将在主机上运行的检查的信息。
通过上述命令,我们可以看到以下资产被发布在config/server-monitor.php 文件中。
<?php
return [
...
// the checks that can be performed by our system
'checks' => [
// diskspace memory check
'diskspace' => Spatie\ServerMonitor\CheckDefinitions\Diskspace::class,
// elasticsearch check
'elasticsearch' => Spatie\ServerMonitor\CheckDefinitions\Elasticsearch::class,
// Memcache checks
'memcached' => Spatie\ServerMonitor\CheckDefinitions\Memcached::class,
// mysql database checks
'mysql' => Spatie\ServerMonitor\CheckDefinitions\MySql::class,
],
...
];
在上述文件中,我们已经添加了以下检查。
- The
diskspace: 这将检查系统的磁盘空间。 - The
elasticsearch: 这将检查弹性搜索服务器。 - The
memcached: 这将检查memcached服务器。 mysql:这将检查mysql数据库。
添加控制器
随着服务器监控器设置的完成,现在让我们继续为我们的应用程序添加一些控制器。
控制器的目标是处理资源管理器的逻辑。
我们希望我们的控制器能够处理以下内容。
- 处理我们服务器上的
apache status检查。 - 检查数据库连接。
- 检查MySQL数据库。
- 检查我们的RAM状态/使用情况。
因此,我们需要为上述每项任务创建4个控制器。
我们创建4个控制器而不是1个有多个方法的控制器的原因是,所安装的包有一个接口,只需要一个方法。
运行下面的命令来添加控制器。
# add the controller for the apache status check
php artisan make:controller ApacheCheckerController
# add the controller for the database connection check
php artisan make:controller DatabaseCheckerController
# add the controller for the mysql database check
php artisan make:controller MySqlCheckerController
# add the controller for the ram check
php artisan make:controller RamCheckerController
接下来,打开ApacheCheckerController.php 文件,添加以下代码。
<?php
...
// import the
use Spatie\ServerMonitor\CheckDefinitions\CheckDefinition;
use Symfony\Component\Process\Process;
class ApacheCheckerController extends CheckDefinition
{
// use this command to check the status of Apache2 on your server
public $command = 'sudo systemctl status apache2';
// resolve the execution
public function resolve(Process $process)
{
// the output will contain the status if it;s active na running
if (str_contains($process->getOutput(), 'active (running)')) {
// if it;s running, then success
$this->check->succeed('is running');
return;
}
// if the check fails, then it;s not running
$this->check->fail('is not running');
}
}
在上面的控制器中,我们已经添加了以下内容。
- The
command: 这是检查Apache2状态的命令,将被执行。 resolve: 这是命令执行时将被调用的方法。
接下来,打开DatabaseCheckerController.php 文件,添加以下代码。
<?php
...
//import the checkDefinition class
use Spatie\ServerMonitor\CheckDefinitions\CheckDefinition;
use Symfony\Component\Process\Process;
class RamCheckerController extends CheckDefinition
{
public $command = "";
// use this method to calculate the RAM percentage
protected function getRAMUsagePercentage(): float
{
$ram = shell_exec("grep 'RAM ' /proc/stat | awk '{ramUsage=($2+$4)*100/($2+$4+$5)} END {print ramUsage}'");
return (float) $ram;
}
public function resolve(Process $process)
{
// assign the ram percentage
$ramPercentage = $this->getRAMUsagePercentage();
// get the exact usage
$ramUsage = round($ramPercentage, 2);
//init the message
$message = "My RAM usage at {$ramUsage}%";
//get the ram usage threshold
$ram_usage_threshold = config('server-monitor.cpu_usage_threshold');
// check for any failures of the RAM percentage against its usage threshold
if ($ramPercentage >= $ram_usage_threshold['fail']) {
$this->check->fail($message);
return;
}
// check for any warnings of the RAM percentage against its usage threshold
if ($ramPercentage >= $ram_usage_threshold['warning']) {
$this->check->warn($message);
return;
}
// otherwise if success, return the message
$this->check->succeed($message);
}
}
在上面的控制器中,我们已经添加了以下内容。
- The
command: 这是一个将被执行的命令,用于检查RAM的使用状况和剩余百分比。 - 解析`。这是命令执行时将被调用的方法。
- 在解析方法中,我们加入了以下内容。
getRAMUsagePercentage:这个方法将被用来计算RAM的使用百分比。- 然后将RAM使用量四舍五入到小数点后2位。
- 我们在检查中要显示的信息。
- 然后根据使用情况检查RAM使用阈值。
现在我们已经定义了控制器,接下来运行下面的命令,把远程主机添加到服务器监控中。
# add the remote hosts to the server monitor
php artisan server-monitor:add-hosts
输出。
Lets add a host!
What is the name of the host:
> section.io
Should a custom ssh user be used? (yes/no) [no]:
> yes
Which user?:
> admin
Should a custom port be used? (yes/no) [no]:
> 8080
Should a specific ip address be used? (yes/no) [no]:
> yes
Which ip address?:
> http://localhost:8080
Which checks should be performed? [<all checks>]:
[0] <all checks>
[1] diskspace
[2] elasticsearch
[3] memcached
[4] mysql
> 1
Host `section.io` added
根据主机的要求,更新上面的是或否的问题。
接下来,让我们继续,运行磁盘空间检查。
# run the diskspace check
php artisan server-monitor:run-checks
预期的输出。
Start running 1 checks...
section.io: performing check `diskspace`...
....
你会注意到上面的检查是针对diskspace ,因为我们在主机配置中选择了该检查。
总结
在本教程中, 我们学习了如何为你的Laravel系统建立一个资源管理器。
我们已经广泛地讨论了Laravel中需要监控的各种主要资源。在本教程中, 我们涵盖了以下内容:
- CPU使用率
- 数据库流量