Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions app/Actions/Server/ClearServiceLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace App\Actions\Server;

use App\DTOs\ServiceLog;
use App\Models\Server;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Throwable;

class ClearServiceLog
{
/**
* @param array<string, mixed> $input
*
* @throws Throwable
* @throws ValidationException
*/
public function run(Server $server, array $input): void
{
$data = Validator::make($input, [
'key' => ['required', 'string', 'max:200'],
])->validate();

$log = app(GetServiceLogs::class)->resolve($server, $data['key']);
abort_if($log === null, 404);

if ($log->source !== ServiceLog::SOURCE_FILE) {
throw ValidationException::withMessages(['key' => 'Journal logs cannot be cleared.']);
}

$server->os()->clearFile($log->target);
}
}
76 changes: 76 additions & 0 deletions app/Actions/Server/DownloadServiceLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

namespace App\Actions\Server;

use App\DTOs\ServiceLog;
use App\Models\Server;
use App\SSH\OS\OS;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;

class DownloadServiceLog
{
/**
* @param array<string, mixed> $input
*
* @throws Throwable
* @throws ValidationException
*/
public function run(Server $server, array $input): StreamedResponse
{
$data = Validator::make($input, [
'key' => ['required', 'string', 'max:200'],
])->validate();

$log = app(GetServiceLogs::class)->resolve($server, $data['key']);
abort_if($log === null, 404);

$downloadName = $log->source === ServiceLog::SOURCE_JOURNAL
? Str::slug($log->key).'.log'
: str($log->target)->afterLast('/')->toString();

$tmpName = $server->id.'-'.now()->timestamp.'-'.Str::random(8).'-'.Str::slug($log->key).'.log';
$tmpPath = Storage::disk('local')->path($tmpName);

$remoteTmp = '/tmp/vito-'.Str::random(12).'.log';
try {
if ($log->source === ServiceLog::SOURCE_JOURNAL) {
$server->ssh()->exec(view('ssh.os.journal-dump', [
'unit' => $log->target,
'path' => $remoteTmp,
]));
} else {
$output = $server->ssh()->exec(view('ssh.os.copy-as-user', [
'source' => $log->target,
'dest' => $remoteTmp,
]));
abort_if(
trim($output) === OS::FILE_NOT_FOUND,
404,
'The log file does not exist on the server.'
);
}
$server->ssh()->download($tmpPath, $remoteTmp);
} finally {
try {
$server->os()->deleteFile($remoteTmp);
} catch (Throwable) {
}
}

dispatch(function () use ($tmpPath): void {
if (File::exists($tmpPath)) {
File::delete($tmpPath);
}
})
->delay(now()->addMinutes(5))
->onQueue('default');

return Storage::disk('local')->download($tmpName, $downloadName);
}
}
57 changes: 57 additions & 0 deletions app/Actions/Server/GetServiceLogs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace App\Actions\Server;

use App\DTOs\ServiceLog;
use App\Enums\ServiceStatus;
use App\Models\Server;
use App\Services\HasLogs;

class GetServiceLogs
{
/**
* @return array<int, ServiceLog>
*/
public function handle(Server $server): array
{
$logs = [];

$server->loadMissing('sites');

$services = $server->services()
->where('status', ServiceStatus::READY)
->get();

foreach ($services as $service) {
$service->setRelation('server', $server);
$handler = $service->handler();
if (! $handler instanceof HasLogs) {
continue;
}
foreach ($handler->logs() as $log) {
$logs[] = $log;
}
}

$logs[] = new ServiceLog(
key: 'system:sshd',
serviceLabel: 'System',
label: 'SSH daemon journal',
source: ServiceLog::SOURCE_JOURNAL,
target: 'ssh.service',
);

return $logs;
}

public function resolve(Server $server, string $key): ?ServiceLog
{
foreach ($this->handle($server) as $log) {
if ($log->key === $key) {
return $log;
}
}

return null;
}
}
64 changes: 64 additions & 0 deletions app/Actions/Server/ReadServiceLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace App\Actions\Server;

use App\DTOs\ServiceLog;
use App\Exceptions\SSHError;
use App\Models\Server;
use App\SSH\OS\OS;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class ReadServiceLog
{
/**
* @param array<string, mixed> $input
* @return array{content: string, display_target: string, source: string}
*
* @throws SSHError
* @throws ValidationException
*/
public function run(Server $server, array $input): array
{
$data = Validator::make($input, [
'key' => ['required', 'string', 'max:200'],
'lines' => ['nullable', 'integer', 'min:50', 'max:2000'],
'search' => ['nullable', 'string', 'max:200', 'regex:/^[^\x00\r\n]*$/'],
])->validate();

$log = app(GetServiceLogs::class)->resolve($server, $data['key']);
abort_if($log === null, 404);

$lines = (int) ($data['lines'] ?? 100);
$search = $data['search'] ?? null;
$hasSearch = $search !== null && $search !== '';

if ($log->source === ServiceLog::SOURCE_JOURNAL) {
$content = $server->ssh()->exec(view('ssh.os.journal-read', [
'unit' => $log->target,
'lines' => $lines,
'search' => $hasSearch ? $search : null,
]));
} elseif ($hasSearch) {
$content = $server->ssh()->exec(view('ssh.os.grep', [
'path' => $log->target,
'term' => $search,
'lines' => $lines,
]));
} else {
$content = $server->os()->tail($log->target, $lines);
}

abort_if(
$log->source === ServiceLog::SOURCE_FILE && trim($content) === OS::FILE_NOT_FOUND,
404,
'The log file does not exist on the server.'
);

return [
'content' => $content,
'display_target' => $log->displayTarget(),
'source' => $log->source,
];
}
}
27 changes: 27 additions & 0 deletions app/DTOs/ServiceLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\DTOs;

final class ServiceLog
{
public const SOURCE_FILE = 'file';

public const SOURCE_JOURNAL = 'journal';

public function __construct(
public string $key,
public string $serviceLabel,
public string $label,
public string $source,
public string $target,
) {}

public function displayTarget(): string
{
if ($this->source === self::SOURCE_JOURNAL) {
return 'journal: '.$this->target;
}

return $this->target;
}
}
58 changes: 57 additions & 1 deletion app/Http/Controllers/ServerLogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@

namespace App\Http\Controllers;

use App\Actions\Server\ClearServiceLog;
use App\Actions\Server\DownloadServiceLog;
use App\Actions\Server\GetServiceLogs;
use App\Actions\Server\ReadServiceLog;
use App\Actions\ServerLog\CreateLog;
use App\Actions\ServerLog\UpdateLog;
use App\DTOs\ServiceLog;
use App\Helpers\QueryBuilder;
use App\Http\Resources\ServerLogResource;
use App\Models\Server;
use App\Models\ServerLog;
use App\Models\Site;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
Expand Down Expand Up @@ -50,7 +56,7 @@ public function remote(Server $server): Response
$this->authorize('viewAny', [ServerLog::class, $server]);

return Inertia::render('server-logs/index', [
'title' => 'Remote logs',
'title' => 'Custom logs',
'logs' => ServerLogResource::collection($server->logs()->where('is_remote', 1)->latest()->simplePaginate(config('web.pagination_size'))),
'remote' => true,
]);
Expand All @@ -69,6 +75,56 @@ public function json(Request $request, Server $server, ?Site $site = null): Reso
return ServerLogResource::collection($logs);
}

#[Get('/services', name: 'logs.services')]
public function services(Server $server): Response
{
$this->authorize('viewAny', [ServerLog::class, $server]);

$catalogue = array_map(
fn (ServiceLog $log): array => [
'key' => $log->key,
'service_label' => $log->serviceLabel,
'label' => $log->label,
'display_target' => $log->displayTarget(),
'source' => $log->source,
],
app(GetServiceLogs::class)->handle($server),
);

return Inertia::render('server-logs/services', [
'title' => 'Service logs',
'catalogue' => $catalogue,
]);
}

#[Post('/services/read', name: 'logs.services.read')]
public function readServiceLog(Request $request, Server $server): JsonResponse
{
$this->authorize('viewAny', [ServerLog::class, $server]);

return response()->json(
app(ReadServiceLog::class)->run($server, $request->only('key', 'lines', 'search')),
);
}

#[Get('/services/download', name: 'logs.services.download')]
public function downloadServiceLog(Request $request, Server $server): StreamedResponse
{
$this->authorize('viewAny', [ServerLog::class, $server]);

return app(DownloadServiceLog::class)->run($server, $request->only('key'));
}

#[Post('/services/clear', name: 'logs.services.clear')]
public function clearServiceLog(Request $request, Server $server): RedirectResponse
{
$this->authorize('deleteMany', [ServerLog::class, $server]);

app(ClearServiceLog::class)->run($server, $request->only('key'));

return back()->with('success', 'Log cleared successfully');
}

#[Get('/{log}', name: 'logs.show')]
public function show(Server $server, ServerLog $log): string
{
Expand Down
5 changes: 4 additions & 1 deletion app/Models/ServerLog.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\DTOs\SocketEventDTO;
use App\Events\SocketEvent;
use App\Http\Resources\ServerLogResource;
use App\SSH\OS\OS;
use Database\Factories\ServerLogFactory;
use Exception;
use Illuminate\Database\Eloquent\Builder;
Expand Down Expand Up @@ -169,7 +170,9 @@ public function write(string $buf): void
public function getContent(?int $lines = null): ?string
{
if ($this->is_remote) {
return $this->server->os()->tail($this->name, $lines ?? 150);
$content = $this->server->os()->tail($this->name, $lines ?? 150);

return trim($content) === OS::FILE_NOT_FOUND ? "Log file doesn't exist or is empty!" : $content;
}

if (Storage::disk($this->disk)->exists($this->name)) {
Expand Down
2 changes: 2 additions & 0 deletions app/SSH/OS/OS.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

class OS
{
public const FILE_NOT_FOUND = 'VITO_NO_FILE';

private const SHELL_IDENTIFIER = '/^[A-Za-z_][A-Za-z0-9_]*$/';

public function __construct(protected Server $server) {}
Expand Down
Loading
Loading