xbnz/mtr

MTR 的无框架包

0.1.2 2022-01-31 22:15 UTC

This package is auto-updated.

Last update: 2024-09-29 06:25:48 UTC


README

GitHub Workflow Status

PHP MTR

无框架异步 MTR 库

启动运行

需要此包

composer require xbnz/mtr

在你的项目中使用 MTR (Laravel)

// Optionally configure DI (Laravel example)

class AppServiceProvider extends Provider
{
    public function register()
    {
        $this->app->bind(MTR::class, function (Application $app) {
            return MTR::build(Config::get('services.mtr_options'), $app->make(LoggerInterface::class));
        });
    }
}

MTR 选项

// services.php
return [
    // ...
    'mtr_options' => new \Xbnz\Mtr\MtrOptionsConfigDto(...)
]

您不应禁用 'report wide' 或 'json' 选项。该包将停止工作。

批量或单个 IP 地址,异步执行

use Xbnz\Mtr;

public function __construct(private MTR $mtr)
{}

// Or without DI...

public function __construct()
{
    $this->mtr = Mtr::build(new MtrOptionsConfigDto(...), new Logger);
}


public function example()
{

    // Consider a high timeout value for large scans. 
    // Async threads above 50 might cause inaccuracies in RTT statistics.

    $results = $this->mtr->withIp('1.1.1.1', '8.8.8.8')->wrap($consoleTimeout, $concurrentProcesses);
    // OR
    $results = $this->mtr->withIp(...['1.1.1.1', '8.8.8.8'])->wrap($consoleTimeout, $concurrentProcesses);
    // OR
    $results = $this->mtr->withIp('1.1.1.1')->wrap($consoleTimeout, $concurrentProcesses);
    // OR
    $results = $this->mtr->withIp(995738574453)->wrap($consoleTimeout, $concurrentProcesses);
    // OR
    $results = $this->mtr->withIp('google.com')->wrap($consoleTimeout, $concurrentProcesses);
    // OR
    $results = $this->mtr->withIp(0x1294812)->wrap($consoleTimeout, $concurrentProcesses);
    
    
    Assert::containsOnlyInstancesOf(
        MtrResult::class,
        $results
    );
  
    /**
    * If last hop of MTR !== supplied IP, the target is dead. 
    * In most circumstances, you'd want to reject dead targets. 
    * You might still want to see the hops for a dead target, so the default policy is not to reject.
    */
    $aliveTargetHopPairs = $results
        ->reject(fn($result) => $result->targetDown()) 
        ->map(fn($result) => [$result->targetHost => $result->hops]);
        ->each(fn($targetWithHops) => Assert::containsOnlyInstancesOf(MtrHopDto::class, $targetWithHops));
    
    $aliveTargetHopPairs
        ->each(function ($hops, $ip) {
            if ($hops->last()->packetLoss > 5) {
                $this->logger->log("Target {$ip}, hop {$hops->last()->hopPositionCount} has {$hops->last()->packetLoss}% loss")
            }
        });
}

连接到 raw() 方法

raw() 方法将返回 MTR 的未处理结果集。这还将允许您连接到每个异步过程,这对于长时间运行的过程非常有用。

例如,您可能想跟踪每个处理的 IP 地址,如下所示。

public function handle(MTR $mtr)
{
    // Thousands of IPs
    $mtr->withIp('1.1.1.1/20') 
        ->raw(callable: function (ForkSerializableProcessDto $dto) {
            dump($dto->host . PHP_EOL);
        })
}