Skip to content

Commit 52843dc

Browse files
committed
NixLog: avoid spawning tail and sh by tailing directly
In the common case we just read 50 lines so it seems wasteful to shell out. Also makes the decompression code a bit more readable.
1 parent b2b2d6e commit 52843dc

File tree

1 file changed

+33
-13
lines changed

1 file changed

+33
-13
lines changed

src/lib/Hydra/View/NixLog.pm

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,55 @@ use warnings;
55
use base qw/Catalyst::View/;
66
use Hydra::Helper::CatalystUtils;
77

8+
sub tail {
9+
my ($filehandle, $n) = @_;
10+
my @lines;
11+
my $line_count = 0;
12+
13+
while (my $line = <$filehandle>) {
14+
$lines[$line_count % $n] = $line;
15+
$line_count++;
16+
}
17+
18+
my $start = $line_count > $n ? $line_count % $n : 0;
19+
my $end = $line_count > $n ? $n : $line_count;
20+
21+
my $result = "";
22+
for my $i (0 .. $end - 1) {
23+
$result .= $lines[($start + $i) % $n];
24+
}
25+
return $result;
26+
}
27+
828
sub process {
929
my ($self, $c) = @_;
1030

1131
my $logPath = $c->stash->{logPath};
1232

1333
$c->response->content_type('text/plain; charset=utf-8');
1434

15-
my $fh = IO::Handle->new();
35+
my $logFh = IO::Handle->new();
1636

17-
my $tail = int($c->stash->{tail} // "0");
37+
my $tailLines = int($c->stash->{tail} // "0");
1838

1939
if ($logPath =~ /\.zst$/) {
20-
my $doTail = $tail ? "| tail -n '$tail'" : "";
21-
open($fh, "-|", "zstd -dc < '$logPath' $doTail") or die;
40+
open($logFh, "-|", "zstd", "-dc", $logPath) or die;
2241
} elsif ($logPath =~ /\.bz2$/) {
23-
my $doTail = $tail ? "| tail -n '$tail'" : "";
24-
open($fh, "-|", "bzip2 -dc < '$logPath' $doTail") or die;
42+
open($logFh, "-|", "bzip2", "-dc", $logPath) or die;
2543
} else {
26-
if ($tail) {
27-
open($fh, "-|", "tail -n '$tail' '$logPath'") or die;
28-
} else {
29-
open($fh, "<", $logPath) or die;
30-
}
44+
open($logFh, "<", $logPath) or die;
3145
}
32-
binmode($fh);
3346

3447
setCacheHeaders($c, 365 * 24 * 60 * 60) if $c->stash->{finished};
3548

36-
$c->response->body($fh);
49+
if ($tailLines > 0) {
50+
my $logEnd = tail($logFh, $tailLines);
51+
$c->response->body($logEnd);
52+
return 1;
53+
}
54+
55+
binmode($logFh);
56+
$c->response->body($logFh);
3757

3858
return 1;
3959
}

0 commit comments

Comments
 (0)