#feature: add Jenkins deploy monitor & log clean task
This commit is contained in:
97
app/Clients/JenkinsClient.php
Normal file
97
app/Clients/JenkinsClient.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Clients;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class JenkinsClient
|
||||
{
|
||||
private ?string $host;
|
||||
private ?string $username;
|
||||
private ?string $apiToken;
|
||||
private int $timeout;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$config = config('jenkins', []);
|
||||
$this->host = rtrim($config['host'] ?? '', '/');
|
||||
$this->username = $config['username'] ?? null;
|
||||
$this->apiToken = $config['api_token'] ?? null;
|
||||
$this->timeout = $config['timeout'] ?? 30;
|
||||
}
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return !empty($this->host) && !empty($this->username) && !empty($this->apiToken);
|
||||
}
|
||||
|
||||
public function getJobInfo(string $jobName): ?array
|
||||
{
|
||||
return $this->request("/job/{$jobName}/api/json");
|
||||
}
|
||||
|
||||
public function getBuildInfo(string $jobName, int $buildNumber): ?array
|
||||
{
|
||||
return $this->request("/job/{$jobName}/{$buildNumber}/api/json");
|
||||
}
|
||||
|
||||
public function getLastBuild(string $jobName): ?array
|
||||
{
|
||||
return $this->request("/job/{$jobName}/lastBuild/api/json");
|
||||
}
|
||||
|
||||
public function getBuilds(string $jobName, int $limit = 10): array
|
||||
{
|
||||
$jobInfo = $this->getJobInfo($jobName);
|
||||
if (!$jobInfo || empty($jobInfo['builds'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$builds = array_slice($jobInfo['builds'], 0, $limit);
|
||||
$result = [];
|
||||
|
||||
foreach ($builds as $build) {
|
||||
$buildInfo = $this->getBuildInfo($jobName, $build['number']);
|
||||
if ($buildInfo) {
|
||||
$result[] = $buildInfo;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function request(string $path): ?array
|
||||
{
|
||||
if (!$this->isConfigured()) {
|
||||
Log::warning('Jenkins client is not configured');
|
||||
return null;
|
||||
}
|
||||
|
||||
$url = $this->host . $path;
|
||||
|
||||
try {
|
||||
$response = Http::timeout($this->timeout)
|
||||
->withBasicAuth($this->username, $this->apiToken)
|
||||
->get($url);
|
||||
|
||||
if ($response->successful()) {
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
Log::warning('Jenkins API request failed', [
|
||||
'url' => $url,
|
||||
'status' => $response->status(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('Jenkins API request error', [
|
||||
'url' => $url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user