Kubernetes/PortForwardSession.pm

filter: Statementstmt 100% 87 / 87 Branchbran 80.5% 58 / 72 Conditioncond 37.0% 10 / 27 MC/DCmcdc 6.6% 1 / 15 Subroutinesub 100% 14 / 14 Podpod 88.8% 8 / 9 totaltotal 79.4% 178 / 224 CC 47 SCAR 21.7
CC
47
Cov
83%
close
12.7
_port_events
12.0
resize
10.8
CRAP 8.7
« Kubernetes.pm ↑ Summary Kubernetes/Controller.pm »
1 package Net::Async::Kubernetes::PortForwardSession;
2 # ABSTRACT: Duplex websocket session for pod port-forward, exec and attach
3 54 our $VERSION = '0.011';
4 54 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 54 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 54 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 20 ▶sub new {
Subroutine new: called CC=7 SCAR=20.4
Pod documented
9 20 my ($class, %args) = @_;
10 20 ▶ croak "ws_client required" unless $args{ws_client};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"ws_client"} 0 20 20
11 20 ▶ if (defined $args{ports}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"ports"}) 16 4 20
12 croak "ports must be a non-empty array reference"
13 16 ▶ unless ref($args{ports}) eq 'ARRAY' && @{$args{ports}};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args{"ports"} eq "ARRAY" and @{$args{"ports"};} 0 16 16
Condition33%1/3
ref $args{"ports"} eq "ARRAY" and @{$args{"ports"};}
!ll&&!rl&&r
0016
MC/DC0%0/2
ref $args{"ports"} eq "ARRAY" and @{$args{"ports"};}
ref $args{"ports"} eq "ARRAY" @{$args{"ports"};}
Truth table33%1/3
A and B
A= ref $args{"ports"} eq "ARRAY"B= @{$args{"ports"};}
ABresult
0X0
100
111
14 16 $args{ports} = [@{$args{ports}}];
15 16 my $i = 0;
16 16 for my $port (@{$args{ports}}) {
17 22 ▶ $args{_port_index}{$port} //= $i;
Condition33%1/3
$args{"_port_index"}{$port} //= $i
l!l&&r!l&&!r
0220
MC/DC0%0/2
$args{"_port_index"}{$port} //= $i
$args{"_port_index"}{$port} $i
Truth table33%1/3
A //= B
A= $args{"_port_index"}{$port}B= $i
ABresult
1X1
011
000
18 22 $i++;
19 }
20 }
21 20 return bless \%args, $class;
22 }
23  
24  
25 41 ▶sub ws_client { $_[0]->{ws_client} }
Subroutine ws_client: called CC=1 SCAR=0.0
Pod undocumented
26  
27 40 ▶sub is_port_forward { $_[0]->{ports} ? 1 : 0 }
Subroutine is_port_forward: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'ports'} ? : 39 1 40
28  
29  
30 2 ▶sub ports { $_[0]->{ports} ? [@{$_[0]->{ports}}] : undef }
Subroutine ports: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'ports'} ? : 1 1 2
31  
32  
33 # The events one incoming frame of a port-forward session stands for, after
34 # the two-byte port preamble every channel starts with is checked and
35 # stripped: ['data', $port, $bytes], ['port_error', $port, $message] or
36 # ['error', $message] (what Net::Async::Kubernetes hands to on_data,
37 # on_port_error and on_error). A channel whose preamble was wrong delivers
38 # nothing further.
39 38 ▶sub _port_events {
Subroutine _port_events: called CC=12 SCAR=24.9
40 38 my ($self, $channel, $payload) = @_;
41 38 my @ports = @{$self->{ports}};
42  
43 38 ▶ return ['error', 'port-forward frame on channel ' . $channel
Branch: 1 branch
BranchTrueFalseTotal
if $channel >= 2 * @ports 1 37 38
44 . ' but ' . scalar(@ports) . ' port(s) requested use channels 0 to '
45 . (2 * @ports - 1)]
46 if $channel >= 2 * @ports;
47  
48 37 my $port = $ports[int($channel / 2)];
49 37 my $is_err = $channel % 2;
50 37 ▶ my $what = 'channel ' . $channel . ' (' . ($is_err ? 'error' : 'data')
Branch: 1 branch
BranchTrueFalseTotal
$is_err ? : 12 25 37
51 . ' of port ' . $port . ')';
52  
53 37 my $state = $self->{_channel_state}{$channel};
54 37 ▶ unless ($state) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($state) 22 15 37
55 22 my $problem;
56 22 ▶ if (length($payload) != 2) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $payload != 2) { } 3 19 22
elsif ((my $got = unpack('v', $payload)) != $port) { } 2 17 19
57 3 ▶ $problem = length($payload) > 2
Branch: 1 branch
BranchTrueFalseTotal
length $payload > 2 ? : 2 1 3
58 ? 'first frame carries data after the port number'
59 : 'first frame is not a 2-byte port number';
60 3 $problem .= ' (' . length($payload) . ' bytes)';
61 } elsif ((my $got = unpack('v', $payload)) != $port) {
62 2 $problem = 'port preamble says ' . $got;
63 }
64 22 ▶ $self->{_channel_state}{$channel} = defined $problem ? 'broken' : 'open';
Branch: 1 branch
BranchTrueFalseTotal
defined $problem ? : 5 17 22
65 22 ▶ return defined $problem ? (['error', $what . ': ' . $problem]) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $problem ? : 5 17 22
66 }
67 15 ▶ return if $state eq 'broken';
Branch: 1 branch
BranchTrueFalseTotal
if $state eq "broken" 1 14 15
68 14 ▶ return unless length $payload;
Branch: 1 branch
BranchTrueFalseTotal
unless length $payload 0 14 14
69 14 ▶ return $is_err ? (['port_error', $port, $payload]) : (['data', $port, $payload]);
Branch: 1 branch
BranchTrueFalseTotal
$is_err ? : 3 11 14
70 }
71  
72 14 ▶sub write_port {
Subroutine write_port: called CC=4 SCAR=13.9
Pod documented
73 14 my ($self, $port, $payload) = @_;
74  
75 14 ▶ croak "write_port is only for port-forward sessions" unless $self->{ports};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ports"} 1 13 14
76 13 ▶ croak "port required for write_port" unless defined $port;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $port 1 12 13
77 12 my $i = $self->{_port_index}{$port};
78 12 ▶ croak "port '$port' is not forwarded by this session" unless defined $i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $i 1 11 12
79  
80 11 return $self->write_channel(2 * $i, $payload);
81 }
82  
83  
84 15 ▶sub write_channel {
Subroutine write_channel: called CC=7 SCAR=23.2
Pod documented
85 15 my ($self, $channel, $payload) = @_;
86  
87 15 ▶ croak "channel required for write_channel" unless defined $channel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $channel 0 15 15
88 15 ▶ croak "invalid channel '$channel' for write_channel"
Branch: 1 branch
BranchTrueFalseTotal
unless $channel =~ /^\d+$/ and $channel >= 0 and $channel <= 255 0 15 15
Condition33%2/6
$channel =~ /^\d+$/ and $channel >= 0 and $channel <= 255
!ll&&!rl&&r
0015
$channel =~ /^\d+$/ and $channel >= 0
!ll&&!rl&&r
0015
MC/DC0%0/3
$channel =~ /^\d+$/ and $channel >= 0 and $channel <= 255
$channel =~ /^\d+$/ $channel >= 0 $channel <= 255
Truth table25%1/4
A and B and C
A= $channel =~ /^\d+$/B= $channel >= 0C= $channel <= 255
ABCresult
0XX0
10X0
1100
1111
89 unless $channel =~ /^\d+$/ && $channel >= 0 && $channel <= 255;
90  
91 15 ▶ $payload = '' unless defined $payload;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload 0 15 15
92 15 ▶ croak "payload must be a plain string for write_channel" if ref($payload);
Branch: 1 branch
BranchTrueFalseTotal
if ref $payload 0 15 15
93  
94 15 return $self->ws_client->send_binary_frame(chr($channel) . $payload);
95 }
96  
97  
98 4 ▶sub write_stdin {
Subroutine write_stdin: called CC=2 SCAR=6.9
Pod documented
99 4 my ($self, $payload) = @_;
100 croak "write_stdin is not available on a port-forward session (use write_port)"
101 4 ▶ if $self->{ports};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ports"} 3 1 4
102 1 return $self->write_channel(0, $payload);
103 }
104  
105  
106 {
107 54 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
108 54 *write = \&write_channel;
109 54 *stdin = \&write_stdin;
110 }
111  
112 5 ▶sub resize {
Subroutine resize: called CC=10 SCAR=23.8
Pod documented
113 5 my ($self, %args) = @_;
114 5 ▶ croak "resize is not available on a port-forward session" if $self->{ports};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ports"} 2 3 5
115  
116 3 ▶ my $width = exists($args{width}) ? $args{width} : $args{cols};
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'width'} ? : 3 0 3
117 3 ▶ my $height = exists($args{height}) ? $args{height} : $args{rows};
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'height'} ? : 2 1 3
118  
119 3 ▶ croak "width required for resize" unless defined $width;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $width 0 3 3
120 3 ▶ croak "height required for resize" unless defined $height;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $height 1 2 3
121 2 ▶ croak "invalid width '$width' for resize"
Branch: 1 branch
BranchTrueFalseTotal
unless $width =~ /^\d+$/ and $width > 0 1 1 2
Condition66%2/3
$width =~ /^\d+$/ and $width > 0
!ll&&!rl&&r
011
MC/DC50%1/2
$width =~ /^\d+$/ and $width > 0
$width =~ /^\d+$/ $width > 0
Truth table66%2/3
A and B
A= $width =~ /^\d+$/B= $width > 0
ABresult
0X0
100
111
122 unless $width =~ /^\d+$/ && $width > 0;
123 1 ▶ croak "invalid height '$height' for resize"
Branch: 1 branch
BranchTrueFalseTotal
unless $height =~ /^\d+$/ and $height > 0 0 1 1
Condition33%1/3
$height =~ /^\d+$/ and $height > 0
!ll&&!rl&&r
001
MC/DC0%0/2
$height =~ /^\d+$/ and $height > 0
$height =~ /^\d+$/ $height > 0
Truth table33%1/3
A and B
A= $height =~ /^\d+$/B= $height > 0
ABresult
0X0
100
111
124 unless $height =~ /^\d+$/ && $height > 0;
125  
126 1 my $payload = sprintf('{"Width":%d,"Height":%d}', $width, $height);
127 1 return $self->write_channel(4, $payload);
128 }
129  
130  
131 8 ▶sub close {
Subroutine close: called CC=9 SCAR=25.4
Pod documented
132 8 my ($self, %args) = @_;
133 8 my $code = $args{code};
134 8 ▶ my $payload = exists $args{payload} ? $args{payload} : '';
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'payload'} ? : 1 7 8
135  
136 8 ▶ croak "payload must be a plain string for close" if ref($payload);
Branch: 1 branch
BranchTrueFalseTotal
if ref $payload 0 8 8
137 8 ▶ croak "invalid websocket close code '$code'"
Branch: 1 branch
BranchTrueFalseTotal
if defined $code and !($code =~ /^\d+$/) || $code < 1000 || $code > 4999 0 8 8
Condition33%3/9
defined $code and !($code =~ /^\d+$/) || $code < 1000 || $code > 4999
!ll&&!rl&&r
080
not $code =~ /^\d+$/ or $code < 1000 or $code > 4999
l!l&&r!l&&!r
008
not $code =~ /^\d+$/ or $code < 1000
l!l&&r!l&&!r
008
MC/DC0%0/4
defined $code and !($code =~ /^\d+$/) || $code < 1000 || $code > 4999
defined $code not $code =~ /^\d+$/ $code < 1000 $code > 4999
Truth table20%1/5
A and not(B) or C or D
A= defined $codeB= not $code =~ /^\d+$/C= $code < 1000D= $code > 4999
ABCDresult
0XXX0
10000
11XX1
101X1
10011
138 if defined($code) && ($code !~ /^\d+$/ || $code < 1000 || $code > 4999);
139  
140 8 ▶ my $close_payload = defined($code) ? pack('n', $code) . $payload : $payload;
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 8 0 8
141 8 my $ret = $self->ws_client->send_close_frame($close_payload);
142 8 ▶ $self->ws_client->close_when_empty if $self->ws_client->can('close_when_empty');
Branch: 1 branch
BranchTrueFalseTotal
if $self->ws_client->can("close_when_empty") 8 0 8
143 8 return $ret;
144 }
145  
146  
147 54 1;
148  
149 __END__
150  
151 =pod
152  
153 =encoding UTF-8
154  
155 =head1 NAME
156  
157 Net::Async::Kubernetes::PortForwardSession - Duplex websocket session for pod port-forward, exec and attach
158  
159 =head1 VERSION
160  
161 version 0.011
162  
163 =head1 SYNOPSIS
164  
165 my $session = $kube->exec('Pod', 'my-pod',
166 namespace => 'default',
167 command => ['sh'],
168 tty => 1,
169 on_frame => sub {
170 my ($channel, $payload) = @_;
171 print $payload if $channel == 1; # stdout
172 },
173 )->get;
174  
175 $session->write_stdin("id\n");
176 $session->resize(width => 120, height => 40);
177 $session->close(code => 1000);
178  
179 # port-forward: payload only, preamble stripped by the library
180 my $pf = $kube->port_forward('Pod', 'web',
181 ports => [8080],
182 on_data => sub { my ($session, $port, $bytes) = @_; print $bytes },
183 )->get;
184 $pf->write_port(8080, "GET / HTTP/1.0\r\n\r\n");
185  
186 =head1 DESCRIPTION
187  
188 A duplex session handle for the Kubernetes exec/attach/port-forward
189 websocket sub-protocol (C<v4.channel.k8s.io> by default). Every frame on the
190 wire carries a channel number as its first byte, identifying which logical
191 stream the rest of the frame belongs to. C<write_channel> is the primitive
192 that builds such a frame. There are two kinds of session, told apart by
193 L</is_port_forward>.
194  
195 B<Exec and attach> sessions have the channels stdin (0), stdout (1), stderr
196 (2), error/status (3) and TTY resize (4). C<write_stdin> and C<resize> are the
197 convenience wrappers over channels 0 and 4.
198  
199 B<Port-forward> sessions have a data and an error channel per forwarded port
200 (C<2 * $i> and C<2 * $i + 1>), each opened by a two-byte port-number frame.
201 C<write_port> writes to the data channel of a port; C<write_stdin> and
202 C<resize> croak. The library strips and checks the preamble and hands the
203 rest to the C<on_data> and C<on_port_error> callbacks of
204 L<Net::Async::Kubernetes/port_forward>.
205  
206 Callers do not normally construct this class themselves: it is what
207 L<Net::Async::Kubernetes/port_forward>, L<Net::Async::Kubernetes/exec>, and
208 L<Net::Async::Kubernetes/attach> resolve their returned C<Future> with, and
209 what they pass to an C<on_open> callback if one was given. Incoming frames
210 are not read through this object; they arrive via the callbacks passed to
211 those methods (C<on_frame> with raw C<($channel, $payload)> pairs).
212  
213 =head2 new
214  
215 my $session = Net::Async::Kubernetes::PortForwardSession->new(
216 ws_client => $ws_client,
217 );
218  
219 Wraps an already-connected websocket client (normally a
220 L<Net::Async::WebSocket::Client>) as a session. C<ws_client> is required.
221  
222 With C<ports> (an arrayref of the requested remote ports, in the order of the
223 port-forward request) the session is a I<port-forward session>: it knows the
224 channel layout of the port-forward sub-protocol and offers L</write_port>;
225 L</write_stdin> and L</resize> croak on it. Without C<ports> it is an
226 exec/attach session.
227  
228 Callers do not normally build a session this way: the C<Future> returned by
229 L<Net::Async::Kubernetes/port_forward>, L<Net::Async::Kubernetes/exec>, and
230 L<Net::Async::Kubernetes/attach> resolves to one, already bound to the open
231 connection, and it is what those methods pass to an C<on_open> callback.
232  
233 =head2 is_port_forward
234  
235 True for a session of L<Net::Async::Kubernetes/port_forward>, false for exec
236 and attach. The first kind has L</write_port> and refuses L</write_stdin> and
237 L</resize>; the second is the other way round.
238  
239 =head2 ports
240  
241 The remote ports of a port-forward session in request order, as a fresh
242 arrayref; channel C<2 * $i> and C<2 * $i + 1> belong to the C<$i>th of them.
243 C<undef> for an exec or attach session.
244  
245 =head2 write_port
246  
247 $session->write_port(8080, "GET / HTTP/1.1\r\nHost: x\r\n\r\n");
248  
249 Port-forward sessions only. Send C<$bytes> to the forwarded TCP connection of
250 remote C<$port>: one binary frame on the port's data channel, C<2 * $i> for
251 the C<$i>th requested port. It croaks on a port the session was not opened
252 for and on an exec/attach session.
253  
254 Returns the L<Future> from L</write_channel>.
255  
256 =head2 write_channel
257  
258 $session->write_channel(0, "id\n");
259  
260 Send C<$payload> as a single binary websocket frame on the given Kubernetes
261 stream C<$channel>, with the channel number prepended as the frame's first
262 byte (C<chr($channel) . $payload>). C<$channel> is required and must be an
263 integer between 0 and 255; C<$payload> defaults to the empty string.
264  
265 C<write_channel> itself does not know what any channel number means, it only
266 frames whatever it is given; the meaning comes from the Kubernetes
267 sub-protocol of the session.
268  
269 For an exec or attach session, 0 is stdin, 1 is stdout, 2 is stderr, 3
270 carries an error/status JSON document, and 4 carries TTY resize events (see
271 L</resize>).
272  
273 A port-forward session has a different layout: each requested port C<$i>
274 (counted from 0, in the order of C<ports>) owns two channels, C<2 * $i> for
275 data and C<2 * $i + 1> for errors, so with two ports channel 3 is the error
276 channel of the second one. The first frame the server sends on each of these
277 channels is the port number as two little-endian bytes, not payload. On a
278 port-forward session prefer L</write_port>, which finds the channel for a
279 port; C<write_channel> stays the raw primitive.
280  
281 C<on_frame>, passed to L<Net::Async::Kubernetes/exec> and friends, splits
282 incoming frames into C<($channel, $payload)> the same way in reverse; it
283 does not interpret the channel number and, on a port-forward session, does
284 not strip the preamble (C<on_data> and C<on_port_error> of
285 L<Net::Async::Kubernetes/port_forward> do).
286  
287 Returns the L<Future> from the underlying C<ws_client>'s
288 C<send_binary_frame> - an L<IO::Async::Stream> write-future that completes
289 with no value once the frame has been flushed to the connection.
290  
291 Aliased as C<write>.
292  
293 =head2 write_stdin
294  
295 $session->write_stdin("id\n");
296  
297 Shortcut for C<< $session->write_channel(0, $payload) >> - writes to channel
298 0, the stdin stream of an exec or attach session's remote process. It
299 croaks on a port-forward session, where channel 0 is the data channel of the
300 first port, not stdin; use L</write_port> there.
301  
302 Returns the L<Future> from the underlying C<write_channel> call.
303  
304 Aliased as C<stdin>.
305  
306 =head2 resize
307  
308 $session->resize(width => 120, height => 40);
309 $session->resize(cols => 120, rows => 40); # cols/rows are accepted too
310  
311 Send a TTY resize event on channel 4, as a C<{"Width":$width,"Height":$height}>
312 JSON payload. C<width> and C<height> (or their C<cols>/C<rows> aliases) are
313 required and must be positive integers. Only meaningful for a session opened
314 with C<tty =E<gt> 1>. It croaks on a port-forward session, where channel 4 is
315 the data channel of the third port.
316  
317 Returns the L<Future> from the underlying C<write_channel> call.
318  
319 =head2 close
320  
321 $session->close(code => 1000, payload => 'bye');
322 $session->close; # close frame with no code
323  
324 Send a websocket close frame, ending the session. C<code>, if given, must be
325 a websocket close code between 1000 and 4999; it is packed as a 16-bit
326 big-endian prefix (C<pack('n', $code)>) ahead of C<payload>, which defaults
327 to the empty string. Once the close frame is sent, the underlying transport
328 is also asked to close the connection once its write buffer drains
329 (C<close_when_empty>), if the transport supports that method.
330  
331 Returns the L<Future> from the underlying C<ws_client>'s C<send_close_frame>
332 - an L<IO::Async::Stream> write-future that completes with no value once the
333 close frame has been flushed to the connection.
334  
335 =head1 SEE ALSO
336  
337 L<Net::Async::Kubernetes>, L<Net::Async::WebSocket::Client>,
338 L<IO::Async::Stream>
339  
340 =head1 SUPPORT
341  
342 =head2 Issues
343  
344 Please report bugs and feature requests on GitHub at
345 L<https://github.com/Getty/p5-net-async-kubernetes/issues>.
346  
347 =head2 IRC
348  
349 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
350  
351 =head1 CONTRIBUTING
352  
353 Contributions are welcome! Please fork the repository and submit a pull request.
354  
355 =head1 AUTHOR
356  
357 Torsten Raudssus <torsten@raudssus.de>
358  
359 =head1 COPYRIGHT AND LICENSE
360  
361 This software is copyright (c) 2026 by Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>.
362  
363 This is free software; you can redistribute it and/or modify it under
364 the same terms as the Perl 5 programming language system itself.
365  
366 =cut
« Kubernetes.pm ↑ Summary Kubernetes/Controller.pm »