Kubernetes.pm

filter: Statementstmt 97.0% 933 / 961 Branchbran 87.3% 505 / 578 Conditioncond 64.7% 154 / 238 MC/DCmcdc 43.2% 58 / 134 Subroutinesub 96.3% 156 / 162 Podpod 100% 32 / 32 totaltotal 87.3% 1838 / 2105 CC 391 SCAR 22.8
CC
391
Cov
90%
exec
24.0
cp_to_pod
21.8
__ANON__
20.0
CRAP 9.8
« Kubernetes/Watcher.pm ↑ Summary Kubernetes/PortForwardSession.pm »
1 package Net::Async::Kubernetes;
2 # ABSTRACT: Async Kubernetes client for IO::Async
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 parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 54 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 54 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 54 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 54 ▶use File::Temp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 54 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 54 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 54 ▶use Protocol::WebSocket::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 54 ▶use Kubernetes::REST;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 54 ▶use Kubernetes::REST::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 54 ▶use Kubernetes::REST::AuthToken;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 54 ▶use Kubernetes::REST::HTTPRequest;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 54 ▶use Kubernetes::REST::HTTPResponse;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 54 ▶use Kubernetes::REST::WatchEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 54 ▶use Kubernetes::REST::LogEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 54 ▶use Net::Async::Kubernetes::PortForwardSession;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 54 ▶use Net::Async::Kubernetes::PortForwardListener;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 54 ▶use Net::Async::Kubernetes::Watcher;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 54 ▶use Net::Async::Kubernetes::Controller;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 345 ▶sub configure {
Subroutine configure: called CC=19 SCAR=29.5
Pod documented
28 345 my ($self, %params) = @_;
29  
30 345 ▶ if (exists $params{kubeconfig}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"kubeconfig"}) 4 341 345
31 4 $self->{kubeconfig} = delete $params{kubeconfig};
32 }
33 345 ▶ if (exists $params{context}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"context"}) 4 341 345
34 4 $self->{context} = delete $params{context};
35 }
36 345 ▶ if (exists $params{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"server"}) 336 9 345
37 336 my $val = delete $params{server};
38 336 ▶ $self->{server} = (blessed($val) && $val->isa('Kubernetes::REST::Server'))
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($val) && $val->isa('Kubernetes::REST::Server') ? : 6 330 336
Condition66%2/3
builtin::blessed($val) and $val->isa("Kubernetes::REST::Server")
!ll&&!rl&&r
33006
MC/DC50%1/2
builtin::blessed($val) and $val->isa("Kubernetes::REST::Server")
builtin::blessed($val) $val->isa("Kubernetes::REST::Server")
Truth table66%2/3
A and B
A= builtin::blessed($val)B= $val->isa("Kubernetes::REST::Server")
ABresult
0X0
100
111
39 ? $val
40 : Kubernetes::REST::Server->new($val);
41 }
42 345 ▶ if (exists $params{credentials}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"credentials"}) 336 9 345
43 336 my $val = delete $params{credentials};
44 336 ▶ if (blessed($val) && $val->can('token')) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($val) and $val->can('token')) { } 6 330 336
elsif (ref $val eq 'HASH') { } 329 1 330
Condition66%2/3
builtin::blessed($val) and $val->can("token")
!ll&&!rl&&r
33006
MC/DC50%1/2
builtin::blessed($val) and $val->can("token")
builtin::blessed($val) $val->can("token")
Truth table66%2/3
A and B
A= builtin::blessed($val)B= $val->can("token")
ABresult
0X0
100
111
45 6 $self->{credentials} = $val;
46 } elsif (ref($val) eq 'HASH') {
47 329 $self->{credentials} = Kubernetes::REST::AuthToken->new($val);
48 } else {
49 1 $self->{credentials} = $val;
50 }
51 }
52 345 ▶ if (exists $params{resource_map}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"resource_map"}) 18 327 345
53 18 $self->{resource_map} = delete $params{resource_map};
54 }
55 345 ▶ if (exists $params{resource_map_from_cluster}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"resource_map_from_cluster"}) 325 20 345
56 325 $self->{resource_map_from_cluster} = delete $params{resource_map_from_cluster};
57 }
58 345 ▶ if (exists $params{with}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"with"}) 1 344 345
59 1 $self->{with} = delete $params{with};
60 }
61  
62 # Resolve server/credentials via Kubeconfig (handles kubeconfig files
63 # and in-cluster service account auto-detection)
64 345 ▶ if (!$self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"server"}) 9 336 345
65 9 require Kubernetes::REST::Kubeconfig;
66 my $kc = Kubernetes::REST::Kubeconfig->new(
67 ($self->{kubeconfig} ? (kubeconfig_path => $self->{kubeconfig}) : ()),
68 9 ▶ ($self->{context} ? (context_name => $self->{context}) : ()),
Branch: 2 branches
BranchTrueFalseTotal
$self->{'kubeconfig'} ? : 4 5 9
$self->{'context'} ? : 3 6 9
69 );
70 9 ▶ if ($self->{kubeconfig} || $self->{context}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'kubeconfig'} or $self->{'context'}) { } 7 2 9
elsif (my $api = eval { do { $kc->api } }) { } 0 2 2
Condition100%3/3
$self->{"kubeconfig"} or $self->{"context"}
l!l&&r!l&&!r
432
MC/DC100%2/2
$self->{"kubeconfig"} or $self->{"context"}
$self->{"kubeconfig"} $self->{"context"}
Truth table100%3/3
A or B
A= $self->{"kubeconfig"}B= $self->{"context"}
ABresult
1X1
011
000
71 # Explicit kubeconfig or context — must resolve or croak with the
72 # reason; swallowed, it would only resurface as "server or
73 # kubeconfig required" on first use.
74 7 my $api = $kc->api;
75 4 $self->{server} = $api->server;
76 4 $self->{credentials} = $api->credentials;
77 2 } elsif (my $api = eval { $kc->api }) {
78 # Auto-detect: kubeconfig default path or in-cluster
79 0 $self->{server} = $api->server;
80 0 $self->{credentials} = $api->credentials;
81 }
82 }
83  
84 342 $self->SUPER::configure(%params);
85 }
86  
87  
88 # Accessors
89 1 ▶sub kubeconfig { $_[0]->{kubeconfig} }
Subroutine kubeconfig: called CC=1 SCAR=0.0
Pod documented
90  
91  
92 2 ▶sub context { $_[0]->{context} }
Subroutine context: called CC=1 SCAR=0.0
Pod documented
93  
94  
95 317 ▶sub resource_map { $_[0]->{resource_map} }
Subroutine resource_map: called CC=1 SCAR=0.0
Pod documented
96  
97  
98 321 ▶sub resource_map_from_cluster { $_[0]->{resource_map_from_cluster} // 0 }
Subroutine resource_map_from_cluster: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"resource_map_from_cluster"} // 0
l!l
3174
MC/DC100%1/1
$_[0]{"resource_map_from_cluster"} // 0
$_[0]{"resource_map_from_cluster"}
Truth table100%2/2
A
A= $_[0]{"resource_map_from_cluster"}
Aresult
11
00
99  
100  
101 300 ▶sub with { $_[0]->{with} // [] }
Subroutine with: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
$_[0]{"with"} // []
l!l
2298
MC/DC100%1/1
$_[0]{"with"} // []
$_[0]{"with"}
Truth table100%2/2
A
A= $_[0]{"with"}
Aresult
11
00
102  
103  
104 347 ▶sub server {
Subroutine server: called CC=2 SCAR=7.1
Pod documented
105 347 my ($self) = @_;
106 347 ▶ $self->{server} // croak "server or kubeconfig required";
Condition66%2/3
$self->{"server"} // croak("server or kubeconfig required")
l!l&&r!l&&!r
34520
MC/DC0%0/2
$self->{"server"} // croak("server or kubeconfig required")
$self->{"server"} croak("server or kubeconfig required")
Truth table33%1/3
A // B
A= $self->{"server"}B= croak("server or kubeconfig required")
ABresult
1X1
011
000
107 }
108  
109  
110 320 ▶sub credentials {
Subroutine credentials: called CC=2 SCAR=7.1
Pod documented
111 320 my ($self) = @_;
112 320 ▶ $self->{credentials} // croak "credentials or kubeconfig required";
Condition66%2/3
$self->{"credentials"} // croak("credentials or kubeconfig required")
l!l&&r!l&&!r
31910
MC/DC0%0/2
$self->{"credentials"} // croak("credentials or kubeconfig required")
$self->{"credentials"} croak("credentials or kubeconfig required")
Truth table33%1/3
A // B
A= $self->{"credentials"}B= croak("credentials or kubeconfig required")
ABresult
1X1
011
000
113 }
114  
115  
116 3778 ▶sub rest {
Subroutine rest: called CC=3 SCAR=11.1
Pod documented
117 3778 my ($self) = @_;
118 3778 ▶ $self->{_rest} //= Kubernetes::REST->new(
Branch: 1 branch
BranchTrueFalseTotal
$self->resource_map ? : 17 281 298
Condition66%2/3
$self->{"_rest"} //= "Kubernetes::REST"->new("server", $self->server, "credentials", $self->credentials, "resource_map_from_cluster", $self->resource_map_from_cluster, $self->resource_map ? ("resource_map", $self->resource_map) : (), "with", $self->with)
l!l&&r!l&&!r
34802980
MC/DC0%0/2
$self->{"_rest"} //= "Kubernetes::REST"->new("server", $self->server, "credentials", $self->credentials, "resource_map_from_cluster", $self->resource_map_from_cluster, $self->resource_map ? ("resource_map", $self->resource_map) : (), "with", $self->with)
$self->{"_rest"} "Kubernetes::REST"->new("server", $self->server, "credentials", $self->credentials, "resource_map_from_cluster", $self->resource_map_from_cluster, $self->resource_map ? ("resource_map", $self->resource_map) : (), "with", $self->with)
Truth table66%2/3
A //= B
A= $self->{"_rest"}B= "Kubernetes::REST"->new("server", $self->server, "credentials", $self->credentials, "resource_map_from_cluster", $self->resource_map_from_cluster, $self->resource_map ? ("resource_map", $self->resource_map) : (), "with", $self->with)
ABresult
1X1
011
000
119 server => $self->server,
120 credentials => $self->credentials,
121 resource_map_from_cluster => $self->resource_map_from_cluster,
122 ($self->resource_map ? (resource_map => $self->resource_map) : ()),
123 with => $self->with,
124 );
125 }
126  
127  
128 # Lazy internal Kubernetes::REST for request building + response processing
129 3984 ▶sub _rest { $_[0]->rest }
Subroutine _rest: called CC=1 SCAR=0.0
130  
131 72 ▶sub new_object {
Subroutine new_object: called CC=1 SCAR=0.0
Pod documented
132 72 my ($self, @args) = @_;
133 72 return $self->rest->new_object(@args);
134 }
135  
136  
137 # Lazy Net::Async::HTTP instance
138 46 ▶sub _http {
Subroutine _http: called CC=2 SCAR=6.9
139 46 my ($self) = @_;
140 46 ▶ unless ($self->{_http}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_http"}) 27 19 46
141 27 require Net::Async::HTTP;
142 27 $self->{_http} = Net::Async::HTTP->new(
143 user_agent => 'Net::Async::Kubernetes Perl Client',
144 max_connections_per_host => 0,
145 );
146 }
147 46 return $self->{_http};
148 }
149  
150 # SSL options derived from server config, passed to every HTTP request
151 43 ▶sub _ssl_options {
Subroutine _ssl_options: called CC=12 SCAR=24.9
152 43 my ($self) = @_;
153 43 ▶ return @{$self->{_ssl_options}} if $self->{_ssl_options};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_ssl_options"} 18 25 43
154  
155 25 my $server = $self->server;
156 25 my @opts;
157  
158 25 ▶ if ($server->ssl_verify_server) {
Branch: 1 branch
BranchTrueFalseTotal
if ($server->ssl_verify_server) { } 24 1 25
159 24 push @opts, SSL_verify_mode => SSL_VERIFY_PEER;
160 } else {
161 1 push @opts, SSL_verify_mode => SSL_VERIFY_NONE;
162 }
163  
164 25 ▶ push @opts, SSL_ca_file => $server->ssl_ca_file if $server->ssl_ca_file;
Branch: 1 branch
BranchTrueFalseTotal
if $server->ssl_ca_file 3 22 25
165 25 ▶ push @opts, SSL_cert_file => $server->ssl_cert_file if $server->ssl_cert_file;
Branch: 1 branch
BranchTrueFalseTotal
if $server->ssl_cert_file 1 24 25
166 25 ▶ push @opts, SSL_key_file => $server->ssl_key_file if $server->ssl_key_file;
Branch: 1 branch
BranchTrueFalseTotal
if $server->ssl_key_file 1 24 25
167 25 my $ca_pem = $server->ssl_ca_pem;
168 25 ▶ if (defined $ca_pem && length $ca_pem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ca_pem and length $ca_pem) 3 22 25
Condition66%2/3
defined $ca_pem and length $ca_pem
!ll&&!rl&&r
2203
MC/DC50%1/2
defined $ca_pem and length $ca_pem
defined $ca_pem length $ca_pem
Truth table66%2/3
A and B
A= defined $ca_pemB= length $ca_pem
ABresult
0X0
100
111
169 3 push @opts, SSL_ca_file => $self->_materialize_ssl_pem(ca => $ca_pem);
170 }
171 25 my $cert_pem = $server->ssl_cert_pem;
172 25 ▶ if (defined $cert_pem && length $cert_pem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cert_pem and length $cert_pem) 3 22 25
Condition66%2/3
defined $cert_pem and length $cert_pem
!ll&&!rl&&r
2203
MC/DC50%1/2
defined $cert_pem and length $cert_pem
defined $cert_pem length $cert_pem
Truth table66%2/3
A and B
A= defined $cert_pemB= length $cert_pem
ABresult
0X0
100
111
173 3 push @opts, SSL_cert_file => $self->_materialize_ssl_pem(cert => $cert_pem);
174 }
175 25 my $key_pem = $server->ssl_key_pem;
176 25 ▶ if (defined $key_pem && length $key_pem) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key_pem and length $key_pem) 3 22 25
Condition66%2/3
defined $key_pem and length $key_pem
!ll&&!rl&&r
2203
MC/DC50%1/2
defined $key_pem and length $key_pem
defined $key_pem length $key_pem
Truth table66%2/3
A and B
A= defined $key_pemB= length $key_pem
ABresult
0X0
100
111
177 3 push @opts, SSL_key_file => $self->_materialize_ssl_pem(key => $key_pem);
178 }
179  
180 25 $self->{_ssl_options} = \@opts;
181 25 return @opts;
182 }
183  
184 9 ▶sub _materialize_ssl_pem {
Subroutine _materialize_ssl_pem: called CC=2 SCAR=6.9
185 9 my ($self, $kind, $pem) = @_;
186  
187 9 my $fh = File::Temp->new(
188 SUFFIX => ".$kind.pem",
189 UNLINK => 1,
190 );
191 9 print {$fh} $pem;
192 9 close $fh;
193  
194 9 ▶ push @{ $self->{_ssl_tempfiles} ||= [] }, $fh;
Condition100%2/2
$self->{"_ssl_tempfiles"} ||= []
l!l
63
MC/DC100%1/1
$self->{"_ssl_tempfiles"} ||= []
$self->{"_ssl_tempfiles"}
Truth table100%2/2
A
A= $self->{"_ssl_tempfiles"}
Aresult
11
00
195 9 return $fh->filename;
196 }
197  
198 # IO::K8s::expand_class fails closed: an unknown, malformed or mismatched
199 # apiVersion yields undef instead of a bare-name guess. Passing that undef on to
200 # build_path dies with "argument is not a module name", naming neither the
201 # resource nor the reason, so _resolve_class reports it with this.
202 47 ▶sub _unknown_resource_error {
Subroutine _unknown_resource_error: called CC=2 SCAR=7.2
203 47 my ($self, $short_class) = @_;
204 47 ▶ return sprintf(
Branch: 1 branch
BranchTrueFalseTotal
defined $short_class ? : 47 0 47
205 "unknown resource '%s': no IO::K8s class for this apiVersion/kind"
206 . " (add it to resource_map if it is a CRD)",
207 defined $short_class ? $short_class : '(undef)',
208 );
209 }
210  
211 # The message for a reference where a resource name - a plain string - is
212 # required, and nothing for a string. A reference reaches a name position two
213 # ways: as the class-name argument (a manifest hashref handed to patch(),
214 # caught by _resolve_class below), or as the object-name argument of get() and
215 # delete() (a manifest hashref or an IO::K8s object, karr k70). Left unchecked
216 # either one stringifies into the request path (.../pods/HASH(0x...)) and only
217 # the server's 404 shows the error. One wording for both positions, so a
218 # reference is refused the same way wherever it lands.
219 730 ▶sub _resource_name_error {
Subroutine _resource_name_error: called CC=3 SCAR=11.0
220 730 my ($self, $name) = @_;
221 730 ▶ return unless ref $name;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $name 713 17 730
222 17 ▶ return 'resource name must be a string, got '
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($name) ? : 4 13 17
223 . (blessed($name) ? 'an object of class ' . ref($name)
224 : 'a ' . ref($name) . ' reference');
225 }
226  
227 # Resolve a resource name to its IO::K8s class. Returns the class, or
228 # (undef, $message) when no usable class comes out of the name, which every
229 # caller reports per its contract - a failed Future or a croak. Kubernetes::REST's
230 # expand_class fails closed for a qualified name (undef) but open for a bare
231 # Kind: it fabricates 'IO::K8s::<Kind>' whether or not that class exists. Both
232 # are an unknown resource; whatever else can go wrong with the class it did
233 # resolve to is _usable_class's to report. A reference is no name at all -
234 # say a manifest hashref handed to patch() - and is refused as such
235 # (_resource_name_error): expand_class would stringify it into a class name
236 # ('IO::K8s::HASH(0x...)') and the load error would name that instead.
237 607 ▶sub _resolve_class {
Subroutine _resolve_class: called CC=3 SCAR=11.0
238 607 my ($self, $name, @args) = @_;
239 607 ▶ if (my $error = $self->_resource_name_error($name)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $self->_resource_name_error($name)) 9 598 607
240 9 return (undef, $error);
241 }
242 598 ▶ my $class = $self->_rest->expand_class($name, @args)
Condition100%2/2
$self->_rest->expand_class($name, @args) // (return undef, $self->_unknown_resource_error($name))
l!l
57226
MC/DC100%1/1
$self->_rest->expand_class($name, @args) // (return undef, $self->_unknown_resource_error($name))
$self->_rest->expand_class($name, @args)
Truth table100%2/2
A
A= $self->_rest->expand_class($name, @args)
Aresult
11
00
243 // return (undef, $self->_unknown_resource_error($name));
244 572 return $self->_usable_class($name, $class);
245 }
246  
247 # What build_path would otherwise die on, synchronously and without naming the
248 # resource: the class must load, and it must answer api_version as a class
249 # method - build_path's own precondition for a path. That precondition, not a
250 # role, is what tells a resource class from IO::K8s's helpers (List, Resource,
251 # Types, Unstructured) that a bare name can land on: List has an api_version,
252 # but as an instance accessor that dies when called on the class. Returns the
253 # class, or (undef, $message) with the real cause - the load error, or "not a
254 # resource class". A fabricated bare-Kind name that does not load is an
255 # unknown resource, not a load error. IO::K8s::Unstructured is the one
256 # resource without a class-level api_version - its Kind is instance data -
257 # so, reached any other way than its own bare name 'Unstructured' (above all
258 # through Kubernetes::REST's discovery fallback for a Kind), it is passed on
259 # to build_path, which gets the Kind from _unstructured_hint.
260 816 ▶sub _usable_class {
Subroutine _usable_class: called CC=14 SCAR=26.8
261 816 my ($self, $name, $class) = @_;
262 816 my $rest = $self->_rest;
263 816 ▶ my $fabricated = defined $name && !ref $name && $class eq 'IO::K8s::' . $name;
Condition50%3/6
defined $name && !ref($name) && $class eq 'IO::K8s::' . $name
!ll&&!rl&&r
072987
defined $name and not ref $name
!ll&&!rl&&r
00816
MC/DC33%1/3
defined $name && !ref($name) && $class eq 'IO::K8s::' . $name
defined $name not ref $name $class eq 'IO::K8s::' . $name
Truth table50%2/4
A and not(B) && C
A= defined $nameB= not ref $nameC= $class eq 'IO::K8s::' . $name
ABCresult
0XX0
10X0
1100
1111
264  
265 816 ▶ unless ($class->can('new') || eval { $rest->k8s->load_class($class); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class->can("new") or eval { do { $rest->k8s->load_class($class); 1 } }) 72 744 816
Condition100%3/3
$class->can("new") or eval {
l!l&&r!l&&!r
7093572
MC/DC100%2/2
$class->can("new") or eval { do { $rest->k8s->load_class($class); 1 } }
$class->can("new") eval { do { $rest->k8s->load_class($class); 1 } }
Truth table100%3/3
A or B
A= $class->can("new")B= eval { do { $rest->k8s->load_class($class); 1 } }
ABresult
1X1
011
000
266 72 my $load_error = $@;
267 72 ▶ return (undef, $self->_unknown_resource_error($name)) if $fabricated;
Branch: 1 branch
BranchTrueFalseTotal
if $fabricated 21 51 72
268 51 chomp $load_error;
269 51 return (undef, sprintf(
270 "resource '%s' resolves to class %s, which cannot be loaded: %s",
271 $name, $class, $load_error,
272 ));
273 }
274  
275 744 ▶ if ($class eq 'IO::K8s::Unstructured' && !$fabricated) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq "IO::K8s::Unstructured" and not $fabricated) 90 654 744
Condition100%3/3
$class eq "IO::K8s::Unstructured" and not $fabricated
!ll&&!rl&&r
6371790
MC/DC100%2/2
$class eq "IO::K8s::Unstructured" and not $fabricated
$class eq "IO::K8s::Unstructured" not $fabricated
Truth table100%3/3
A and not(B)
A= $class eq "IO::K8s::Unstructured"B= not $fabricated
ABresult
0X0
100
111
276 # A qualified name counts only in its own group/version (see
277 # _request_path). Asking for its path confirms it exactly, from the
278 # cached catalog, without a request.
279 90 ▶ return $class unless defined $name && !ref $name && $name =~ m{/};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and $name =~ m[/] 80 10 90
Condition50%3/6
defined $name and not ref $name and $name =~ m[/]
!ll&&!rl&&r
08010
defined $name and not ref $name
!ll&&!rl&&r
0090
MC/DC33%1/3
defined $name and not ref $name and $name =~ m[/]
defined $name not ref $name $name =~ m[/]
Truth table50%2/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $name =~ m[/]
ABCresult
0XX0
10X0
1100
1111
280 10 my ($path) = $self->_request_path($class, $name);
281 10 ▶ return defined $path ? $class : (undef, $self->_unknown_resource_error($name));
Branch: 1 branch
BranchTrueFalseTotal
defined $path ? : 10 0 10
282 }
283 654 ▶ return $class if $class->can('api_version') && defined eval { $class->api_version };
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("api_version") and defined eval { do { $class->api_version } } 570 84 654
Condition100%3/3
$class->can("api_version") and defined eval {
!ll&&!rl&&r
5826570
MC/DC100%2/2
$class->can("api_version") and defined eval { do { $class->api_version } }
$class->can("api_version") defined eval { do { $class->api_version } }
Truth table100%3/3
A and B
A= $class->can("api_version")B= defined eval { do { $class->api_version } }
ABresult
0X0
100
111
284 84 return (undef, sprintf(
285 "resource '%s' resolves to %s, which is not a Kubernetes resource class"
286 . " (it has no api_version to build a request path from)",
287 $name, $class,
288 ));
289 }
290  
291 # The class of an object handed to one of the object forms (create, update,
292 # update_status, patch, patch_status, delete, ensure), which build their path
293 # from it. It is checked like a resolved name (_usable_class): an IO::K8s::List,
294 # a nested type such as a PodSpec, or no IO::K8s object at all has no request
295 # path, and build_path - or the metadata lookup before it - would die on it
296 # synchronously. Returns the class, or (undef, $message) naming $label, which
297 # each caller reports per its contract - a failed Future or a croak.
298 235 ▶sub _object_class {
Subroutine _object_class: called CC=3 SCAR=11.0
299 235 my ($self, $label, $object) = @_;
300 235 ▶ return (undef, "$label requires an IO::K8s object") unless blessed($object);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($object) 5 230 235
301 230 my ($class, $error) = $self->_usable_class(ref($object), ref($object));
302 230 ▶ return defined $class ? $class : (undef, "$label: $error");
Branch: 1 branch
BranchTrueFalseTotal
defined $class ? : 212 18 230
303 }
304  
305 # The extra build_path arguments for a class that resolved to
306 # IO::K8s::Unstructured - empty for every other class, whose path comes from
307 # the class alone. Unstructured has no class-level api_version: its Kind and
308 # apiVersion are instance data, so build_path takes them from the caller and
309 # looks plural and scope up in Kubernetes::REST's discovery catalog. $ident is
310 # what the class came from. An object gives its own kind and apiVersion. A
311 # name is split the way Kubernetes::REST's expand_class splits it: a qualified
312 # 'example.org/v1/Widget' keeps its group and version, instead of landing in
313 # whichever group serving a Widget discovery lists first, and an explicit
314 # class name ('+...', 'IO::K8s::...', any '...::...') carries no Kind. Mirrors
315 # the private helper of the same name in Kubernetes::REST, which is not part
316 # of its public seam.
317 666 ▶sub _unstructured_hint {
Subroutine _unstructured_hint: called CC=11 SCAR=24.4
318 666 my ($self, $class, $ident) = @_;
319 666 ▶ return () unless defined $class && $class eq 'IO::K8s::Unstructured';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and $class eq "IO::K8s::Unstructured" 565 101 666
Condition66%2/3
defined $class and $class eq "IO::K8s::Unstructured"
!ll&&!rl&&r
0565101
MC/DC50%1/2
defined $class and $class eq "IO::K8s::Unstructured"
defined $class $class eq "IO::K8s::Unstructured"
Truth table66%2/3
A and B
A= defined $classB= $class eq "IO::K8s::Unstructured"
ABresult
0X0
100
111
320 101 my ($kind, $api_version);
321 101 ▶ if (blessed($ident)) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($ident)) { } 50 51 101
elsif (defined $ident and not ref $ident and not $ident =~ /\A(?:\+|IO::K8s::)/) { } 29 22 51
322 50 ($kind, $api_version) = ($ident->kind, $ident->apiVersion);
323 ▶ } elsif (defined $ident && !ref $ident && $ident !~ m{\A(?:\+|IO::K8s::)}) {
Condition50%3/6
defined $ident and not ref $ident and not $ident =~ /\A(?:\+|IO::K8s::)/
!ll&&!rl&&r
02229
defined $ident and not ref $ident
!ll&&!rl&&r
0051
MC/DC33%1/3
defined $ident and not ref $ident and not $ident =~ /\A(?:\+|IO::K8s::)/
defined $ident not ref $ident not $ident =~ /\A(?:\+|IO::K8s::)/
Truth table50%2/4
A and not(B) and not(C)
A= defined $identB= not ref $identC= not $ident =~ /\A(?:\+|IO::K8s::)/
ABCresult
0XX0
10X0
1100
1111
324 29 ▶ if ($ident =~ m{/}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ident =~ m[/]) { } 14 15 29
elsif (not $ident =~ /::/) { } 15 0 15
325 14 ($api_version, $kind) = $ident =~ m{\A(.*)/([^/]+)\z};
326 } elsif ($ident !~ /::/) {
327 15 $kind = $ident;
328 }
329 }
330 return (
331 101 ▶ (defined $kind ? (kind => $kind) : ()),
Branch: 2 branches
BranchTrueFalseTotal
defined $kind ? : 71 30 101
defined $api_version ? : 64 37 101
332 (defined $api_version ? (api_version => $api_version) : ()),
333 );
334 }
335  
336 # The request path for $class: Kubernetes::REST's build_path with %args and
337 # the Unstructured hint for $ident, the name or object the class came from.
338 # Returns the path, or (undef, $message) when build_path gives up - on
339 # IO::K8s::Unstructured without discovery, or without a Kind (the explicit
340 # class name, an object without kind) - which every caller reports per its
341 # contract, a failed Future or a croak, as it does a resolution error.
342 # build_path croaks for that, and synchronously: from a Future-returning
343 # method it escaped as a die. The message drops the location the croak ends
344 # in, which points here; a croaking caller adds its caller's own.
345 #
346 # An apiVersion in the hint - from a qualified name or the object - names
347 # the one group/version the request may go to; a path outside it is refused
348 # with Kubernetes::REST's own message (its k43), so list, delete and
349 # ensure_only's prune never reach another group serving a Kind of that name.
350 666 ▶sub _request_path {
Subroutine _request_path: called CC=8 SCAR=21.2
351 666 my ($self, $class, $ident, %args) = @_;
352 666 my %hint = $self->_unstructured_hint($class, $ident);
353 666 my $path = eval { $self->_rest->build_path($class, %args, %hint) };
354 666 ▶ unless (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path) 45 621 666
355 45 ▶ my $error = $@ ? "$@" : "cannot build a request path for $class";
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 45 0 45
356 45 $error =~ s/\s+\z//;
357 45 $error =~ s/ at \S+ line \d+\.\z//;
358 45 return (undef, $error);
359 }
360 621 my $api_version = $hint{api_version};
361 621 ▶ if (defined $api_version && length $api_version) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $api_version and length $api_version) 41 580 621
Condition66%2/3
defined $api_version and length $api_version
!ll&&!rl&&r
580041
MC/DC50%1/2
defined $api_version and length $api_version
defined $api_version length $api_version
Truth table66%2/3
A and B
A= defined $api_versionB= length $api_version
ABresult
0X0
100
111
362 41 ▶ my $prefix = $api_version =~ m{/} ? "/apis/$api_version/" : "/api/$api_version/";
Branch: 1 branch
BranchTrueFalseTotal
$api_version =~ m[/] ? : 39 2 41
363 41 ▶ return (undef, "no discovery entry for Kind '" . ($hint{kind} // '') . "'"
Branch: 1 branch
BranchTrueFalseTotal
unless index($path, $prefix) == 0 0 41 41
Condition0%0/2
$hint{"kind"} // ""
l!l
00
MC/DC0%0/1
$hint{"kind"} // ""
$hint{"kind"}
Truth table0%0/2
A
A= $hint{"kind"}
Aresult
11
00
364 . " in apiVersion '$api_version' - cannot build a path for IO::K8s::Unstructured")
365 unless index($path, $prefix) == 0;
366 }
367 621 return $path;
368 }
369  
370 # The name to hand Kubernetes::REST's inflate_object, inflate_list and
371 # process_watch_chunk for $class. A single-segment class of the caller's own
372 # ('+Gizmo' in the resource_map, which expand_class returns as 'Gizmo') must
373 # not read to them as the Kind Gizmo - IO::K8s::Gizmo, or whatever class the
374 # map gives that Kind. A loaded IO::K8s resource class therefore goes over as
375 # '+Class', which is taken exactly; anything else is left as it is. Mirrors
376 # the private helper of the same name in Kubernetes::REST, which is not part
377 # of its public seam.
378 398 ▶sub _exact_class {
Subroutine _exact_class: called CC=7 SCAR=28.7
379 398 my ($self, $class) = @_;
380 398 ▶ return '+' . $class
Branch: 1 branch
BranchTrueFalseTotal
if defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does") and $class->does("IO::K8s::Role::Resource") 398 0 398
Condition33%5/15
defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does") and $class->does("IO::K8s::Role::Resource")
!ll&&!rl&&r
00398
defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does")
!ll&&!rl&&r
00398
defined $class and not ref $class and length $class and not $class =~ /\A\+/
!ll&&!rl&&r
00398
defined $class and not ref $class and length $class
!ll&&!rl&&r
00398
defined $class and not ref $class
!ll&&!rl&&r
00398
MC/DC0%0/6
defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does") and $class->does("IO::K8s::Role::Resource")
defined $class not ref $class length $class not $class =~ /\A\+/ $class->can("does") $class->does("IO::K8s::Role::Resource")
Truth table14%1/7
A and not(B) and C and not(D) and E and F
A= defined $classB= not ref $classC= length $classD= not $class =~ /\A\+/E= $class->can("does")F= $class->does("IO::K8s::Role::Resource")
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
381 if defined $class && !ref $class && length $class && $class !~ /\A\+/
382 && $class->can('does') && $class->does('IO::K8s::Role::Resource');
383 0 return $class;
384 }
385  
386 34 ▶sub expand_class {
Subroutine expand_class: called CC=2 SCAR=6.9
Pod documented
387 34 my ($self, @args) = @_;
388 34 my ($class, $error) = $self->_resolve_class(@args);
389 34 ▶ croak $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 19 15 34
390 15 return $class;
391 }
392  
393  
394 7 ▶sub discover {
Subroutine discover: called CC=2 SCAR=6.9
Pod documented
395 7 my ($self) = @_;
396  
397 7 my $rest = $self->_rest;
398 7 ▶ return Future->done unless $self->resource_map_from_cluster;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->resource_map_from_cluster 1 6 7
399  
400 6 my %requests = $rest->prepare_discovery_requests;
401 6 my @roots = sort keys %requests;
402 return Future->needs_all(
403 12 map { $self->_checked_request($requests{$_}, "discovery GET $_") } @roots
404 5 ▶ )->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
405 5 my %responses;
406 5 @responses{@roots} = @_;
407 # False for legacy discovery: nothing is kept, and Kubernetes::REST
408 # reads it through its own io on first use, as without discover.
409 5 $rest->absorb_discovery(%responses);
410 4 return Future->done;
411 6 });
412 }
413  
414  
415 27 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=1 SCAR=0.0
416 27 my ($self, $loop) = @_;
417 27 $self->add_child($self->_http);
418 }
419  
420 # ============================================================================
421 # ASYNC CRUD METHODS - return Futures
422 # ============================================================================
423  
424 59 ▶sub list {
Subroutine list: called CC=1 SCAR=0.0
Pod documented
425 59 my ($self, $short_class, @args) = @_;
426  
427 59 my $rest = $self->_rest;
428 29 ▶ return $self->_list_request($short_class, @args)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
429 29 my ($class, $response) = @_;
430 26 ▶ return $self->_checked_response($response, "list $short_class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
431 26 return Future->done($rest->inflate_list($self->_exact_class($class), $response));
432 29 });
433 59 });
434 }
435  
436  
437 # list() up to the response, unchecked: resolves with the class and the raw
438 # Kubernetes::REST::HTTPResponse, or fails before any request when the name
439 # resolves to no usable class. ensure_only() needs the status itself - a 404
440 # there means the Kind is not served, not a failure - and must not read it
441 # back out of the text check_response croaks with.
442 91 ▶sub _list_request {
Subroutine _list_request: called CC=8 SCAR=20.8
443 91 my ($self, $short_class, @args) = @_;
444  
445 91 ▶ return Future->fail("Invalid arguments to list()") if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 4 87 91
446 87 my %args = @args;
447 87 my $unknown = $self->_unknown_argument_error('list', \%args,
448 qw( namespace labelSelector fieldSelector limit continue resourceVersion ));
449 87 ▶ return Future->fail($unknown) if defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
if defined $unknown 5 82 87
450  
451 82 my $rest = $self->_rest;
452 82 my ($class, $error) = $self->_resolve_class($short_class);
453 82 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 21 61 82
454  
455 # Selectors and paging are query parameters; build_path only knows path
456 # segments and would drop them silently, turning a filtered list into a
457 # full one.
458 61 my %params;
459 61 for my $selector (qw(labelSelector fieldSelector limit continue resourceVersion)) {
460 305 my $value = delete $args{$selector};
461 305 ▶ $params{$selector} = $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 43 262 305
462 }
463  
464 61 (my $path, $error) = $self->_request_path($class, $short_class, %args);
465 61 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 4 57 61
466 return $self->_request_unchecked('GET', $path,
467 %params ? (parameters => \%params) : (),
468 57 ▶ )->then(sub { Future->done($class, @_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
%params ? : 37 20 57
469 }
470  
471 57 ▶sub get {
Subroutine get: called CC=11 SCAR=24.0
Pod documented
472 57 my ($self, $short_class, @rest_args) = @_;
473  
474 57 my $rest = $self->_rest;
475 57 my %args;
476 57 ▶ if (@rest_args == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest_args == 1) { } 24 33 57
elsif (@rest_args >= 2 and not $rest_args[0] =~ /^(name|namespace)$/) { } 26 7 33
elsif (@rest_args % 2 == 0) { } 5 2 7
477 24 $args{name} = $rest_args[0];
478 ▶ } elsif (@rest_args >= 2 && $rest_args[0] !~ /^(name|namespace)$/) {
Condition66%2/3
@rest_args >= 2 and not $rest_args[0] =~ /^(name|namespace)$/
!ll&&!rl&&r
0726
MC/DC50%1/2
@rest_args >= 2 and not $rest_args[0] =~ /^(name|namespace)$/
@rest_args >= 2 not $rest_args[0] =~ /^(name|namespace)$/
Truth table66%2/3
A and not(B)
A= @rest_args >= 2B= not $rest_args[0] =~ /^(name|namespace)$/
ABresult
0X0
100
111
479 26 $args{name} = shift @rest_args;
480 26 ▶ return Future->fail("Invalid arguments to get()") if @rest_args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rest_args % 2 3 23 26
481 23 %args = (%args, @rest_args);
482 } elsif (@rest_args % 2 == 0) {
483 5 %args = @rest_args;
484 } else {
485 2 return Future->fail("Invalid arguments to get()");
486 }
487 52 my $unknown = $self->_unknown_argument_error('get', \%args, qw( name namespace ));
488 52 ▶ return Future->fail($unknown) if defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
if defined $unknown 2 50 52
489  
490 # A reference in the name position (a manifest hashref, an IO::K8s object)
491 # would otherwise be stringified straight into the path (k70).
492 50 ▶ if (my $name_error = $self->_resource_name_error($args{name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name_error = $self->_resource_name_error($args{"name"})) 4 46 50
493 4 return Future->fail($name_error);
494 }
495  
496 46 my ($class, $error) = $self->_resolve_class($short_class);
497 46 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 19 27 46
498 27 ▶ return Future->fail("name required for get") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 26 27
499  
500 26 (my $path, $error) = $self->_request_path($class, $short_class, %args);
501 26 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 24 26
502 24 my $req = $rest->prepare_request('GET', $path);
503  
504 19 ▶ return $self->_checked_request($req, "get $short_class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
505 19 my ($response) = @_;
506 19 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
507 24 });
508 }
509  
510  
511 34 ▶sub create {
Subroutine create: called CC=5 SCAR=16.3
Pod documented
512 34 my ($self, $object) = @_;
513  
514 34 my $rest = $self->_rest;
515 34 my ($class, $error) = $self->_object_class('create', $object);
516 34 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 4 30 34
517 30 ▶ my $namespace = $object->can('metadata') && $object->metadata
Branch: 1 branch
BranchTrueFalseTotal
$object->can('metadata') && $object->metadata ? : 30 0 30
Condition33%1/3
$object->can("metadata") and $object->metadata
!ll&&!rl&&r
0030
MC/DC0%0/2
$object->can("metadata") and $object->metadata
$object->can("metadata") $object->metadata
Truth table33%1/3
A and B
A= $object->can("metadata")B= $object->metadata
ABresult
0X0
100
111
518 ? $object->metadata->namespace
519 : undef;
520  
521 30 (my $path, $error) = $self->_request_path($class, $object, namespace => $namespace);
522 30 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 3 27 30
523 27 my $req = $rest->prepare_request('POST', $path, body => $object->TO_JSON);
524  
525 24 ▶ return $self->_checked_request($req, "create " . ref($object))->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
526 24 my ($response) = @_;
527 24 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
528 27 });
529 }
530  
531  
532 20 ▶sub update {
Subroutine update: called CC=5 SCAR=16.1
Pod documented
533 20 my ($self, $object) = @_;
534  
535 20 my $rest = $self->_rest;
536 20 my ($class, $error) = $self->_object_class('update', $object);
537 20 ▶ croak $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 3 17 20
538 17 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 16 1 17
539 16 ▶ my $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $metadata->name or croak("object must have metadata.name") 15 1 16
540 15 my $namespace = $metadata->namespace;
541  
542 15 (my $path, $error) = $self->_request_path($class, $object,
543 name => $name, namespace => $namespace);
544 15 ▶ croak $error unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 3 12 15
545 12 my $req = $rest->prepare_request('PUT', $path, body => $object->TO_JSON);
546  
547 6 ▶ return $self->_checked_request($req, "update " . ref($object))->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
548 6 my ($response) = @_;
549 6 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
550 12 });
551 }
552  
553  
554 18 ▶sub update_status {
Subroutine update_status: called CC=5 SCAR=16.1
Pod documented
555 18 my ($self, $object) = @_;
556  
557 18 my $rest = $self->_rest;
558 18 my ($class, $error) = $self->_object_class('update_status', $object);
559 18 ▶ croak $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 3 15 18
560 15 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 15 0 15
561 15 ▶ my $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $metadata->name or croak("object must have metadata.name") 14 1 15
562 14 my $namespace = $metadata->namespace;
563  
564 14 (my $path, $error) = $self->_request_path($class, $object,
565 name => $name,
566 namespace => $namespace,
567 subresource => 'status',
568 );
569 14 ▶ croak $error unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 3 11 14
570 11 my $req = $rest->prepare_request('PUT', $path, body => $object->TO_JSON);
571  
572 6 ▶ return $self->_checked_request($req, "update_status $class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
573 6 my ($response) = @_;
574 6 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
575 11 });
576 }
577  
578  
579 # Argument handling shared by patch() and patch_status(): the object form and
580 # both class+name forms, the required patch document and the patch type.
581 # Returns (undef, $class, $name, $namespace, $patch, $content_type), or just
582 # the failure message, which the caller turns into a failed Future. $label
583 # names the calling method in those messages; $default_type is the patch type
584 # used when the caller passes none.
585 119 ▶sub _patch_args {
Subroutine _patch_args: called CC=16 SCAR=27.7
586 119 my ($self, $label, $default_type, $class_or_object, @rest_args) = @_;
587  
588 119 my $rest = $self->_rest;
589 119 my ($class, $name, $namespace, $patch, $patch_type);
590  
591 119 ▶ if (ref($class_or_object) && blessed($class_or_object)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_object and builtin::blessed($class_or_object)) { } 38 81 119
Condition100%3/3
ref $class_or_object and builtin::blessed($class_or_object)
!ll&&!rl&&r
77438
MC/DC100%2/2
ref $class_or_object and builtin::blessed($class_or_object)
ref $class_or_object builtin::blessed($class_or_object)
Truth table100%3/3
A and B
A= ref $class_or_objectB= builtin::blessed($class_or_object)
ABresult
0X0
100
111
592 38 my $object = $class_or_object;
593 38 ($class, my $error) = $self->_object_class($label, $object);
594 38 ▶ return $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 6 32 38
595 32 ▶ my $metadata = $object->metadata or return "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or return "object must have metadata" 30 2 32
596 30 ▶ $name = $metadata->name or return "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
$name = $metadata->name or return "object must have metadata.name" 28 2 30
597 28 $namespace = $metadata->namespace;
598 28 ▶ return "Invalid arguments to $label()" if @rest_args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rest_args % 2 4 24 28
599 24 my %args = @rest_args;
600 24 my $unknown = $self->_unknown_argument_error($label, \%args, qw( patch type ));
601 24 ▶ return $unknown if defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
if defined $unknown 2 22 24
602 22 ▶ $patch = $args{patch} // return "$label requires 'patch' parameter";
Condition100%2/2
$args{"patch"} // (return "$label requires 'patch' parameter")
l!l
202
MC/DC100%1/1
$args{"patch"} // (return "$label requires 'patch' parameter")
$args{"patch"}
Truth table100%2/2
A
A= $args{"patch"}
Aresult
11
00
603 20 ▶ $patch_type = $args{type} // $default_type;
Condition66%2/3
$args{"type"} // $default_type
l!l&&r!l&&!r
8120
MC/DC0%0/2
$args{"type"} // $default_type
$args{"type"} $default_type
Truth table66%2/3
A // B
A= $args{"type"}B= $default_type
ABresult
1X1
011
000
604 } else {
605 81 my ($arg_error, %args) = $self->_named_args($label, \@rest_args,
606 qw( name namespace patch type ));
607 81 ▶ return $arg_error if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 11 70 81
608  
609 70 ($class, my $error) = $self->_resolve_class($class_or_object);
610 70 ▶ return $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 34 36 70
611 36 ▶ $name = $args{name} or return "name required for $label";
Branch: 1 branch
BranchTrueFalseTotal
$name = $args{"name"} or return "name required for $label" 34 2 36
612 34 $namespace = $args{namespace};
613 34 ▶ $patch = $args{patch} // return "$label requires 'patch' parameter";
Condition100%2/2
$args{"patch"} // (return "$label requires 'patch' parameter")
l!l
331
MC/DC100%1/1
$args{"patch"} // (return "$label requires 'patch' parameter")
$args{"patch"}
Truth table100%2/2
A
A= $args{"patch"}
Aresult
11
00
614 33 ▶ $patch_type = $args{type} // $default_type;
Condition66%2/3
$args{"type"} // $default_type
l!l&&r!l&&!r
19140
MC/DC0%0/2
$args{"type"} // $default_type
$args{"type"} $default_type
Truth table66%2/3
A // B
A= $args{"type"}B= $default_type
ABresult
1X1
011
000
615 }
616  
617 53 my %patch_types = (
618 strategic => 'application/strategic-merge-patch+json',
619 merge => 'application/merge-patch+json',
620 json => 'application/json-patch+json',
621 );
622 53 ▶ my $content_type = $patch_types{$patch_type}
Condition100%2/2
$patch_types{$patch_type} // (return "Unknown patch type '${patch_type}'")
l!l
503
MC/DC100%1/1
$patch_types{$patch_type} // (return "Unknown patch type '${patch_type}'")
$patch_types{$patch_type}
Truth table100%2/2
A
A= $patch_types{$patch_type}
Aresult
11
00
623 // return "Unknown patch type '$patch_type'";
624  
625 50 return (undef, $class, $name, $namespace, $patch, $content_type);
626 }
627  
628 50 ▶sub patch {
Subroutine patch: called CC=3 SCAR=11.0
Pod documented
629 50 my ($self, $class_or_object, @rest_args) = @_;
630  
631 50 my $rest = $self->_rest;
632 50 my ($error, $class, $name, $namespace, $patch, $content_type)
633 = $self->_patch_args('patch', 'strategic', $class_or_object, @rest_args);
634 50 ▶ return Future->fail($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 29 21 50
635  
636 21 (my $path, $error) = $self->_request_path($class, $class_or_object,
637 name => $name, namespace => $namespace);
638 21 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 5 16 21
639 16 my $req = $rest->prepare_request('PATCH', $path,
640 body => $patch, content_type => $content_type);
641  
642 13 ▶ return $self->_checked_request($req, "patch $class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
643 13 my ($response) = @_;
644 13 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
645 16 });
646 }
647  
648  
649 69 ▶sub patch_status {
Subroutine patch_status: called CC=3 SCAR=11.0
Pod documented
650 69 my ($self, $class_or_object, @rest_args) = @_;
651  
652 69 my $rest = $self->_rest;
653 69 my ($error, $class, $name, $namespace, $patch, $content_type)
654 = $self->_patch_args('patch_status', 'merge', $class_or_object, @rest_args);
655 69 ▶ return Future->fail($error) if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 40 29 69
656  
657 29 (my $path, $error) = $self->_request_path($class, $class_or_object,
658 name => $name,
659 namespace => $namespace,
660 subresource => 'status',
661 );
662 29 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 5 24 29
663 24 my $req = $rest->prepare_request('PATCH', $path,
664 body => $patch, content_type => $content_type);
665  
666 19 ▶ return $self->_checked_request($req, "patch_status $class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
667 19 my ($response) = @_;
668 19 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
669 24 });
670 }
671  
672  
673 81 ▶sub delete {
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
674 81 my ($self, @args) = @_;
675  
676 81 my $rest = $self->_rest;
677 46 ▶ return $self->_delete_request(@args)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
678 46 my ($class, $response) = @_;
679 40 ▶ return $self->_checked_response($response, "delete $class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
680 40 return Future->done(1);
681 46 });
682 81 });
683 }
684  
685  
686 # The message for the first key of %$args (in sort order) that is not in
687 # @allowed, or nothing when there is none - Kubernetes::REST's wording, naming
688 # $label and what is allowed. Each caller reports it per its contract, a
689 # failed Future or a croak, before any request: an option a method does not
690 # take would otherwise be dropped silently (a misspelt labelSelector lists
691 # everything, namespace for namespaces makes ensure_only prune at cluster
692 # scope only).
693 685 ▶sub _unknown_argument_error {
Subroutine _unknown_argument_error: called CC=2 SCAR=6.9
694 685 my ($self, $label, $args, @allowed) = @_;
695 685 my %allowed = map { $_ => 1 } @allowed;
696 685 my ($unknown) = sort grep { !$allowed{$_} } keys %$args;
697 685 ▶ return unless defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $unknown 531 154 685
698 154 return "Unknown argument '$unknown' to $label() (allowed: " . join(', ', @allowed) . ')';
699 }
700  
701 # Argument handling shared by log(), port_forward(), exec(), attach(),
702 # cp_to_pod(), cp_from_pod() and the class form of patch() and patch_status()
703 # (in _patch_args): the name positional - METHOD('Pod', 'web',
704 # %options) - or keyed - METHOD('Pod', name => 'web', %options). A first
705 # argument that is one of @allowed starts the keyed form, so the keys read as
706 # the start of the keyed form and the keys _unknown_argument_error accepts are
707 # one list. Returns (undef, %args), or just the failure message, which the
708 # caller turns into a failed Future; $label names the calling method.
709 465 ▶sub _named_args {
Subroutine _named_args: called CC=7 SCAR=19.5
710 465 my ($self, $label, $rest_args, @allowed) = @_;
711 465 my @rest_args = @$rest_args;
712 465 my $keys = join '|', map { quotemeta } @allowed;
713 465 my %args;
714 465 ▶ if (@rest_args >= 1
Branch: 2 branches
BranchTrueFalseTotal
if (@rest_args >= 1 and not ref $rest_args[0] and not $rest_args[0] =~ /^(?:$keys)$/) { } 343 122 465
elsif (@rest_args % 2 == 0) { } 56 66 122
Condition100%6/6
@rest_args >= 1 and not ref $rest_args[0] and not $rest_args[0] =~ /^(?:$keys)$/
!ll&&!rl&&r
12110343
@rest_args >= 1 and not ref $rest_args[0]
!ll&&!rl&&r
66453
MC/DC100%3/3
@rest_args >= 1 and not ref $rest_args[0] and not $rest_args[0] =~ /^(?:$keys)$/
@rest_args >= 1 not ref $rest_args[0] not $rest_args[0] =~ /^(?:$keys)$/
Truth table100%4/4
A and not(B) and not(C)
A= @rest_args >= 1B= not ref $rest_args[0]C= not $rest_args[0] =~ /^(?:$keys)$/
ABCresult
0XX0
10X0
1100
1111
715 && !ref($rest_args[0])
716 && $rest_args[0] !~ /^(?:$keys)$/
717 ) {
718 343 $args{name} = shift @rest_args;
719 343 ▶ return "Invalid arguments to $label()" if @rest_args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rest_args % 2 21 322 343
720 322 %args = (%args, @rest_args);
721 } elsif (@rest_args % 2 == 0) {
722 56 %args = @rest_args;
723 } else {
724 66 return "Invalid arguments to $label()";
725 }
726 378 my $unknown = $self->_unknown_argument_error($label, \%args, @allowed);
727 378 ▶ return $unknown if defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
if defined $unknown 135 243 378
728 243 return (undef, %args);
729 }
730  
731 # The propagationPolicy values the API server accepts in a DELETE's
732 # DeleteOptions.
733 54 my @PROPAGATION_POLICIES = qw( Background Foreground Orphan );
734  
735 # Nothing when $policy is absent or one of @PROPAGATION_POLICIES, else the
736 # message for it, naming $label - in Kubernetes::REST's wording.
737 102 ▶sub _propagation_policy_error {
Subroutine _propagation_policy_error: called CC=3 SCAR=11.0
738 102 my ($self, $label, $policy) = @_;
739 102 ▶ return if !defined $policy || grep { $policy eq $_ } @PROPAGATION_POLICIES;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $policy or grep {$policy eq $_;} @PROPAGATION_POLICIES 98 4 102
Condition100%3/3
not defined $policy or grep {$policy eq $_;} @PROPAGATION_POLICIES
l!l&&r!l&&!r
38604
MC/DC100%2/2
not defined $policy or grep {$policy eq $_;} @PROPAGATION_POLICIES
not defined $policy grep {$policy eq $_;} @PROPAGATION_POLICIES
Truth table100%3/3
not(A) or B
A= not defined $policyB= grep {$policy eq $_;} @PROPAGATION_POLICIES
ABresult
1X1
011
000
740 4 return "Unknown propagationPolicy '$policy' for $label() (use: "
741 . join(', ', @PROPAGATION_POLICIES) . ')';
742 }
743  
744 # delete() up to the response, unchecked: resolves with the class and the raw
745 # Kubernetes::REST::HTTPResponse, or fails before any request on bad
746 # arguments - for the same reason as _list_request: ensure_only() treats a
747 # 404 (already gone) differently from a failure. An option delete() does not
748 # know is a bad argument too: a mistyped propagationPolicy dropped on the
749 # floor would leave a Job's Pods orphaned.
750 99 ▶sub _delete_request {
Subroutine _delete_request: called CC=18 SCAR=28.9
751 99 my ($self, $class_or_object, @rest_args) = @_;
752  
753 99 my ($class, $name, $namespace, %options, @known);
754  
755 99 ▶ if (ref($class_or_object)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_object) { } 41 58 99
756 41 my $object = $class_or_object;
757 41 ($class, my $error) = $self->_object_class('delete', $object);
758 41 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 3 38 41
759 38 ▶ my $metadata = $object->metadata or return Future->fail("object must have metadata");
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or return "Future"->fail("object must have metadata") 37 1 38
760 37 ▶ $name = $metadata->name or return Future->fail("object must have metadata.name");
Branch: 1 branch
BranchTrueFalseTotal
$name = $metadata->name or return "Future"->fail("object must have metadata.name") 36 1 37
761 36 $namespace = $metadata->namespace;
762 36 ▶ return Future->fail("Invalid arguments to delete()") if @rest_args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rest_args % 2 1 35 36
763 35 %options = @rest_args;
764 35 @known = qw( propagationPolicy );
765 } else {
766 58 my %args;
767 58 ▶ if (@rest_args == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest_args == 1) { } 13 45 58
elsif (@rest_args >= 2 and not $rest_args[0] =~ /^(name|namespace|propagationPolicy)$/) { } 33 12 45
elsif (@rest_args % 2 == 0) { } 11 1 12
768 13 $args{name} = $rest_args[0];
769 ▶ } elsif (@rest_args >= 2 && $rest_args[0] !~ /^(name|namespace|propagationPolicy)$/) {
Condition100%3/3
@rest_args >= 2 and not $rest_args[0] =~ /^(name|namespace|propagationPolicy)$/
!ll&&!rl&&r
11133
MC/DC100%2/2
@rest_args >= 2 and not $rest_args[0] =~ /^(name|namespace|propagationPolicy)$/
@rest_args >= 2 not $rest_args[0] =~ /^(name|namespace|propagationPolicy)$/
Truth table100%3/3
A and not(B)
A= @rest_args >= 2B= not $rest_args[0] =~ /^(name|namespace|propagationPolicy)$/
ABresult
0X0
100
111
770 33 $args{name} = shift @rest_args;
771 33 ▶ return Future->fail("Invalid arguments to delete()") if @rest_args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rest_args % 2 0 33 33
772 33 %args = (%args, @rest_args);
773 } elsif (@rest_args % 2 == 0) {
774 11 %args = @rest_args;
775 } else {
776 1 return Future->fail("Invalid arguments to delete()");
777 }
778  
779 57 ($class, my $error) = $self->_resolve_class($class_or_object);
780 57 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 10 47 57
781 47 ▶ $name = delete $args{name} or return Future->fail("name required for delete");
Branch: 1 branch
BranchTrueFalseTotal
$name = delete $args{"name"} or return "Future"->fail("name required for delete") 45 2 47
782 45 $namespace = delete $args{namespace};
783 45 %options = %args;
784 45 @known = qw( name namespace propagationPolicy );
785 }
786  
787 80 my $policy = delete $options{propagationPolicy};
788 80 my $unknown = $self->_unknown_argument_error('delete', \%options, @known);
789 80 ▶ return Future->fail($unknown) if defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
if defined $unknown 4 76 80
790 76 my $policy_error = $self->_propagation_policy_error('delete', $policy);
791 76 ▶ return Future->fail($policy_error) if defined $policy_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $policy_error 3 73 76
792  
793 # A reference in the name position of the class form (delete('Pod',
794 # {name => 'web'})) would otherwise be stringified straight into the path
795 # (k70); the object form's name comes from metadata and is always a string.
796 73 ▶ if (my $name_error = $self->_resource_name_error($name)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name_error = $self->_resource_name_error($name)) 4 69 73
797 4 return Future->fail($name_error);
798 }
799  
800 69 my ($path, $error) = $self->_request_path($class, $class_or_object,
801 name => $name, namespace => $namespace);
802 69 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 5 64 69
803 return $self->_request_unchecked('DELETE', $path,
804 defined $policy ? (parameters => { propagationPolicy => $policy }) : (),
805 64 ▶ )->then(sub { Future->done($class, @_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
defined $policy ? : 35 29 64
806 }
807  
808 # One request through the Kubernetes::REST seam, resolving with the unchecked
809 # Kubernetes::REST::HTTPResponse -- for ensure() and ensure_only(), which
810 # branch on the status code (404 absent, 409 conflict), directly or through
811 # _list_request and _delete_request. check_response would fold that code into
812 # an error string it could only be read back out of with a regex.
813 252 ▶sub _request_unchecked {
Subroutine _request_unchecked: called CC=1 SCAR=0.0
814 252 my ($self, $method, $path, %opts) = @_;
815 252 return $self->_do_request($self->_rest->prepare_request($method, $path, %opts));
816 }
817  
818 # The Future for a response: done with it when Kubernetes::REST's
819 # check_response accepts it, failed the way Future's convention has it when
820 # it does not (status >= 400) - ->fail($error, 'http', $response). $error is
821 # exactly what check_response throws: the message string, or the error object
822 # of a Kubernetes::REST that has one; $response lets a caller branch on
823 # ->status (404 already gone, 409 conflict) instead of parsing the text.
824 # $context names the operation in the message, as for check_response.
825 350 ▶sub _checked_response {
Subroutine _checked_response: called CC=2 SCAR=6.9
826 350 my ($self, $response, $context) = @_;
827 return Future->done($response)
828 350 ▶ if eval { $self->_rest->check_response($response, $context); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->_rest->check_response($response, $context); 1 } } 288 62 350
829 62 return Future->fail($@, http => $response);
830 }
831  
832 # _do_request, then _checked_response: resolves with the response, or fails
833 # as above.
834 147 ▶sub _checked_request {
Subroutine _checked_request: called CC=1 SCAR=0.0
835 147 my ($self, $req, $context) = @_;
836 147 ▶ return $self->_do_request($req)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
837 147 my ($response) = @_;
838 147 return $self->_checked_response($response, $context);
839 147 });
840 }
841  
842 # Shared hashref handling for ensure() and ensure_only(): turns a manifest into
843 # a typed object. A manifest's apiVersion is authoritative - with one, the
844 # class is resolved as that exact group/version/Kind, and an apiVersion no
845 # class serves croaks instead of falling back to the version the bare Kind
846 # happens to map to (HorizontalPodAutoscaler alone means autoscaling/v2, a
847 # different endpoint and schema than an autoscaling/v1 manifest). Without an
848 # apiVersion the bare Kind resolves as it always did. Either way the class
849 # must be usable (_usable_class): one that does not load croaks with its load
850 # error. The class is resolved here, so it goes to struct_to_object with a
851 # '+', which IO::K8s takes as that exact class: struct_to_object resolves a
852 # plain name again, and a single-segment class of the caller's own ('+Gizmo'
853 # in the resource_map, which expand_class returns as 'Gizmo') reads to it as
854 # the Kind Gizmo - IO::K8s::Gizmo, or whatever class the map gives that Kind.
855 # $label only appears in croak messages.
856 26 ▶sub _manifest_to_object {
Subroutine _manifest_to_object: called CC=6 SCAR=17.9
857 26 my ($self, $label, $manifest) = @_;
858 26 ▶ my $kind = $manifest->{kind} or croak "$label: hashref must have 'kind'";
Branch: 1 branch
BranchTrueFalseTotal
my $kind = $manifest->{"kind"} or croak("${label}: hashref must have 'kind'") 25 1 26
859 25 my $api_version = $manifest->{apiVersion};
860 25 my $rest = $self->_rest;
861  
862 25 ▶ return $rest->k8s->struct_to_object('+' . $self->expand_class($kind), $manifest)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version and length $api_version 8 17 25
Condition100%3/3
defined $api_version and length $api_version
!ll&&!rl&&r
7117
MC/DC100%2/2
defined $api_version and length $api_version
defined $api_version length $api_version
Truth table100%3/3
A and B
A= defined $api_versionB= length $api_version
ABresult
0X0
100
111
863 unless defined $api_version && length $api_version;
864  
865 17 ▶ my $resolved = $rest->expand_class($kind, $api_version)
Condition100%3/3
$rest->expand_class($kind, $api_version) // croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
l!l&&r!l&&!r
1421
MC/DC0%0/2
$rest->expand_class($kind, $api_version) // croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
$rest->expand_class($kind, $api_version) croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
Truth table33%1/3
A // B
A= $rest->expand_class($kind, $api_version)B= croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
ABresult
1X1
011
000
866 // croak "$label: no IO::K8s class for apiVersion '$api_version', kind '$kind'"
867 . " (add it to resource_map if it is a CRD)";
868 14 my ($class, $error) = $self->_usable_class("$api_version/$kind", $resolved);
869 14 ▶ croak "$label: $error" unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 1 13 14
870 13 return $rest->k8s->struct_to_object('+' . $class, $manifest);
871 }
872  
873 # The apiVersion and Kind an object is an instance of, for ensure() and
874 # ensure_only() to tell resources apart by. A typed object answers from its
875 # class (api_version(), kind()); IO::K8s::Unstructured from its instance data,
876 # since its class name says nothing about what it holds. The last segment of a
877 # class name is not enough on its own: a CRD is free to reuse a built-in Kind
878 # name in its own group. Mirrors the private helper of the same name in
879 # Kubernetes::REST, which is not part of its public seam.
880 124 ▶sub _api_version_and_kind {
Subroutine _api_version_and_kind: called CC=6 SCAR=18.4
881 124 my ($self, $object) = @_;
882 124 ▶ my $api_version = ref($object) eq 'IO::K8s::Unstructured' ? $object->apiVersion
Branch: 2 branches
BranchTrueFalseTotal
ref $object eq 'IO::K8s::Unstructured' ? : 18 106 124
$object->can('api_version') ? : 106 0 106
883 : $object->can('api_version') ? $object->api_version
884 : undef;
885 124 ▶ my $kind = $object->can('kind') ? $object->kind : undef;
Branch: 1 branch
BranchTrueFalseTotal
$object->can('kind') ? : 124 0 124
886 124 ▶ ($kind = ref $object) =~ s/.*::// unless defined $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind 2 122 124
887 124 ▶ return ($api_version // '', $kind);
Condition50%1/2
$api_version // ""
l!l
1240
MC/DC0%0/1
$api_version // ""
$api_version
Truth table50%1/2
A
A= $api_version
Aresult
11
00
888 }
889  
890 87 ▶sub ensure {
Subroutine ensure: called CC=10 SCAR=23.1
Pod documented
891 87 my ($self, $object) = @_;
892  
893 87 my $rest = $self->_rest;
894 87 ▶ $object = $self->_manifest_to_object('ensure', $object) if ref($object) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $object eq "HASH" 20 67 87
895 78 ▶ croak "ensure requires an IO::K8s object or hashref" unless blessed($object);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($object) 0 78 78
896  
897 78 my ($class, $error) = $self->_object_class('ensure', $object);
898 78 ▶ croak $error unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 2 76 78
899 76 my ($api_version, $kind) = $self->_api_version_and_kind($object);
900 # The special cases below are the built-in core v1 PersistentVolumeClaim
901 # and batch/v1 Job only. The apiVersion is compared exactly, not just its
902 # group: the Job branch reads batch/v1's status fields and deletes what it
903 # takes for a failed Job, so an apiVersion it was not written for falls
904 # through to the plain update, where a mismatch fails loudly instead.
905 76 ▶ my $is_pvc = $api_version eq 'v1' && $kind eq 'PersistentVolumeClaim';
Condition100%3/3
$api_version eq 'v1' && $kind eq 'PersistentVolumeClaim'
!ll&&!rl&&r
38353
MC/DC100%2/2
$api_version eq 'v1' && $kind eq 'PersistentVolumeClaim'
$api_version eq 'v1' $kind eq 'PersistentVolumeClaim'
Truth table100%3/3
A && B
A= $api_version eq 'v1'B= $kind eq 'PersistentVolumeClaim'
ABresult
0X0
100
111
906 76 ▶ my $is_job = $api_version eq 'batch/v1' && $kind eq 'Job';
Condition66%2/3
$api_version eq 'batch/v1' && $kind eq 'Job'
!ll&&!rl&&r
6709
MC/DC50%1/2
$api_version eq 'batch/v1' && $kind eq 'Job'
$api_version eq 'batch/v1' $kind eq 'Job'
Truth table66%2/3
A && B
A= $api_version eq 'batch/v1'B= $kind eq 'Job'
ABresult
0X0
100
111
907 76 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 76 0 76
908 76 ▶ my $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $metadata->name or croak("object must have metadata.name") 76 0 76
909 76 my $namespace = $metadata->namespace;
910 76 (my $path, $error) = $self->_request_path($class, $object,
911 name => $name, namespace => $namespace);
912 76 ▶ croak $error unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 5 71 76
913 71 (my $collection, $error) = $self->_request_path($class, $object, namespace => $namespace);
914 71 ▶ croak $error unless defined $collection;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $collection 0 71 71
915  
916 # GET the object as the server has it now; $context names the step.
917 13 ▶ my $fetch = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
918 13 my ($context) = @_;
919 return $self->_checked_request($rest->prepare_request('GET', $path), "$context $kind/$name")
920 11 ▶ ->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
921 11 my ($response) = @_;
922 11 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
923 13 });
924 71 };
925  
926 # PUT at the server's resourceVersion. A 409 means the object changed
927 # between GET and PUT: fetch it once more and retry once, no further.
928 20 ▶ my $replace = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
929 20 my ($existing) = @_;
930 20 $metadata->resourceVersion($existing->metadata->resourceVersion);
931 20 ▶ return $self->_request_unchecked('PUT', $path, body => $object->TO_JSON)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
932 20 my ($response) = @_;
933 20 ▶ if ($response->status == 409) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->status == 409) 7 13 20
934 5 ▶ return $fetch->('ensure refetch')->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
935 5 my ($current) = @_;
936 5 $metadata->resourceVersion($current->metadata->resourceVersion);
937 5 return $self->update($object);
938 7 });
939 }
940 10 ▶ return $self->_checked_response($response, "update $class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
941 10 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
942 13 });
943 20 });
944 71 };
945  
946 # The object as the server has it, however ensure found out it exists.
947 32 ▶ my $apply_to_existing = sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
948 32 my ($existing) = @_;
949  
950 # An existing claim is never rewritten.
951 32 ▶ return Future->done($existing) if $is_pvc;
Branch: 1 branch
BranchTrueFalseTotal
if $is_pvc 3 29 32
952  
953 # A Job's pod template is immutable: a running or succeeded Job stays,
954 # any other is replaced - deleted with its Pods (Background), which
955 # the API server's default for a Job would orphan. A failing delete
956 # does not stop the create. The status is read from TO_JSON, not
957 # status(): an IO::K8s::Unstructured Job has no status accessor.
958 29 ▶ if ($is_job) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_job) 9 20 29
959 9 ▶ my $status = $existing->TO_JSON->{status} || {};
Condition50%1/2
$existing->TO_JSON->{'status'} || {}
l!l
90
MC/DC0%0/1
$existing->TO_JSON->{'status'} || {}
$existing->TO_JSON->{'status'}
Truth table50%1/2
A
A= $existing->TO_JSON->{'status'}
Aresult
11
00
960 return Future->done($existing)
961 9 ▶ if $status->{succeeded} || $status->{active};
Branch: 1 branch
BranchTrueFalseTotal
if $status->{"succeeded"} or $status->{"active"} 4 5 9
Condition100%3/3
$status->{"succeeded"} or $status->{"active"}
l!l&&r!l&&!r
225
MC/DC100%2/2
$status->{"succeeded"} or $status->{"active"}
$status->{"succeeded"} $status->{"active"}
Truth table100%3/3
A or B
A= $status->{"succeeded"}B= $status->{"active"}
ABresult
1X1
011
000
962 5 ▶ return Future->call(sub { $self->delete($existing, propagationPolicy => 'Background') })
Subroutine __ANON__: called CC=1 SCAR=0.0
963 1 ▶ ->else(sub { Future->done })
Subroutine __ANON__: called CC=1 SCAR=0.0
964 5 ▶ ->then(sub { $self->create($object) });
Subroutine __ANON__: called CC=1 SCAR=0.0
965 }
966  
967 20 return $replace->($existing);
968 71 };
969  
970 # POST. A 409 means it was created by someone else after our GET: from
971 # there on it is an existing object like any other, special cases
972 # included - a Job must not get a PUT onto its immutable Pod template.
973 40 ▶ my $create = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
974 40 ▶ return $self->_request_unchecked('POST', $collection, body => $object->TO_JSON)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
975 40 my ($response) = @_;
976 40 ▶ return $fetch->('ensure post-409 get')->then($apply_to_existing)
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 409 6 34 40
977 if $response->status == 409;
978 32 ▶ return $self->_checked_response($response, "create $class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
979 32 return Future->done($rest->inflate_object($self->_exact_class($class), $response));
980 34 });
981 40 });
982 71 };
983  
984 71 ▶ return $self->_request_unchecked('GET', $path)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
985 71 my ($response) = @_;
986 71 ▶ return $create->() if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 40 31 71
987 26 ▶ return $self->_checked_response($response, "ensure get $kind/$name")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
988 26 return $apply_to_existing->($rest->inflate_object($self->_exact_class($class), $response));
989 31 });
990 71 });
991 }
992  
993  
994 34 ▶sub ensure_all {
Subroutine ensure_all: called CC=2 SCAR=6.9
Pod documented
995 34 my ($self, @objects) = @_;
996  
997 # Strictly one after another: object N+1 is only started once object N
998 # is done, so a later object may rely on an earlier one (a Namespace and
999 # what lives in it). Any error, a croak from ensure() included, fails
1000 # the chain and nothing after it is started.
1001 34 my @results;
1002 34 my $f = Future->done;
1003 34 for my $object (@objects) {
1004 31 ▶ $f = $f->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1005 31 return $self->ensure($object);
1006 23 ▶ })->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1007 23 push @results, @_;
1008 23 return Future->done;
1009 31 });
1010 }
1011  
1012 34 ▶ return $f->then(sub { Future->done(@results) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1013 }
1014  
1015  
1016 31 ▶sub ensure_only {
Subroutine ensure_only: called CC=11 SCAR=24.0
Pod documented
1017 31 my ($self, @args) = @_;
1018  
1019 # Before anything is applied: an odd list drops a value (no objects
1020 # prunes everything carrying the label), namespace for namespaces would
1021 # prune at cluster scope only.
1022 31 ▶ croak "Invalid arguments to ensure_only()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 2 29 31
1023 29 my %args = @args;
1024 29 my $unknown = $self->_unknown_argument_error('ensure_only', \%args,
1025 qw( label objects kinds namespaces propagationPolicy ));
1026 29 ▶ croak $unknown if defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
if defined $unknown 2 27 29
1027  
1028 27 my $rest = $self->_rest;
1029 27 ▶ my $label = $args{label} or croak "ensure_only requires 'label'";
Branch: 1 branch
BranchTrueFalseTotal
my $label = $args{"label"} or croak("ensure_only requires 'label'") 26 1 27
1030 # Background unless told otherwise: the API server's own default leaves
1031 # the Pods of a pruned Job behind.
1032 26 ▶ my $policy = $args{propagationPolicy} // 'Background';
Condition100%2/2
$args{"propagationPolicy"} // "Background"
l!l
224
MC/DC100%1/1
$args{"propagationPolicy"} // "Background"
$args{"propagationPolicy"}
Truth table100%2/2
A
A= $args{"propagationPolicy"}
Aresult
11
00
1033 26 my $policy_error = $self->_propagation_policy_error('ensure_only', $policy);
1034 26 ▶ croak $policy_error if defined $policy_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $policy_error 1 25 26
1035 25 ▶ my @objects = @{ $args{objects} || [] };
Condition50%1/2
$args{'objects'} || []
l!l
250
MC/DC0%0/1
$args{'objects'} || []
$args{'objects'}
Truth table50%1/2
A
A= $args{'objects'}
Aresult
11
00
1036 25 ▶ my @kinds = @{ $args{kinds} || [] };
Condition50%1/2
$args{'kinds'} || []
l!l
250
MC/DC0%0/1
$args{'kinds'} || []
$args{'kinds'}
Truth table50%1/2
A
A= $args{'kinds'}
Aresult
11
00
1037 25 ▶ my @namespaces = @{ $args{namespaces} || [undef] };
Condition100%2/2
$args{'namespaces'} || [undef]
l!l
223
MC/DC100%1/1
$args{'namespaces'} || [undef]
$args{'namespaces'}
Truth table100%2/2
A
A= $args{'namespaces'}
Aresult
11
00
1038  
1039 # Every hashref is resolved before the first request, so one that cannot
1040 # be (no kind, an apiVersion no class serves) stops the whole call.
1041 25 for my $object (@objects) {
1042 18 ▶ $object = $self->_manifest_to_object('ensure_only', $object)
Branch: 1 branch
BranchTrueFalseTotal
if ref $object eq "HASH" 6 12 18
1043 if ref($object) eq 'HASH';
1044 }
1045  
1046 # (group, Kind, namespace, name), taken from the object on both sides -
1047 # never from the kinds entry, which may be qualified ('autoscaling/v1/...')
1048 # and would then match nothing, deleting the objects just applied. Group
1049 # and Kind come from _api_version_and_kind: class-derived for a typed
1050 # object, instance data for IO::K8s::Unstructured. The group keeps the same
1051 # Kind name in two groups apart (Istio's and the Gateway API's Gateway);
1052 # the core group is ''. No version in the key: the same resource listed
1053 # through another version's class is still the same resource.
1054 46 ▶ my $key_of = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1055 46 my ($object) = @_;
1056 46 my ($api_version, $kind) = $self->_api_version_and_kind($object);
1057 46 my ($group) = $api_version =~ m{\A(.*)/[^/]*\z};
1058 46 my $metadata = $object->metadata;
1059 46 ▶ return join("\0", $group // '', $kind, $metadata->namespace // '', $metadata->name);
Condition75%3/4
$group // ""
l!l
2422
$metadata->namespace // ""
l!l
460
MC/DC100%1/1
$group // ""
$group
MC/DC0%0/1
$metadata->namespace // ""
$metadata->namespace
Truth table100%2/2
A
A= $group
Aresult
11
00
Truth table50%1/2
A
A= $metadata->namespace
Aresult
11
00
1060 24 };
1061  
1062 # A failed list or delete leaves stale objects behind, so it is reported
1063 # rather than swallowed - but only a real failure: a 404 on the list means
1064 # the cluster does not serve the Kind, a 404 on the delete that the object
1065 # is already gone. The status comes from the unchecked response, never
1066 # from the text of an error. A caught croak already ends in its own
1067 # location, which carp adds again, so the reason drops it.
1068 11 ▶ my $where = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1069 11 my ($namespace) = @_;
1070 11 ▶ return defined $namespace ? "in namespace '$namespace'" : 'at cluster scope';
Branch: 1 branch
BranchTrueFalseTotal
defined $namespace ? : 10 1 11
1071 24 };
1072 11 ▶ my $reason_of = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1073 11 my ($error) = @_;
1074 11 ▶ $error = defined $error ? "$error" : 'unknown error';
Branch: 1 branch
BranchTrueFalseTotal
defined $error ? : 11 0 11
1075 11 $error =~ s/\s+\z//;
1076 11 $error =~ s/ at \S+ line \d+\.\z//;
1077 11 return $error;
1078 24 };
1079 18 ▶ my $prune = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1080 18 my ($item) = @_;
1081 18 ▶ return Future->call(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1082 18 $self->_delete_request($item, propagationPolicy => $policy);
1083 18 ▶ })->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1084 18 my ($class, $response) = @_;
1085 18 ▶ return Future->done if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 1 17 18
1086 17 return $self->_checked_response($response, "delete $class");
1087 2 ▶ })->else(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1088 2 my ($error) = @_;
1089 2 my (undef, $kind) = $self->_api_version_and_kind($item);
1090 2 carp "ensure_only: cannot delete $kind '" . $item->metadata->name . "' "
1091 . $where->($item->metadata->namespace) . ': ' . $reason_of->($error);
1092 2 return Future->done;
1093 18 });
1094 24 };
1095  
1096 24 ▶ return $self->ensure_all(@objects)->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1097 24 my @applied = @_;
1098 24 my %expected = map { $key_of->($_) => 1 } @objects;
1099  
1100 # One Kind x namespace after another, each delete after the one
1101 # before, and on past every failure.
1102 24 my $f = Future->done;
1103 24 for my $kind (@kinds) {
1104 28 for my $namespace (@namespaces) {
1105 32 ▶ $f = $f->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1106 32 ▶ return Future->call(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1107 32 ▶ $self->_list_request($kind,
Branch: 1 branch
BranchTrueFalseTotal
defined $namespace ? : 29 3 32
1108 labelSelector => $label,
1109 (defined $namespace ? (namespace => $namespace) : ()),
1110 );
1111 27 ▶ })->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1112 27 my ($class, $response) = @_;
1113 27 ▶ return Future->done if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 1 26 27
1114 22 ▶ return $self->_checked_response($response, "list $kind")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1115 22 return Future->done($rest->inflate_list($self->_exact_class($class), $response));
1116 26 });
1117 9 ▶ })->else(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1118 9 my ($error) = @_;
1119 9 carp "ensure_only: cannot list $kind " . $where->($namespace)
1120 . ', nothing pruned there: ' . $reason_of->($error);
1121 8 return Future->done;
1122 31 ▶ })->then(sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1123 31 my ($list) = @_;
1124 31 my $deletes = Future->done;
1125 31 ▶ return $deletes unless $list;
Branch: 1 branch
BranchTrueFalseTotal
unless $list 9 22 31
1126 22 for my $item (@{ $list->items }) {
1127 30 ▶ next if $expected{ $key_of->($item) };
Branch: 1 branch
BranchTrueFalseTotal
if $expected{&$key_of($item)} 12 18 30
1128 18 ▶ $deletes = $deletes->then(sub { $prune->($item) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1129 }
1130 22 return $deletes;
1131 32 });
1132 32 });
1133 }
1134 }
1135  
1136 24 ▶ return $f->then(sub { Future->done(@applied) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1137 24 });
1138 }
1139  
1140  
1141 70 ▶sub log {
Subroutine log: called CC=15 SCAR=27.1
Pod documented
1142 70 my ($self, $short_class, @rest_args) = @_;
1143  
1144 70 my $rest = $self->_rest;
1145  
1146 # Support: log('Pod', 'name', ...) and log('Pod', name => 'name', ...)
1147 70 my ($arg_error, %args) = $self->_named_args('log', \@rest_args, qw( name namespace
1148 container follow tailLines sinceSeconds sinceTime timestamps previous limitBytes
1149 on_line ));
1150 70 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 40 30 70
1151  
1152 30 ▶ return Future->fail("name required for log") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 28 30
1153  
1154 28 my $on_line = delete $args{on_line};
1155 28 my $container = delete $args{container};
1156 28 my $follow = delete $args{follow};
1157 28 my $tail_lines = delete $args{tailLines};
1158 28 my $since_seconds = delete $args{sinceSeconds};
1159 28 my $since_time = delete $args{sinceTime};
1160 28 my $timestamps = delete $args{timestamps};
1161 28 my $previous = delete $args{previous};
1162 28 my $limit_bytes = delete $args{limitBytes};
1163  
1164 28 my ($class, $error) = $self->_resolve_class($short_class);
1165 28 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 11 17 28
1166 17 (my $path, $error) = $self->_request_path($class, $short_class, %args);
1167 17 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 15 17
1168 15 $path .= '/log';
1169  
1170 15 my %params;
1171 15 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 2 13 15
1172 15 ▶ $params{follow} = 'true' if $follow;
Branch: 1 branch
BranchTrueFalseTotal
if $follow 6 9 15
1173 15 ▶ $params{tailLines} = $tail_lines if defined $tail_lines;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tail_lines 2 13 15
1174 15 ▶ $params{sinceSeconds} = $since_seconds if defined $since_seconds;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since_seconds 2 13 15
1175 15 ▶ $params{sinceTime} = $since_time if defined $since_time;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since_time 0 15 15
1176 15 ▶ $params{timestamps} = 'true' if $timestamps;
Branch: 1 branch
BranchTrueFalseTotal
if $timestamps 2 13 15
1177 15 ▶ $params{previous} = 'true' if $previous;
Branch: 1 branch
BranchTrueFalseTotal
if $previous 2 13 15
1178 15 ▶ $params{limitBytes} = $limit_bytes if defined $limit_bytes;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit_bytes 2 13 15
1179  
1180 15 ▶ if ($on_line) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_line) 7 8 15
1181 7 my $req = $rest->prepare_request('GET', $path, parameters => \%params);
1182 7 my $buffer = '';
1183  
1184 5 ▶ return $self->_do_streaming_request($req, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1185 5 my ($chunk) = @_;
1186 5 for my $event ($rest->process_log_chunk(\$buffer, $chunk)) {
1187 6 $on_line->($event);
1188 }
1189 7 ▶ })->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1190 7 my ($response) = @_;
1191 7 return $self->_checked_response($response, "log $short_class");
1192 4 ▶ })->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1193 4 ▶ if (length $buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $buffer) 1 3 4
1194 1 $on_line->(Kubernetes::REST::LogEvent->new(line => $buffer));
1195 }
1196 4 return Future->done(undef);
1197 7 });
1198 }
1199  
1200 8 ▶ my $req = $rest->prepare_request('GET', $path,
Branch: 1 branch
BranchTrueFalseTotal
%params ? : 1 7 8
1201 %params ? (parameters => \%params) : (),
1202 );
1203 4 ▶ return $self->_checked_request($req, "log $short_class")->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1204 4 my ($response) = @_;
1205 4 return Future->done($response->content);
1206 8 });
1207 }
1208  
1209  
1210 74 ▶sub port_forward {
Subroutine port_forward: called CC=15 SCAR=27.3
Pod documented
1211 74 my ($self, $short_class, @rest_args) = @_;
1212  
1213 74 my $rest = $self->_rest;
1214  
1215 # Support: port_forward('Pod', 'name', ...) and port_forward('Pod', name => 'name', ...)
1216 74 my ($arg_error, %args) = $self->_named_args('port_forward', \@rest_args,
1217 qw( name namespace ports subprotocol on_open on_frame on_data on_port_error
1218 on_close on_error ));
1219 74 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 37 37 74
1220  
1221 37 ▶ return Future->fail("name required for port_forward") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 35 37
1222  
1223 35 my $ports = delete $args{ports};
1224 35 ▶ return Future->fail("ports required for port_forward") unless defined $ports;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ports 1 34 35
1225 34 ▶ $ports = [$ports] unless ref($ports) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ports eq "ARRAY" 0 34 34
1226 34 ▶ return Future->fail("ports required for port_forward") unless @$ports;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ports 0 34 34
1227 34 for my $p (@$ports) {
1228 42 ▶ return Future->fail("invalid port '$p' for port_forward")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535 1 41 42
Condition66%6/9
defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535
!ll&&!rl&&r
1041
defined $p and $p =~ /^\d+$/ and $p > 0
!ll&&!rl&&r
1041
defined $p and $p =~ /^\d+$/
!ll&&!rl&&r
0141
MC/DC25%1/4
defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535
defined $p $p =~ /^\d+$/ $p > 0 $p <= 65535
Truth table40%2/5
A and B and C and D
A= defined $pB= $p =~ /^\d+$/C= $p > 0D= $p <= 65535
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1229 unless defined($p) && $p =~ /^\d+$/ && $p > 0 && $p <= 65535;
1230 }
1231  
1232 33 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
330
MC/DC100%1/1
delete $args{"subprotocol"} // "v4.channel.k8s.io"
delete $args{"subprotocol"}
Truth table100%2/2
A
A= delete $args{"subprotocol"}
Aresult
11
00
1233 33 my $on_open = delete $args{on_open};
1234 33 my $on_frame = delete $args{on_frame};
1235 33 my $on_data = delete $args{on_data};
1236 33 my $on_port_error = delete $args{on_port_error};
1237 33 my $on_close = delete $args{on_close};
1238 33 my $on_error = delete $args{on_error};
1239  
1240 33 my ($class, $error) = $self->_resolve_class($short_class);
1241 33 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 10 23 33
1242 23 (my $path, $error) = $self->_request_path($class, $short_class, %args);
1243 23 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 21 23
1244 21 $path .= '/portforward';
1245  
1246 # Keep compatibility with Kubernetes::REST >= 1.100 by expanding repeated
1247 # ports query params here instead of relying on arrayref parameter support.
1248 21 my $query = join('&', map { "ports=$_" } @$ports);
1249 21 ▶ my $path_with_query = $query ? "$path?$query" : $path;
Branch: 1 branch
BranchTrueFalseTotal
$query ? : 21 0 21
1250  
1251 21 my $req = $rest->prepare_request('GET', $path_with_query,
1252 headers => {
1253 Accept => '*/*',
1254 Connection => 'Upgrade',
1255 Upgrade => 'websocket',
1256 'Sec-WebSocket-Protocol' => $subprotocol,
1257 },
1258 );
1259  
1260 21 return $self->_do_duplex_request($req,
1261 caller => 'port_forward',
1262 ports => $ports,
1263 on_open => $on_open,
1264 on_frame => $on_frame,
1265 on_data => $on_data,
1266 on_port_error => $on_port_error,
1267 on_close => $on_close,
1268 on_error => $on_error,
1269 );
1270 }
1271  
1272  
1273 18 ▶sub port_forward_listen {
Subroutine port_forward_listen: called CC=19 SCAR=29.7
Pod documented
1274 18 my ($self, $short_class, @rest_args) = @_;
1275  
1276 18 my ($arg_error, %args) = $self->_named_args('port_forward_listen', \@rest_args,
1277 qw( name namespace ports host subprotocol on_error ));
1278 18 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 2 16 18
1279  
1280 16 ▶ return Future->fail("name required for port_forward_listen") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 15 16
1281  
1282 15 my $ports = delete $args{ports};
1283 15 ▶ return Future->fail("ports required for port_forward_listen")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ports eq "HASH" and %$ports 3 12 15
Condition100%3/3
ref $ports eq "HASH" and %$ports
!ll&&!rl&&r
2112
MC/DC100%2/2
ref $ports eq "HASH" and %$ports
ref $ports eq "HASH" %$ports
Truth table100%3/3
A and B
A= ref $ports eq "HASH"B= %$ports
ABresult
0X0
100
111
1284 unless ref($ports) eq 'HASH' && %$ports;
1285 12 my %seen_remote;
1286 12 for my $local (sort keys %$ports) {
1287 14 my $remote = $ports->{$local};
1288 14 ▶ return Future->fail("invalid local port '$local' for port_forward_listen")
Branch: 1 branch
BranchTrueFalseTotal
unless $local =~ /^\d+$/ and $local <= 65535 2 12 14
Condition100%3/3
$local =~ /^\d+$/ and $local <= 65535
!ll&&!rl&&r
1112
MC/DC100%2/2
$local =~ /^\d+$/ and $local <= 65535
$local =~ /^\d+$/ $local <= 65535
Truth table100%3/3
A and B
A= $local =~ /^\d+$/B= $local <= 65535
ABresult
0X0
100
111
1289 unless $local =~ /^\d+$/ && $local <= 65535;
1290 12 ▶ return Future->fail("invalid remote port '" . ($remote // 'undef') . "' for port_forward_listen")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $remote and $remote =~ /^\d+$/ and $remote > 0 and $remote <= 65535 2 10 12
Condition63%7/11
defined $remote and $remote =~ /^\d+$/ and $remote > 0 and $remote <= 65535
!ll&&!rl&&r
1110
defined $remote and $remote =~ /^\d+$/ and $remote > 0
!ll&&!rl&&r
0111
defined $remote and $remote =~ /^\d+$/
!ll&&!rl&&r
0012
$remote // "undef"
l!l
20
MC/DC50%2/4
defined $remote and $remote =~ /^\d+$/ and $remote > 0 and $remote <= 65535
defined $remote $remote =~ /^\d+$/ $remote > 0 $remote <= 65535
MC/DC0%0/1
$remote // "undef"
$remote
Truth table60%3/5
A and B and C and D
A= defined $remoteB= $remote =~ /^\d+$/C= $remote > 0D= $remote <= 65535
ABCDresult
0XXX0
10XX0
110X0
11100
11111
Truth table50%1/2
A
A= $remote
Aresult
11
00
1291 unless defined($remote) && $remote =~ /^\d+$/ && $remote > 0 && $remote <= 65535;
1292 return Future->fail("remote port '$remote' listed twice for port_forward_listen")
1293 10 ▶ if $seen_remote{$remote}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_remote{$remote}++ 1 9 10
1294 }
1295  
1296 7 my $loop = eval { $self->loop };
1297 7 ▶ return Future->fail("port_forward_listen requires Net::Async::Kubernetes to be added to an IO::Async::Loop")
Branch: 1 branch
BranchTrueFalseTotal
unless $loop 1 6 7
1298 unless $loop;
1299  
1300 6 my ($class, $error) = $self->_resolve_class($short_class);
1301 6 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 1 5 6
1302  
1303 my $listener = Net::Async::Kubernetes::PortForwardListener->new(
1304 kube => $self,
1305 host => $args{host} // '127.0.0.1',
1306 mappings => { %$ports },
1307 on_error => $args{on_error},
1308 forward_args => [
1309 $short_class,
1310 name => $args{name},
1311 (defined $args{namespace} ? (namespace => $args{namespace}) : ()),
1312 5 ▶ (defined $args{subprotocol} ? (subprotocol => $args{subprotocol}) : ()),
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'namespace'} ? : 1 4 5
defined $args{'subprotocol'} ? : 0 5 5
Condition50%1/2
$args{"host"} // "127.0.0.1"
l!l
05
MC/DC0%0/1
$args{"host"} // "127.0.0.1"
$args{"host"}
Truth table50%1/2
A
A= $args{"host"}
Aresult
11
00
1313 ],
1314 );
1315 5 return $listener->start;
1316 }
1317  
1318  
1319 87 ▶sub exec {
Subroutine exec: called CC=24 SCAR=31.8
Pod documented
1320 87 my ($self, $short_class, @rest_args) = @_;
1321  
1322 87 my $rest = $self->_rest;
1323  
1324 # Support: exec('Pod', 'name', ...) and exec('Pod', name => 'name', ...)
1325 87 my ($arg_error, %args) = $self->_named_args('exec', \@rest_args, qw( name namespace command
1326 container stdin stdout stderr tty subprotocol on_open on_frame on_close on_error ));
1327 87 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 46 41 87
1328  
1329 41 ▶ return Future->fail("name required for exec") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 39 41
1330  
1331 39 my $command = delete $args{command};
1332 39 ▶ return Future->fail("command required for exec") unless defined $command;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $command 1 38 39
1333 38 ▶ $command = [$command] unless ref($command) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $command eq "ARRAY" 1 37 38
1334 38 ▶ return Future->fail("command required for exec") unless @$command;
Branch: 1 branch
BranchTrueFalseTotal
unless @$command 1 37 38
1335 37 for my $part (@$command) {
1336 99 ▶ return Future->fail("invalid command element for exec")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part and not ref $part and length $part 1 98 99
Condition66%4/6
defined $part and not ref $part and length $part
!ll&&!rl&&r
1098
defined $part and not ref $part
!ll&&!rl&&r
1098
MC/DC33%1/3
defined $part and not ref $part and length $part
defined $part not ref $part length $part
Truth table50%2/4
A and not(B) and C
A= defined $partB= not ref $partC= length $part
ABCresult
0XX0
10X0
1100
1111
1337 unless defined($part) && !ref($part) && length $part;
1338 }
1339  
1340 36 my $container = delete $args{container};
1341 36 ▶ my $stdin = delete($args{stdin}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'stdin'} ? : 12 24 36
1342 36 ▶ my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stdout'} ? : 20 16 36
delete $args{'stdout'} ? : 10 10 20
1343 36 ▶ my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stderr'} ? : 21 15 36
delete $args{'stderr'} ? : 19 2 21
1344 36 ▶ my $tty = delete($args{tty}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'tty'} ? : 2 34 36
1345  
1346 36 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
234
MC/DC100%1/1
delete $args{"subprotocol"} // "v4.channel.k8s.io"
delete $args{"subprotocol"}
Truth table100%2/2
A
A= delete $args{"subprotocol"}
Aresult
11
00
1347 36 my $on_open = delete $args{on_open};
1348 36 my $on_frame = delete $args{on_frame};
1349 36 my $on_close = delete $args{on_close};
1350 36 my $on_error = delete $args{on_error};
1351  
1352 36 my ($class, $error) = $self->_resolve_class($short_class);
1353 36 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 26 10 36
1354 10 (my $path, $error) = $self->_request_path($class, $short_class, %args);
1355 10 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 8 10
1356 8 $path .= '/exec';
1357  
1358 8 ▶ my %params = (
Branch: 4 branches
BranchTrueFalseTotal
$stdin ? : 4 4 8
$stdout ? : 6 2 8
$stderr ? : 6 2 8
$tty ? : 2 6 8
1359 command => $command,
1360 stdin => $stdin ? 'true' : 'false',
1361 stdout => $stdout ? 'true' : 'false',
1362 stderr => $stderr ? 'true' : 'false',
1363 tty => $tty ? 'true' : 'false',
1364 );
1365 8 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 4 4 8
1366  
1367 8 my $req = $rest->prepare_request('GET', $path,
1368 parameters => \%params,
1369 headers => {
1370 Accept => '*/*',
1371 Connection => 'Upgrade',
1372 Upgrade => 'websocket',
1373 'Sec-WebSocket-Protocol' => $subprotocol,
1374 },
1375 );
1376  
1377 8 return $self->_do_duplex_request($req,
1378 caller => 'exec',
1379 on_open => $on_open,
1380 on_frame => $on_frame,
1381 on_close => $on_close,
1382 on_error => $on_error,
1383 );
1384 }
1385  
1386  
1387 62 ▶sub attach {
Subroutine attach: called CC=17 SCAR=28.4
Pod documented
1388 62 my ($self, $short_class, @rest_args) = @_;
1389  
1390 62 my $rest = $self->_rest;
1391  
1392 # Support: attach('Pod', 'name', ...) and attach('Pod', name => 'name', ...)
1393 62 my ($arg_error, %args) = $self->_named_args('attach', \@rest_args, qw( name namespace
1394 container stdin stdout stderr tty subprotocol on_open on_frame on_close on_error ));
1395 62 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 42 20 62
1396  
1397 20 ▶ return Future->fail("name required for attach") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 18 20
1398  
1399 18 my $container = delete $args{container};
1400 18 ▶ my $stdin = delete($args{stdin}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'stdin'} ? : 3 15 18
1401 18 ▶ my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stdout'} ? : 2 16 18
delete $args{'stdout'} ? : 2 0 2
1402 18 ▶ my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stderr'} ? : 3 15 18
delete $args{'stderr'} ? : 0 3 3
1403 18 ▶ my $tty = delete($args{tty}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'tty'} ? : 2 16 18
1404  
1405 18 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
216
MC/DC100%1/1
delete $args{"subprotocol"} // "v4.channel.k8s.io"
delete $args{"subprotocol"}
Truth table100%2/2
A
A= delete $args{"subprotocol"}
Aresult
11
00
1406 18 my $on_open = delete $args{on_open};
1407 18 my $on_frame = delete $args{on_frame};
1408 18 my $on_close = delete $args{on_close};
1409 18 my $on_error = delete $args{on_error};
1410  
1411 18 my ($class, $error) = $self->_resolve_class($short_class);
1412 18 ▶ return Future->fail($error) unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 10 8 18
1413 8 (my $path, $error) = $self->_request_path($class, $short_class, %args);
1414 8 ▶ return Future->fail($error) unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 2 6 8
1415 6 $path .= '/attach';
1416  
1417 6 ▶ my %params = (
Branch: 4 branches
BranchTrueFalseTotal
$stdin ? : 3 3 6
$stdout ? : 6 0 6
$stderr ? : 3 3 6
$tty ? : 2 4 6
1418 stdin => $stdin ? 'true' : 'false',
1419 stdout => $stdout ? 'true' : 'false',
1420 stderr => $stderr ? 'true' : 'false',
1421 tty => $tty ? 'true' : 'false',
1422 );
1423 6 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 3 3 6
1424  
1425 6 my $req = $rest->prepare_request('GET', $path,
1426 parameters => \%params,
1427 headers => {
1428 Accept => '*/*',
1429 Connection => 'Upgrade',
1430 Upgrade => 'websocket',
1431 'Sec-WebSocket-Protocol' => $subprotocol,
1432 },
1433 );
1434  
1435 6 return $self->_do_duplex_request($req,
1436 caller => 'attach',
1437 on_open => $on_open,
1438 on_frame => $on_frame,
1439 on_close => $on_close,
1440 on_error => $on_error,
1441 );
1442 }
1443  
1444  
1445 38 ▶sub cp_to_pod {
Subroutine cp_to_pod: called CC=17 SCAR=30.8
Pod documented
1446 38 my ($self, $short_class, @rest_args) = @_;
1447  
1448 38 my $loop = eval { $self->loop };
1449 38 ▶ return Future->fail("cp_to_pod requires Net::Async::Kubernetes to be added to an IO::Async::Loop")
Branch: 1 branch
BranchTrueFalseTotal
unless $loop 1 37 38
1450 unless $loop;
1451  
1452 37 my ($arg_error, %args) = $self->_named_args('cp_to_pod', \@rest_args,
1453 qw( name namespace container local remote chunk_size ));
1454 37 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 24 13 37
1455  
1456 13 ▶ return Future->fail("name required for cp_to_pod") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 12 13
1457  
1458 12 my $local = delete $args{local};
1459 12 my $remote = delete $args{remote};
1460 12 ▶ return Future->fail("local path required for cp_to_pod") unless defined $local && length $local;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $local and length $local 0 12 12
Condition33%1/3
defined $local and length $local
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $local and length $local
defined $local length $local
Truth table33%1/3
A and B
A= defined $localB= length $local
ABresult
0X0
100
111
1461 12 ▶ return Future->fail("remote path required for cp_to_pod") unless defined $remote && length $remote;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $remote and length $remote 0 12 12
Condition33%1/3
defined $remote and length $remote
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $remote and length $remote
defined $remote length $remote
Truth table33%1/3
A and B
A= defined $remoteB= length $remote
ABresult
0X0
100
111
1462 12 ▶ return Future->fail("local file '$local' does not exist for cp_to_pod") unless -e $local;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $local 0 12 12
1463 12 ▶ return Future->fail("local path '$local' is not a file for cp_to_pod") unless -f $local;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $local 0 12 12
1464  
1465 12 ▶ my $chunk_size = delete($args{chunk_size}) // 64 * 1024;
Condition100%2/2
delete $args{"chunk_size"} // 65536
l!l
210
MC/DC100%1/1
delete $args{"chunk_size"} // 65536
delete $args{"chunk_size"}
Truth table100%2/2
A
A= delete $args{"chunk_size"}
Aresult
11
00
1466 12 ▶ return Future->fail("invalid chunk_size '$chunk_size' for cp_to_pod")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk_size and $chunk_size =~ /^\d+$/ and $chunk_size > 0 0 12 12
Condition33%2/6
defined $chunk_size and $chunk_size =~ /^\d+$/ and $chunk_size > 0
!ll&&!rl&&r
0012
defined $chunk_size and $chunk_size =~ /^\d+$/
!ll&&!rl&&r
0012
MC/DC0%0/3
defined $chunk_size and $chunk_size =~ /^\d+$/ and $chunk_size > 0
defined $chunk_size $chunk_size =~ /^\d+$/ $chunk_size > 0
Truth table25%1/4
A and B and C
A= defined $chunk_sizeB= $chunk_size =~ /^\d+$/C= $chunk_size > 0
ABCresult
0XX0
10X0
1100
1111
1467 unless defined($chunk_size) && $chunk_size =~ /^\d+$/ && $chunk_size > 0;
1468  
1469 12 ▶ open my $fh, '<:raw', $local
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $local or return "Future"->fail("cannot read local file '${local}' for cp_to_pod: $!") 12 0 12
1470 or return Future->fail("cannot read local file '$local' for cp_to_pod: $!");
1471 12 local $/ = undef;
1472 12 my $bytes = <$fh>;
1473 12 close $fh;
1474 12 ▶ $bytes = '' unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 12 12
1475  
1476 12 my $size = length($bytes);
1477 12 my $stderr = '';
1478 12 my $status_payload = '';
1479 12 my $done = $loop->new_future;
1480  
1481 return $self->exec($short_class, $args{name},
1482 namespace => $args{namespace},
1483 (defined($args{container}) ? (container => $args{container}) : ()),
1484 command => ['sh', '-c', 'head -c "$1" > "$2"', 'k8s-cp', $size, $remote],
1485 stdin => 1,
1486 stdout => 0,
1487 stderr => 1,
1488 tty => 0,
1489 2 ▶ on_frame => sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
1490 2 my ($channel, $payload) = @_;
1491 2 ▶ $stderr .= $payload if $channel == 2;
Branch: 1 branch
BranchTrueFalseTotal
if $channel == 2 0 2 2
1492 2 ▶ $status_payload .= $payload if $channel == 3;
Branch: 1 branch
BranchTrueFalseTotal
if $channel == 3 2 0 2
1493 },
1494 3 ▶ on_close => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1495 3 ▶ return if $done->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $done->is_ready 0 3 3
1496 3 ▶ if ($status_payload =~ /"status"\s*:\s*"Failure"/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($status_payload =~ /"status"\s*:\s*"Failure"/i) { } 1 2 3
elsif (not $status_payload =~ /"status"\s*:\s*"Success"/i) { } 1 1 2
1497 1 $done->fail("cp_to_pod failed: $status_payload");
1498 } elsif ($status_payload !~ /"status"\s*:\s*"Success"/i) {
1499 1 $done->fail("cp_to_pod failed: connection closed without a Success status, "
1500 . "the transfer may be incomplete");
1501 } else {
1502 1 $done->done({
1503 local => $local,
1504 remote => $remote,
1505 bytes => $size,
1506 stderr => $stderr,
1507 status => $status_payload,
1508 });
1509 }
1510 },
1511 0 ▶ on_error => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1512 0 my ($err) = @_;
1513 0 ▶ $done->fail("cp_to_pod transport error: $err") unless $done->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $done->is_ready 0 0 0
1514 },
1515 4 ▶ )->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1516 4 my ($session) = @_;
1517 return $self->_send_stdin_chunks($session, $bytes, $chunk_size)
1518 4 ▶ ->then(sub { return $done; });
Subroutine __ANON__: called CC=1 SCAR=0.0
1519 12 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'container'} ? : 1 11 12
1520 }
1521  
1522  
1523 37 ▶sub cp_from_pod {
Subroutine cp_from_pod: called CC=10 SCAR=24.0
Pod documented
1524 37 my ($self, $short_class, @rest_args) = @_;
1525  
1526 37 my $loop = eval { $self->loop };
1527 37 ▶ return Future->fail("cp_from_pod requires Net::Async::Kubernetes to be added to an IO::Async::Loop")
Branch: 1 branch
BranchTrueFalseTotal
unless $loop 1 36 37
1528 unless $loop;
1529  
1530 36 my ($arg_error, %args) = $self->_named_args('cp_from_pod', \@rest_args,
1531 qw( name namespace container local remote ));
1532 36 ▶ return Future->fail($arg_error) if defined $arg_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg_error 20 16 36
1533  
1534 16 ▶ return Future->fail("name required for cp_from_pod") unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 14 16
1535  
1536 14 my $local = delete $args{local};
1537 14 my $remote = delete $args{remote};
1538 14 ▶ return Future->fail("local path required for cp_from_pod") unless defined $local && length $local;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $local and length $local 0 14 14
Condition33%1/3
defined $local and length $local
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $local and length $local
defined $local length $local
Truth table33%1/3
A and B
A= defined $localB= length $local
ABresult
0X0
100
111
1539 14 ▶ return Future->fail("remote path required for cp_from_pod") unless defined $remote && length $remote;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $remote and length $remote 1 13 14
Condition66%2/3
defined $remote and length $remote
!ll&&!rl&&r
1013
MC/DC50%1/2
defined $remote and length $remote
defined $remote length $remote
Truth table66%2/3
A and B
A= defined $remoteB= length $remote
ABresult
0X0
100
111
1540 13 ▶ return Future->fail("local path '$local' is a directory for cp_from_pod") if -d $local;
Branch: 1 branch
BranchTrueFalseTotal
if -d $local 0 13 13
1541  
1542 13 my $stdout = '';
1543 13 my $stderr = '';
1544 13 my $status_payload = '';
1545 13 my $done = $loop->new_future;
1546  
1547 return $self->exec($short_class, $args{name},
1548 namespace => $args{namespace},
1549 (defined($args{container}) ? (container => $args{container}) : ()),
1550 command => ['cat', $remote],
1551 stdin => 0,
1552 stdout => 1,
1553 stderr => 1,
1554 tty => 0,
1555 9 ▶ on_frame => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1556 9 my ($channel, $payload) = @_;
1557 9 ▶ $stdout .= $payload if $channel == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $channel == 1 5 4 9
1558 9 ▶ $stderr .= $payload if $channel == 2;
Branch: 1 branch
BranchTrueFalseTotal
if $channel == 2 1 8 9
1559 9 ▶ $status_payload .= $payload if $channel == 3;
Branch: 1 branch
BranchTrueFalseTotal
if $channel == 3 3 6 9
1560 },
1561 4 ▶ on_close => sub {
Subroutine __ANON__: called CC=7 SCAR=20.9
1562 4 ▶ return if $done->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $done->is_ready 0 4 4
1563 4 ▶ if ($status_payload =~ /"status"\s*:\s*"Failure"/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status_payload =~ /"status"\s*:\s*"Failure"/i) 0 4 4
1564 0 $done->fail("cp_from_pod failed: $status_payload");
1565 0 return;
1566 }
1567 4 ▶ if ($status_payload !~ /"status"\s*:\s*"Success"/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($status_payload =~ /"status"\s*:\s*"Success"/i) 1 3 4
1568 1 $done->fail("cp_from_pod failed: connection closed without a Success status, "
1569 . "the transfer may be incomplete");
1570 1 return;
1571 }
1572  
1573 open my $fh, '>:raw', $local
1574 3 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $local or do { $done->fail("cannot write local file '${local}' for cp_from_pod: $!"); return } 2 1 3
1575 1 $done->fail("cannot write local file '$local' for cp_from_pod: $!");
1576 1 return;
1577 };
1578 2 ▶ unless (print {$fh} $stdout) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print {$fh;} $stdout) 0 2 2
1579 0 my $err = $!;
1580 0 close $fh;
1581 0 $done->fail("cannot write local file '$local' for cp_from_pod: $err");
1582 0 return;
1583 }
1584 2 ▶ unless (close $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close $fh) 1 1 2
1585 1 $done->fail("cannot write local file '$local' for cp_from_pod: $!");
1586 1 return;
1587 }
1588  
1589 $done->done({
1590 1 local => $local,
1591 remote => $remote,
1592 bytes => length($stdout),
1593 stderr => $stderr,
1594 status => $status_payload,
1595 });
1596 },
1597 0 ▶ on_error => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1598 0 my ($err) = @_;
1599 0 ▶ $done->fail("cp_from_pod transport error: $err") unless $done->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $done->is_ready 0 0 0
1600 },
1601 13 ▶ )->then(sub { return $done; });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'container'} ? : 1 12 13
1602 }
1603  
1604  
1605 4 ▶sub _send_stdin_chunks {
Subroutine _send_stdin_chunks: called CC=3 SCAR=11.0
1606 4 my ($self, $session, $bytes, $chunk_size) = @_;
1607  
1608 4 my $f = Future->done;
1609 4 ▶ my $len = length($bytes // '');
Condition50%1/2
$bytes // ""
l!l
40
MC/DC0%0/1
$bytes // ""
$bytes
Truth table50%1/2
A
A= $bytes
Aresult
11
00
1610 4 ▶ for (my $off = 0; $off < $len; $off += $chunk_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($off < $len) 8 4 12
1611 8 my $chunk = substr($bytes, $off, $chunk_size);
1612 8 ▶ $f = $f->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1613 8 return $session->write_stdin($chunk);
1614 8 });
1615 }
1616  
1617 4 return $f;
1618 }
1619  
1620 # ============================================================================
1621 # WATCHER FACTORY
1622 # ============================================================================
1623  
1624 104 ▶sub watcher {
Subroutine watcher: called CC=2 SCAR=6.9
Pod documented
1625 104 my ($self, $resource, @args) = @_;
1626  
1627 104 ▶ croak "Invalid arguments to watcher()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 103 104
1628 103 my $watcher = Net::Async::Kubernetes::Watcher->new(
1629 kube => $self,
1630 resource => $resource,
1631 @args,
1632 );
1633  
1634 102 $self->add_child($watcher);
1635 89 return $watcher;
1636 }
1637  
1638  
1639 33 ▶sub controller {
Subroutine controller: called CC=2 SCAR=6.9
Pod documented
1640 33 my ($self, @args) = @_;
1641  
1642 33 ▶ croak "Invalid arguments to controller()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 32 33
1643 32 my $controller = Net::Async::Kubernetes::Controller->new(
1644 kube => $self,
1645 @args,
1646 );
1647  
1648 32 $self->add_child($controller);
1649 32 return $controller;
1650 }
1651  
1652  
1653 # ============================================================================
1654 # HTTP TRANSPORT
1655 # ============================================================================
1656  
1657 12 ▶sub _do_request {
Subroutine _do_request: called CC=3 SCAR=13.3
1658 12 my ($self, $req) = @_;
1659  
1660 12 my $uri = URI->new($req->url);
1661  
1662 12 my @content_args;
1663 12 ▶ if (defined $req->content) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $req->content) 0 12 12
1664 0 ▶ my $ct = $req->headers->{'Content-Type'} // 'application/json';
Condition0%0/2
$req->headers->{"Content-Type"} // "application/json"
l!l
00
MC/DC0%0/1
$req->headers->{"Content-Type"} // "application/json"
$req->headers->{"Content-Type"}
Truth table0%0/2
A
A= $req->headers->{"Content-Type"}
Aresult
11
00
1665 0 @content_args = (content => $req->content, content_type => $ct);
1666 }
1667  
1668 return $self->_http->do_request(
1669 method => $req->method,
1670 uri => $uri,
1671 headers => $req->headers,
1672 @content_args,
1673 $self->_ssl_options,
1674 12 ▶ )->then(sub {
Subroutine __ANON__: called CC=3 SCAR=13.1
1675 12 my ($response) = @_;
1676 12 ▶ return Future->done(Kubernetes::REST::HTTPResponse->new(
Condition40%2/5
($response->decoded_content("charset", "none") // $response->content) // ""
l!l
120
$response->decoded_content("charset", "none") // $response->content
l!l&&r!l&&!r
1200
MC/DC0%0/2
($response->decoded_content("charset", "none") // $response->content) // ""
$response->decoded_content("charset", "none") $response->content
Truth table33%1/3
A // B
A= $response->decoded_content("charset", "none")B= $response->content
ABresult
1X1
011
000
1677 status => $response->code,
1678 content => $response->decoded_content(charset => 'none') // $response->content // '',
1679 ));
1680 12 });
1681 }
1682  
1683 # Resolves with the response status and, for an error response (>= 400), its
1684 # body as content. An error body is the Status explaining the rejection, not
1685 # stream data: it never reaches $on_chunk, where it would pass for a watch
1686 # event or a log line, and is kept for the caller's check_response instead.
1687 7 ▶sub _do_streaming_request {
Subroutine _do_streaming_request: called CC=1 SCAR=0.0
1688 7 my ($self, $req, $on_chunk) = @_;
1689  
1690 7 my $uri = URI->new($req->url);
1691 7 my $error_body = '';
1692  
1693 return $self->_http->do_request(
1694 method => $req->method,
1695 uri => $uri,
1696 headers => $req->headers,
1697 7 ▶ on_header => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1698 7 my ($response) = @_;
1699 7 my $is_error = $response->code >= 400;
1700 14 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1701 # Called once more without arguments at the end of the body;
1702 # what it returns is what the request Future resolves with.
1703 14 ▶ return $response unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 7 7 14
1704 7 my ($chunk) = @_;
1705 7 ▶ return unless defined $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk 0 7 7
1706 7 ▶ if ($is_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_error) { } 3 4 7
1707 3 $error_body .= $chunk;
1708 } else {
1709 4 $on_chunk->($chunk);
1710 }
1711 7 return;
1712 7 };
1713 },
1714 $self->_ssl_options,
1715 7 ▶ )->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1716 7 my ($response) = @_;
1717 7 return Future->done(Kubernetes::REST::HTTPResponse->new(
1718 status => $response->code,
1719 content => $error_body,
1720 ));
1721 7 });
1722 }
1723  
1724 22 ▶sub _do_duplex_request {
Subroutine _do_duplex_request: called CC=4 SCAR=14.8
1725 22 my ($self, $req, %callbacks) = @_;
1726 22 ▶ my $caller_name = delete($callbacks{caller}) // 'duplex request';
Condition50%1/2
delete $callbacks{"caller"} // "duplex request"
l!l
220
MC/DC0%0/1
delete $callbacks{"caller"} // "duplex request"
delete $callbacks{"caller"}
Truth table50%1/2
A
A= delete $callbacks{"caller"}
Aresult
11
00
1727 22 my $loop = eval { $self->loop };
1728 22 ▶ return Future->fail("$caller_name requires Net::Async::Kubernetes to be added to an IO::Async::Loop")
Branch: 1 branch
BranchTrueFalseTotal
unless $loop 4 18 22
1729 unless $loop;
1730  
1731 18 my $on_open = $callbacks{on_open};
1732 18 my $on_frame = $callbacks{on_frame};
1733 18 my $on_data = $callbacks{on_data};
1734 18 my $on_port_error = $callbacks{on_port_error};
1735 18 my $on_close = $callbacks{on_close};
1736 18 my $on_error = $callbacks{on_error};
1737 18 my $ports = $callbacks{ports};
1738  
1739 18 my $ws_url = $self->_build_websocket_url($req->url);
1740 18 my $ws_req = $self->_build_websocket_request($req);
1741  
1742 18 my $client;
1743 my $session;
1744 18 my $close_notified = 0;
1745  
1746 3 ▶ my $detach_client = sub {
Subroutine __ANON__: called CC=5 SCAR=18.6
1747 3 ▶ return unless $client;
Branch: 1 branch
BranchTrueFalseTotal
unless $client 0 3 3
1748 3 ▶ return unless $client->can('parent');
Branch: 1 branch
BranchTrueFalseTotal
unless $client->can("parent") 0 3 3
1749 3 ▶ return unless $client->parent && $client->parent == $self;
Branch: 1 branch
BranchTrueFalseTotal
unless $client->parent and $client->parent == $self 0 3 3
Condition33%1/3
$client->parent and $client->parent == $self
!ll&&!rl&&r
003
MC/DC0%0/2
$client->parent and $client->parent == $self
$client->parent $client->parent == $self
Truth table33%1/3
A and B
A= $client->parentB= $client->parent == $self
ABresult
0X0
100
111
1750 3 $self->remove_child($client);
1751 18 };
1752  
1753 9 ▶ my $notify_error = sub {
Subroutine __ANON__: called CC=3 SCAR=11.6
1754 9 my ($err) = @_;
1755 9 ▶ return unless ref($on_error) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $on_error eq "CODE" 0 9 9
1756 9 my $ok = eval { $on_error->($err); 1 };
1757 9 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 9 0 9
1758 0 warn $@;
1759 18 };
1760  
1761 1 ▶ my $notify_close = sub {
Subroutine __ANON__: called CC=4 SCAR=14.3
1762 1 ▶ return if $close_notified++;
Branch: 1 branch
BranchTrueFalseTotal
if $close_notified++ 0 1 1
1763 1 ▶ if (ref($on_close) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $on_close eq "CODE") 1 0 1
1764 1 my $ok = eval { $on_close->(@_); 1 };
1765 1 ▶ $notify_error->($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 1 1
1766 }
1767 1 $detach_client->();
1768 18 };
1769  
1770 38 ▶ my $dispatch_frame = sub {
Subroutine __ANON__: called CC=13 SCAR=26.5
1771 38 my ($bytes) = @_;
1772 38 ▶ return unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 38 38
1773 38 ▶ return unless length $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bytes 0 38 38
1774  
1775 38 my $channel = ord(substr($bytes, 0, 1));
1776 38 my $payload = substr($bytes, 1);
1777 38 ▶ if (ref($on_frame) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $on_frame eq "CODE") 10 28 38
1778 10 my $ok = eval { $on_frame->($channel, $payload); 1 };
1779 10 ▶ $notify_error->($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 10 10
1780 }
1781  
1782 # port-forward: strip and check the preamble, route data and errors
1783 38 ▶ return unless $session && $session->is_port_forward;
Branch: 1 branch
BranchTrueFalseTotal
unless $session and $session->is_port_forward 0 38 38
Condition33%1/3
$session and $session->is_port_forward
!ll&&!rl&&r
0038
MC/DC0%0/2
$session and $session->is_port_forward
$session $session->is_port_forward
Truth table33%1/3
A and B
A= $sessionB= $session->is_port_forward
ABresult
0X0
100
111
1784 38 for my $event ($session->_port_events($channel, $payload)) {
1785 20 my ($kind, @rest) = @$event;
1786 20 ▶ my $cb = $kind eq 'data' ? $on_data
Branch: 2 branches
BranchTrueFalseTotal
$kind eq 'data' ? : 11 9 20
$kind eq 'port_error' ? : 3 6 9
1787 : $kind eq 'port_error' ? $on_port_error : undef;
1788 20 ▶ if ($kind eq 'error') {
Branch: 2 branches
BranchTrueFalseTotal
if ($kind eq 'error') { } 6 14 20
elsif (ref $cb eq 'CODE') { } 14 0 14
1789 6 $notify_error->($rest[0]);
1790 } elsif (ref($cb) eq 'CODE') {
1791 14 my $ok = eval { $cb->($session, @rest); 1 };
1792 14 ▶ $notify_error->($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 14 14
1793 }
1794 }
1795 18 };
1796  
1797 $client = $self->_make_websocket_client(
1798 38 ▶ on_binary_frame => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1799 38 my (undef, $bytes) = @_;
1800 38 $dispatch_frame->($bytes);
1801 },
1802 0 ▶ on_text_frame => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1803 0 my (undef, $text) = @_;
1804 0 ▶ return unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 0 0
1805 0 my $bytes = $text;
1806 0 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 0 0 0
1807 0 $dispatch_frame->($bytes);
1808 },
1809 1 ▶ on_close_frame => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1810 1 my (undef, $payload) = @_;
1811 1 $notify_close->($payload);
1812 },
1813 1 ▶ on_read_error => sub {
Subroutine __ANON__: called CC=4 SCAR=17.9
1814 1 my (undef, $errno, $msg) = @_;
1815 1 ▶ my $err = defined $msg && length $msg ? $msg : ($errno // 'websocket read error');
Branch: 1 branch
BranchTrueFalseTotal
defined $msg && length $msg ? : 1 0 1
Condition20%1/5
defined $msg and length $msg
!ll&&!rl&&r
001
$errno // "websocket read error"
l!l
00
MC/DC0%0/2
defined $msg and length $msg
defined $msg length $msg
MC/DC0%0/1
$errno // "websocket read error"
$errno
Truth table33%1/3
A and B
A= defined $msgB= length $msg
ABresult
0X0
100
111
Truth table0%0/2
A
A= $errno
Aresult
11
00
1816 1 $notify_error->($err);
1817 },
1818 0 ▶ on_write_error => sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1819 0 my (undef, $errno, $msg) = @_;
1820 0 ▶ my $err = defined $msg && length $msg ? $msg : ($errno // 'websocket write error');
Branch: 1 branch
BranchTrueFalseTotal
defined $msg && length $msg ? : 0 0 0
Condition0%0/5
defined $msg and length $msg
!ll&&!rl&&r
000
$errno // "websocket write error"
l!l
00
MC/DC0%0/2
defined $msg and length $msg
defined $msg length $msg
MC/DC0%0/1
$errno // "websocket write error"
$errno
Truth table0%0/3
A and B
A= defined $msgB= length $msg
ABresult
0X0
100
111
Truth table0%0/2
A
A= $errno
Aresult
11
00
1821 0 $notify_error->($err);
1822 },
1823 0 ▶ on_closed => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1824 0 $notify_close->();
1825 },
1826 18 );
1827  
1828 18 ▶ $session = Net::Async::Kubernetes::PortForwardSession->new(
Branch: 1 branch
BranchTrueFalseTotal
$ports ? : 16 2 18
1829 ws_client => $client,
1830 ($ports ? (ports => $ports) : ()),
1831 );
1832  
1833 18 $self->add_child($client);
1834  
1835 return $client->connect(
1836 url => $ws_url,
1837 req => $ws_req,
1838 $self->_ssl_options,
1839 16 ▶ )->then(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1840  
1841 16 ▶ if (ref($on_open) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $on_open eq "CODE") 8 8 16
1842 8 my $ok = eval { $on_open->($session); 1 };
1843 8 ▶ $notify_error->($@) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 8 8
1844 }
1845  
1846 16 return Future->done($session);
1847 2 ▶ })->else(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1848 2 my ($error) = @_;
1849 2 $notify_error->($error);
1850 2 $detach_client->();
1851 2 return Future->fail($error);
1852 18 });
1853 }
1854  
1855 18 ▶sub _build_websocket_url {
Subroutine _build_websocket_url: called CC=1 SCAR=0.0
1856 18 my ($self, $url) = @_;
1857 18 $url =~ s/^https:/wss:/i;
1858 18 $url =~ s/^http:/ws:/i;
1859 18 return $url;
1860 }
1861  
1862 18 ▶sub _build_websocket_request {
Subroutine _build_websocket_request: called CC=11 SCAR=24.5
1863 18 my ($self, $req) = @_;
1864 18 ▶ my $headers = $req->headers || {};
Condition50%1/2
$req->headers || {}
l!l
180
MC/DC0%0/1
$req->headers || {}
$req->headers
Truth table50%1/2
A
A= $req->headers
Aresult
11
00
1865  
1866 18 my @extra_headers;
1867 my $subprotocol;
1868  
1869 18 for my $name (keys %$headers) {
1870 107 my $value = $headers->{$name};
1871 107 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 107 107
1872  
1873 107 my $lc = lc($name);
1874 107 ▶ if ($lc eq 'sec-websocket-protocol') {
Branch: 1 branch
BranchTrueFalseTotal
if ($lc eq "sec-websocket-protocol") 18 89 107
1875 18 $subprotocol = $value;
1876 18 next;
1877 }
1878 89 ▶ next if $lc eq 'connection';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "connection" 18 71 89
1879 71 ▶ next if $lc eq 'upgrade';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "upgrade" 18 53 71
1880 53 ▶ next if $lc eq 'host';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "host" 0 53 53
1881 53 ▶ next if $lc eq 'sec-websocket-key';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "sec-websocket-key" 0 53 53
1882 53 ▶ next if $lc eq 'sec-websocket-version';
Branch: 1 branch
BranchTrueFalseTotal
if $lc eq "sec-websocket-version" 0 53 53
1883  
1884 53 push @extra_headers, $name, $value;
1885 }
1886  
1887 18 ▶ return Protocol::WebSocket::Request->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $subprotocol ? : 18 0 18
1888 headers => \@extra_headers,
1889 (defined $subprotocol ? (subprotocol => $subprotocol) : ()),
1890 );
1891 }
1892  
1893 0 ▶sub _make_websocket_client {
Subroutine _make_websocket_client: not called CC=1 SCAR=6.9
1894 0 my ($self, %args) = @_;
1895 0 require Net::Async::WebSocket::Client;
1896 0 return Net::Async::WebSocket::Client->new(%args);
1897 }
1898  
1899 54 1;
1900  
1901 __END__
1902  
1903 =pod
1904  
1905 =encoding UTF-8
1906  
1907 =head1 NAME
1908  
1909 Net::Async::Kubernetes - Async Kubernetes client for IO::Async
1910  
1911 =head1 VERSION
1912  
1913 version 0.011
1914  
1915 =head1 SYNOPSIS
1916  
1917 use IO::Async::Loop;
1918 use Net::Async::Kubernetes;
1919  
1920 my $loop = IO::Async::Loop->new;
1921  
1922 # From kubeconfig (easiest)
1923 my $kube = Net::Async::Kubernetes->new(
1924 kubeconfig => "$ENV{HOME}/.kube/config",
1925 );
1926 $loop->add($kube);
1927  
1928 # In-cluster: auto-detects service account token (no config needed)
1929 my $kube = Net::Async::Kubernetes->new;
1930 $loop->add($kube);
1931  
1932 # Or with explicit server/credentials
1933 my $kube = Net::Async::Kubernetes->new(
1934 server => { endpoint => 'https://kubernetes.local:6443' },
1935 credentials => { token => $token },
1936 );
1937 $loop->add($kube);
1938  
1939 # Future-based CRUD
1940 my $pods = $kube->list('Pod', namespace => 'default')->get;
1941  
1942 my $pod = $kube->get('Pod', 'nginx', namespace => 'default')->get;
1943  
1944 my $patched = $kube->patch('Pod', 'nginx',
1945 namespace => 'default',
1946 patch => { metadata => { labels => { env => 'staging' } } },
1947 )->get;
1948  
1949 $kube->delete('Pod', 'nginx', namespace => 'default')->get;
1950  
1951 # Pod logs (one-shot)
1952 my $text = $kube->log('Pod', 'nginx',
1953 namespace => 'default',
1954 tailLines => 100,
1955 )->get;
1956  
1957 # Pod logs (streaming)
1958 $kube->log('Pod', 'nginx',
1959 namespace => 'default',
1960 follow => 1,
1961 on_line => sub { my ($event) = @_; say $event->line },
1962 )->get;
1963  
1964 # Port-forward (built-in websocket duplex support)
1965 my $pf = $kube->port_forward('Pod', 'nginx',
1966 namespace => 'default',
1967 ports => [8080],
1968 on_frame => sub { my ($channel, $payload) = @_; ... },
1969 )->get;
1970  
1971 $pf->write_channel(0, "GET / HTTP/1.1\r\n\r\n");
1972 $pf->close(code => 1000);
1973  
1974 # Pod exec (websocket duplex)
1975 my $exec = $kube->exec('Pod', 'nginx',
1976 namespace => 'default',
1977 command => ['sh', '-c', 'id'],
1978 on_frame => sub { my ($channel, $payload) = @_; ... },
1979 )->get;
1980 $exec->write_stdin("id\n");
1981 $exec->resize(width => 120, height => 40);
1982  
1983 # Pod attach (websocket duplex)
1984 my $attach = $kube->attach('Pod', 'nginx',
1985 namespace => 'default',
1986 container => 'app',
1987 stdin => 1,
1988 stdout => 1,
1989 stderr => 1,
1990 tty => 0,
1991 on_frame => sub { my ($channel, $payload) = @_; ... },
1992 )->get;
1993 $attach->write_stdin("help\n");
1994  
1995 # Copy local file to pod and back (built on exec)
1996 $kube->cp_to_pod('Pod', 'nginx',
1997 namespace => 'default',
1998 local => '/tmp/local.txt',
1999 remote => '/tmp/remote.txt',
2000 )->get;
2001 $kube->cp_from_pod('Pod', 'nginx',
2002 namespace => 'default',
2003 remote => '/tmp/remote.txt',
2004 local => '/tmp/downloaded.txt',
2005 )->get;
2006  
2007 # Watcher with auto-reconnect
2008 my $watcher = $kube->watcher('Pod',
2009 namespace => 'default',
2010 on_added => sub { my ($pod) = @_; say "Added: " . $pod->metadata->name },
2011 on_modified => sub { my ($pod) = @_; say "Modified: " . $pod->metadata->name },
2012 on_deleted => sub { my ($pod) = @_; say "Deleted: " . $pod->metadata->name },
2013 );
2014  
2015 $loop->run;
2016  
2017 =head1 DESCRIPTION
2018  
2019 C<Net::Async::Kubernetes> is an async Kubernetes client built on L<IO::Async>.
2020 It extends L<IO::Async::Notifier> and uses L<Net::Async::HTTP> for
2021 non-blocking HTTP communication, plus L<Net::Async::WebSocket::Client> for
2022 duplex subresources like pod port-forward.
2023  
2024 All CRUD, log, port-forward, exec, attach, and cp helper methods return L<Future> objects. The
2025 L<Net::Async::Kubernetes::Watcher>
2026 provides auto-reconnecting event streaming with separate callbacks per
2027 event type.
2028  
2029 Request preparation and response processing are delegated to
2030 L<Kubernetes::REST>, so the same IO::K8s object inflation, short class
2031 names, and CRD support are available.
2032  
2033 Authentication is automatically resolved in the following order:
2034  
2035 =over 4
2036  
2037 =item 1. Explicit C<server> and C<credentials> parameters
2038  
2039 =item 2. C<kubeconfig> file (via L<Kubernetes::REST::Kubeconfig>)
2040  
2041 =item 3. In-cluster service account token at
2042 C</var/run/secrets/kubernetes.io/serviceaccount/token> (automatic when
2043 running inside a Kubernetes pod)
2044  
2045 =back
2046  
2047 =head2 configure
2048  
2049 Internal L<IO::Async::Notifier> configuration method. Handles initialization
2050 of C<kubeconfig>, C<context>, C<server>, C<credentials>, C<resource_map>,
2051 C<resource_map_from_cluster> and C<with> parameters.
2052  
2053 If C<kubeconfig> is provided without explicit C<server> or C<credentials>,
2054 they are loaded automatically via L<Kubernetes::REST::Kubeconfig>. So are
2055 they for a C<context> without C<kubeconfig>, from the default kubeconfig.
2056 Either way a kubeconfig or context that cannot be resolved croaks with the
2057 reason (a missing file, C<Context not found: ...>).
2058  
2059 When running inside a Kubernetes pod (no C<kubeconfig> or C<server> set),
2060 the service account token at
2061 C</var/run/secrets/kubernetes.io/serviceaccount/token> is used
2062 automatically for in-cluster authentication.
2063  
2064 =head2 kubeconfig
2065  
2066 Path to kubeconfig file. If provided, C<server> and C<credentials> are
2067 extracted automatically (via L<Kubernetes::REST::Kubeconfig>).
2068  
2069 =head2 context
2070  
2071 Kubernetes context to use from the kubeconfig. Defaults to current-context.
2072 Without L</kubeconfig> it is looked up in the default kubeconfig
2073 (C<KUBECONFIG>, else F<~/.kube/config>); when it is not found there, or
2074 there is no kubeconfig at all and no in-cluster service account either, the
2075 constructor croaks with the reason.
2076  
2077 =head2 resource_map
2078  
2079 Optional. Custom resource map for short class names.
2080  
2081 =head2 resource_map_from_cluster
2082  
2083 Optional boolean, defaults to false. When true, L<Kubernetes::REST> reads the
2084 cluster's discovery documents (C<GET /api>, C<GET /apis>) and, unless a
2085 L</resource_map> is given, builds the resource map from them. Left to itself
2086 it fetches them once, on first use, through its own synchronous HTTP backend,
2087 not through this client's transport, so that first use blocks the loop.
2088 Await L</discover> once at start-up to have them read through this client's
2089 transport instead:
2090  
2091 my $kube = Net::Async::Kubernetes->new(
2092 kubeconfig => "$ENV{HOME}/.kube/config",
2093 resource_map_from_cluster => 1,
2094 );
2095 $loop->add($kube);
2096 $kube->discover->get;
2097  
2098 It also makes custom resources usable without a class of their own: a Kind
2099 that no IO::K8s class or C<resource_map> entry serves, but which discovery
2100 lists, resolves to L<IO::K8s::Unstructured>. Requests for it take the
2101 resource's plural and scope from discovery, and a qualified
2102 C<'group/version/Kind'> name stays in that group and version. An
2103 L<IO::K8s::Unstructured> object handed to L</create>, L</update>,
2104 L</ensure> or another object form is addressed the same way, by its own
2105 C<kind> and C<apiVersion> -- without this option there is no discovery to
2106 find its path in.
2107  
2108 That group and version are the only ones such a request goes to. When the
2109 cluster does not serve them, a qualified name is an unknown resource and an
2110 object or manifest with that C<apiVersion> is refused, even if another group
2111 or another version serves a Kind of the same name -- nothing is listed,
2112 changed or deleted there instead.
2113  
2114 A request for L<IO::K8s::Unstructured> that has no path -- without this
2115 option, for the explicit class name C<IO::K8s::Unstructured> (a class name
2116 carries no Kind), or for an object without C<kind> -- is refused before it
2117 is sent, like any other bad argument: the L<Future> fails with the reason,
2118 and L</update>, L</update_status>, L</ensure> and a watcher starting up
2119 croak with it instead, as they do for their other argument errors.
2120  
2121 =head2 with
2122  
2123 Optional arrayref of L<IO::K8s> resource-map providers (CRD bundles),
2124 passed on to L<Kubernetes::REST/with>, so their Kinds resolve to typed
2125 classes -- in names, lists, watches and L</new_object>:
2126  
2127 my $kube = Net::Async::Kubernetes->new(
2128 kubeconfig => "$ENV{HOME}/.kube/config",
2129 with => ['IO::K8s::GatewayAPI'],
2130 );
2131 my $gateways = $kube->list('Gateway', namespace => 'default')->get;
2132  
2133 Defaults to C<[]>. See L<IO::K8s/with> for the accepted provider forms.
2134  
2135 =head2 server
2136  
2137 Returns the L<Kubernetes::REST::Server> instance. Croaks if neither C<server>
2138 nor C<kubeconfig> was provided during initialization.
2139  
2140 =head2 credentials
2141  
2142 Returns the credentials object (typically L<Kubernetes::REST::AuthToken>).
2143 Croaks if neither C<credentials> nor C<kubeconfig> was provided during
2144 initialization.
2145  
2146 =head2 rest
2147  
2148 my $rest = $kube->rest;
2149  
2150 Returns the underlying lazily-built L<Kubernetes::REST> instance used for
2151 request building and response processing. Exposed for advanced use -- most
2152 callers want the higher-level CRUD methods instead. The private C<_rest>
2153 accessor used throughout the internals returns this same cached instance.
2154  
2155 =head2 new_object
2156  
2157 my $cm = $kube->new_object(ConfigMap =>
2158 metadata => { name => 'my-config' },
2159 data => { key => 'value' },
2160 );
2161  
2162 Builds a typed L<IO::K8s> object from a short class name (e.g. C<'Pod'>,
2163 C<'ConfigMap'>) and either a hashref or a hash of attributes. Delegates to
2164 L<Kubernetes::REST/new_object>. This is the public path for constructing the
2165 objects passed to C<create> and C<update>.
2166  
2167 =head2 expand_class
2168  
2169 my $full_class = $kube->expand_class('Pod');
2170 # Returns 'IO::K8s::Api::Core::V1::Pod'
2171  
2172 Expands a short resource name (e.g., C<'Pod'>, C<'Deployment'>) to its full
2173 IO::K8s class name. Delegates to L<Kubernetes::REST/expand_class>.
2174  
2175 The name may also be qualified as C<'group/version/Kind'>, which resolves to
2176 that exact API version instead of the historical default the bare Kind name
2177 carries -- the two forms can and do point at different classes:
2178  
2179 $kube->expand_class('HorizontalPodAutoscaler');
2180 # 'IO::K8s::Api::Autoscaling::V2::HorizontalPodAutoscaler' (bare-name default)
2181  
2182 $kube->expand_class('autoscaling/v1/HorizontalPodAutoscaler');
2183 # 'IO::K8s::Api::Autoscaling::V1::HorizontalPodAutoscaler' (pinned to v1)
2184  
2185 This qualified form is accepted anywhere a resource name is, including
2186 C<list>, C<get>, and C<watcher>.
2187  
2188 The result is a plain class name, without a C<+>. Handed back to a method
2189 that resolves names again -- L</new_object>, L<IO::K8s/struct_to_object> --
2190 a single-segment class of your own (C<'+Gizmo'> in the L</resource_map>,
2191 returned as C<'Gizmo'>) reads as the Kind C<Gizmo> there. Prefix it with
2192 C<+> when you do that yourself. The client's own methods already do, for the
2193 manifests L</ensure> resolves and for every answer they inflate, a watch
2194 event included -- whichever L<Kubernetes::REST> version is installed.
2195  
2196 Croaks when the name cannot be resolved to an IO::K8s class -- a qualified
2197 name no class serves, and equally a bare Kind no class ships for (C<'Bogus'>),
2198 which L<Kubernetes::REST/expand_class> would hand back as a fabricated
2199 C<IO::K8s::Bogus>. It also croaks when the name resolves to a class that
2200 cannot serve as a resource, with the real cause rather than "unknown
2201 resource": a class that does not load or compile (say, a typo in a
2202 C<'+Class'> entry of L</resource_map>) croaks with its load error, and a
2203 class without an C<api_version> of its own -- an IO::K8s helper such as
2204 C<IO::K8s::List> that a bare C<'List'> lands on -- croaks as not being a
2205 Kubernetes resource class. This is the synchronous counterpart of the
2206 C<Future>-returning methods below, which report the same conditions as a
2207 failed L<Future> with the same message.
2208  
2209 =head2 discover
2210  
2211 $kube->discover->get; # once, at start-up
2212  
2213 Reads the cluster's discovery documents (C<GET /api>, C<GET /apis>) through
2214 this client's own asynchronous transport and hands them to
2215 L<Kubernetes::REST>, which then resolves names -- a Kind only the cluster
2216 serves included (see L</resource_map_from_cluster>) -- and builds its
2217 resource map from them without a request of its own. Returns a L<Future>
2218 that resolves, with no value, once that is done.
2219  
2220 With L</resource_map_from_cluster> on, await it once at start-up, before the
2221 first request: otherwise L<Kubernetes::REST> reads discovery itself on first
2222 use, through its synchronous HTTP backend, and that first use blocks the
2223 loop. No other method calls C<discover> for you. Calling it again reads
2224 discovery anew and replaces what was read before -- after installing a
2225 CustomResourceDefinition, for example.
2226  
2227 =over 4
2228  
2229 =item * Without L</resource_map_from_cluster> there is no discovery to read:
2230 the L<Future> is done at once and nothing is sent.
2231  
2232 =item * A cluster older than Kubernetes 1.27 answers with legacy discovery,
2233 which takes a further request per API group and version.
2234 L<Kubernetes::REST> keeps nothing of it; the L<Future> is done all the same,
2235 and discovery is read synchronously on first use, as without C<discover>.
2236  
2237 =item * An error status (C<401>, C<403>, C<5xx>) fails the L<Future> as
2238 described in L</ERRORS>, C<< ->fail($error, 'http', $response) >>. A request
2239 that gets no response fails it the way the transport reports it, and a
2240 document that cannot be read (not JSON) with the reason.
2241  
2242 =back
2243  
2244 =head2 list
2245  
2246 my $future = $kube->list('Pod', namespace => 'default');
2247 my $list = $future->get;
2248 my @pods = @{ $list->items };
2249  
2250 my $future = $kube->list('Pod', labelSelector => 'app=web');
2251  
2252 List resources of the given type. Returns a L<Future> that resolves to an
2253 L<IO::K8s::List>. Its C<items> accessor holds the ArrayRef of inflated
2254 IO::K8s objects.
2255  
2256 C<labelSelector> and C<fieldSelector> are sent as query parameters, so
2257 filtering happens server-side rather than on the list that comes back.
2258 C<limit>, C<continue> and C<resourceVersion> are sent as query parameters too,
2259 as in L<Kubernetes::REST/list>. The list carries the collection's metadata
2260 (C<resourceVersion>, C<continue>, C<remainingItemCount>) in
2261 C<< $list->metadata >>, so a large collection can be paged and a watch can
2262 start from the version the list was read at:
2263  
2264 my ($continue, @pods);
2265 do {
2266 my $page = $kube->list('Pod', namespace => 'default', limit => 500,
2267 defined $continue ? (continue => $continue) : ())->get;
2268 push @pods, @{ $page->items };
2269 $continue = $page->metadata->continue;
2270 } while (defined $continue && length $continue);
2271  
2272 Any other option -- a misspelt C<labelselector> would otherwise list every
2273 object -- fails the L<Future> before a request is sent, naming the options
2274 C<list> takes. So does an odd list of options, as C<Invalid arguments to
2275 list()>: its last key would otherwise go out without a value.
2276  
2277 Arguments:
2278  
2279 =over 4
2280  
2281 =item C<$short_class> - Resource type (e.g., C<'Pod'>, C<'Deployment'>), or a
2282 qualified C<'group/version/Kind'> name to pin a specific API version -- see
2283 L</expand_class>
2284  
2285 =item C<%args> - Optional parameters: C<namespace>, C<labelSelector>,
2286 C<fieldSelector>, C<limit>, C<continue>, C<resourceVersion>
2287  
2288 =back
2289  
2290 =head2 get
2291  
2292 my $future = $kube->get('Pod', 'nginx', namespace => 'default');
2293 my $pod = $future->get;
2294  
2295 Get a single resource by name. Returns a L<Future> that resolves to an
2296 inflated IO::K8s object. An option other than C<name> and C<namespace> fails
2297 the L<Future> before a request is sent, and so does an odd list of options,
2298 as C<Invalid arguments to get()>. A reference in place of the name -- a
2299 manifest hashref, an IO::K8s object -- fails it as C<resource name must be a
2300 string, got a HASH reference>, before it is stringified into the request path.
2301  
2302 Arguments:
2303  
2304 =over 4
2305  
2306 =item C<$short_class> - Resource type (e.g., C<'Pod'>), or a qualified
2307 C<'group/version/Kind'> name -- see L</expand_class>
2308  
2309 =item C<$name> - Resource name (required)
2310  
2311 =item C<%args> - Optional parameters: C<namespace>
2312  
2313 =back
2314  
2315 =head2 create
2316  
2317 my $future = $kube->create($pod_object);
2318 my $created = $future->get;
2319  
2320 Create a resource from an IO::K8s object. Returns a L<Future> that resolves
2321 to the created object with server-populated fields (C<resourceVersion>, etc.).
2322  
2323 An object that is no Kubernetes resource -- an L<IO::K8s::List>, a nested
2324 type such as a C<PodSpec> -- or anything that is not an IO::K8s object fails
2325 the L<Future> before a request is sent.
2326  
2327 Arguments:
2328  
2329 =over 4
2330  
2331 =item C<$object> - IO::K8s object instance (e.g., C<IO::K8s::Api::Core::V1::Pod>)
2332  
2333 =back
2334  
2335 =head2 update
2336  
2337 my $future = $kube->update($modified_pod);
2338 my $updated = $future->get;
2339  
2340 Update an existing resource. The object must have C<metadata.name> (and
2341 C<metadata.namespace> if namespaced). Returns a L<Future> that resolves to
2342 the updated object.
2343  
2344 A missing C<metadata> or C<metadata.name> croaks synchronously, and so does
2345 an object that is no Kubernetes resource -- an L<IO::K8s::List>, a nested
2346 type such as a C<PodSpec> -- or anything that is not an IO::K8s object.
2347  
2348 Arguments:
2349  
2350 =over 4
2351  
2352 =item C<$object> - Modified IO::K8s object with updated fields
2353  
2354 =back
2355  
2356 =head2 update_status
2357  
2358 my $future = $kube->update_status($node);
2359 my $updated = $future->get;
2360  
2361 Replace a resource's B<status> through the C</status> subresource. The whole
2362 object is sent, as with L</update>, but the server only stores the C<status>
2363 it carries and leaves C<spec> and C<metadata> untouched. Returns a L<Future>
2364 that resolves to the updated object.
2365  
2366 Needs a current C<resourceVersion> and fails with a 409 conflict if the
2367 object changed on the server in the meantime. A missing C<metadata> or
2368 C<metadata.name>, or an object that is no Kubernetes resource, croaks
2369 synchronously, as with L</update>. Prefer
2370 L</patch_status> when you are setting individual status fields.
2371  
2372 Arguments:
2373  
2374 =over 4
2375  
2376 =item C<$object> - IO::K8s object with C<metadata.name> (and C<namespace> if
2377 namespaced) and the desired C<status>
2378  
2379 =back
2380  
2381 =head2 patch
2382  
2383 # By class and name
2384 my $future = $kube->patch('Pod', 'nginx',
2385 namespace => 'default',
2386 patch => { metadata => { labels => { env => 'prod' } } },
2387 type => 'strategic', # or 'merge', 'json'
2388 );
2389  
2390 # Or by object
2391 my $future = $kube->patch($pod_object,
2392 patch => { spec => { replicas => 3 } },
2393 );
2394  
2395 Patch an existing resource. Returns a L<Future> that resolves to the patched
2396 object. Bad arguments -- among them an object that is no Kubernetes
2397 resource, such as an L<IO::K8s::List> or a nested C<PodSpec>, a plain
2398 reference such as a manifest hashref in place of the resource name, an odd
2399 list of options after the object or the name (C<Invalid arguments to
2400 patch()>), and an option not listed below (in the object form C<name> and
2401 C<namespace> come from the object and are refused as options too) -- fail
2402 the L<Future> before a request is sent.
2403  
2404 Arguments:
2405  
2406 =over 4
2407  
2408 =item C<$class_or_object> - Resource class name or IO::K8s object
2409  
2410 =item C<name> - Resource name (required unless passing object)
2411  
2412 =item C<namespace> - Namespace (if namespaced)
2413  
2414 =item C<patch> - HashRef of changes to apply (required)
2415  
2416 =item C<type> - Patch type: C<'strategic'> (default), C<'merge'>, or C<'json'>
2417  
2418 =back
2419  
2420 =head2 patch_status
2421  
2422 # By class and name
2423 my $future = $kube->patch_status('OCPNode', 'cp-1',
2424 namespace => 'ocp',
2425 patch => { status => { phase => 'Ready' } },
2426 );
2427  
2428 # Or by object
2429 my $future = $kube->patch_status($node,
2430 patch => { status => { phase => 'Ready' } },
2431 );
2432  
2433 Partially update a resource's B<status> through the C</status> subresource.
2434 Once a CustomResourceDefinition declares C<subresources: { status: {} }>, the
2435 API server drops the C<status> stanza from every write to the main endpoint
2436 and still answers 2xx -- so a C<status> written via L</patch> or L</update>
2437 is silently discarded. This method writes to C</status> instead.
2438  
2439 Takes the same call forms and arguments as L</patch> (object, or class plus
2440 name in either the shorthand or fully-keyed form), and refuses any other
2441 option, and an odd list of options, the same way. The patch document is
2442 sent unchanged and carries its own C<status> key.
2443  
2444 The default patch type is C<merge>, not C<strategic> as in L</patch>: custom
2445 resources reject strategic merge patch with a 415, and C<merge> works for
2446 built-in kinds too. Pass C<type =E<gt> 'strategic'> explicitly to patch the
2447 status of a built-in resource when you need array merge semantics.
2448  
2449 Returns a L<Future> that resolves to the patched object; bad arguments, an
2450 unknown patch C<type>, or a server error fail the Future, as with L</patch>.
2451  
2452 Arguments:
2453  
2454 =over 4
2455  
2456 =item C<$class_or_object> - Resource class name or IO::K8s object
2457  
2458 =item C<name> - Resource name (required unless passing object)
2459  
2460 =item C<namespace> - Namespace (if namespaced)
2461  
2462 =item C<patch> - HashRef with a C<status> key (or ArrayRef of operations when
2463 C<type> is C<json>)
2464  
2465 =item C<type> - Patch type: C<'merge'> (default), C<'strategic'>, or C<'json'>
2466  
2467 =back
2468  
2469 =head2 delete
2470  
2471 # By class and name
2472 my $future = $kube->delete('Pod', 'nginx', namespace => 'default');
2473 $future->get;
2474  
2475 # Or by object
2476 my $future = $kube->delete($pod_object);
2477 $future->get;
2478  
2479 # A Job together with its Pods
2480 $kube->delete('Job', 'nightly', namespace => 'default',
2481 propagationPolicy => 'Background')->get;
2482 $kube->delete($job, propagationPolicy => 'Foreground')->get;
2483  
2484 Delete a resource. Returns a L<Future> that resolves to C<1> on success.
2485 In the object form, an object without C<metadata.name>, one that is no
2486 Kubernetes resource (an L<IO::K8s::List>, a nested C<PodSpec>), or a
2487 reference that is not an IO::K8s object fails the L<Future>. In the class
2488 form, a reference in place of the name -- C<delete('Pod', $manifest)> --
2489 fails it as C<resource name must be a string, got a HASH reference>, before
2490 it is stringified into the request path.
2491  
2492 C<propagationPolicy> is sent as a query parameter and decides what happens
2493 to the objects the deleted one owns: C<Background> deletes them after it,
2494 C<Foreground> before it, C<Orphan> leaves them. Without it the API server
2495 applies the resource's own default -- for a C<Job> that orphans its Pods.
2496 Any other value, and any option C<delete> does not know (a misspelt
2497 C<propagationPolicy> would otherwise be dropped silently), fails the
2498 L<Future> before a request is sent, worded as L<Kubernetes::REST> words it:
2499 C<Unknown propagationPolicy 'x' for delete() (use: Background, Foreground,
2500 Orphan)>, or C<Unknown argument 'x' to delete() (allowed: ...)> naming the
2501 first unknown option.
2502  
2503 Arguments:
2504  
2505 =over 4
2506  
2507 =item C<$class_or_object> - Resource class name or IO::K8s object
2508  
2509 =item C<$name> - Resource name (required unless passing object)
2510  
2511 =item C<namespace> - Namespace (if namespaced; not in the object form, which
2512 takes it from the object)
2513  
2514 =item C<propagationPolicy> - C<'Background'>, C<'Foreground'> or C<'Orphan'>;
2515 optional
2516  
2517 =back
2518  
2519 =head2 ensure
2520  
2521 my $future = $kube->ensure($pod);
2522 my $obj = $future->get;
2523  
2524 # or from a plain hashref (treated as a Kubernetes manifest):
2525 my $future = $kube->ensure({
2526 apiVersion => 'v1',
2527 kind => 'Secret',
2528 metadata => { name => 'foo', namespace => 'default' },
2529 stringData => { password => 'hunter2' },
2530 });
2531  
2532 Idempotent create-or-update. GETs the object by kind/name/namespace: if it is
2533 missing, creates it; if it exists, updates it at the server's
2534 C<resourceVersion>, which this method writes back into the object passed in.
2535 Returns a L<Future> that resolves to the resulting IO::K8s object.
2536  
2537 Accepts a typed IO::K8s object or a plain hashref; a hashref must carry a
2538 C<kind> field and uses manifest-style camelCase keys (C<stringData>, not
2539 C<string_data>).
2540  
2541 A hashref's C<apiVersion>, when present, selects the class: an
2542 C<autoscaling/v1> HorizontalPodAutoscaler stays C<autoscaling/v1> and goes to
2543 that endpoint, although the bare Kind resolves to C<autoscaling/v2>. A hashref
2544 without C<apiVersion> (or with an empty one) resolves by its Kind alone, as
2545 L</expand_class> does.
2546  
2547 Handles the create/update race: a 409 on update (something else changed the
2548 object between GET and PUT) refetches once and retries the update; a 409 on
2549 create (something else created it between GET and POST) refetches it and
2550 handles it like an object that existed from the start -- updated, with the
2551 same one retry, or, for the two special cases below, returned unchanged or
2552 deleted and recreated.
2553  
2554 Two kinds get special handling because their spec is immutable after
2555 creation: an existing core C<v1> C<PersistentVolumeClaim> is left unchanged,
2556 and an existing C<batch/v1> C<Job> is left unchanged while it is active or has
2557 succeeded, and deleted and recreated otherwise -- deleted with
2558 C<propagationPolicy> C<Background>, so its Pods go with it instead of being
2559 orphaned. Both are recognised by
2560 apiVersion and Kind together -- the object's C<api_version> and C<kind> --
2561 never by the class name. A custom resource that reuses one of these Kind
2562 names in its own group is ensured like any other object, and so is a C<Job>
2563 under any apiVersion other than C<batch/v1>.
2564  
2565 Errors that are known before any request is made -- a hashref without
2566 C<kind>, a value that is neither an object nor a hashref, an object that is
2567 no Kubernetes resource (an L<IO::K8s::List>, a nested type such as a
2568 C<PodSpec>), an object missing C<metadata>/C<metadata.name>, an unknown
2569 C<kind>, a C<kind> whose class does
2570 not load or is no resource class (see L</expand_class>), or an C<apiVersion>
2571 that resolves to no known class (the message names both the Kind and the
2572 C<apiVersion>) -- croak synchronously, as with L</update>. Anything that
2573 goes wrong during the request flow itself fails the Future instead.
2574  
2575 Arguments:
2576  
2577 =over 4
2578  
2579 =item C<$object> - IO::K8s object or hashref manifest (must have C<kind> if a
2580 hashref)
2581  
2582 =back
2583  
2584 =head2 ensure_all
2585  
2586 my $future = $kube->ensure_all(@objects);
2587 my @results = $future->get;
2588  
2589 Batch form of L</ensure>. Applies each object in order, one at a time --
2590 object N+1 is only started once object N has resolved, so a later object may
2591 depend on an earlier one (a Namespace before what lives in it). Returns a
2592 L<Future> that resolves to the list of results in input order.
2593  
2594 If any object fails -- including a croak from L</ensure>, which becomes a
2595 failure here -- the Future fails and no later object is started.
2596 C<ensure_all> itself never croaks synchronously.
2597  
2598 Arguments:
2599  
2600 =over 4
2601  
2602 =item C<@objects> - IO::K8s objects or hashref manifests, as accepted by
2603 L</ensure>
2604  
2605 =back
2606  
2607 =head2 ensure_only
2608  
2609 my $future = $kube->ensure_only(
2610 label => 'app.kubernetes.io/component=queen',
2611 objects => \@objects,
2612 kinds => [qw(Role RoleBinding ClusterRoleBinding)],
2613 namespaces => ['default', 'kube-system', undef],
2614 );
2615 my @applied = $future->get;
2616  
2617 Like L</ensure_all>, but also deletes anything matching the label selector in
2618 the given kinds and namespaces that is not present in C<objects>. Use this
2619 for resources where stale objects must not survive (e.g. RBAC). Croaks
2620 synchronously if C<label> is missing, if C<propagationPolicy> is none of
2621 the values L</delete> accepts, on any option not listed below -- a
2622 C<namespace> meant as C<namespaces> would otherwise prune at cluster scope
2623 only -- and on an odd list of options (C<Invalid arguments to
2624 ensure_only()>), whose last key would otherwise be taken as given without a
2625 value: a stray C<objects> would prune everything carrying the label.
2626  
2627 Hashrefs in C<objects> are resolved as in L</ensure>, all of them before the
2628 first request: one without C<kind> or with an C<apiVersion> no class serves
2629 croaks, and nothing is applied or deleted.
2630  
2631 Applies C<objects> via L</ensure_all>, then for each kind in C<kinds> and
2632 each namespace in C<namespaces>, lists resources of that kind carrying the
2633 label and deletes any that do not match one of the just-applied objects by
2634 API group, Kind, namespace and name. Group and Kind are each object's own --
2635 the group from its C<api_version>, the Kind from its C<kind> -- so a
2636 qualified C<'group/version/Kind'> entry in C<kinds> still recognises the
2637 objects it lists rather than deleting them. The same Kind name in another
2638 group is another resource: with Istio's C<networking.istio.io> Gateway in
2639 C<objects>, a labelled Gateway API C<gateway.networking.k8s.io> Gateway of
2640 the same name and namespace is deleted. The version is not compared: an
2641 object applied as C<autoscaling/v1> is kept when the listing goes through
2642 C<autoscaling/v2>. A C<namespaces> entry of C<undef> scans cluster-scoped
2643 resources; if C<namespaces> is omitted, only cluster-scoped resources are
2644 scanned.
2645  
2646 Stale objects are deleted with C<propagationPolicy> C<Background> unless
2647 C<propagationPolicy> says otherwise, so a pruned Job or Deployment takes its
2648 Pods with it; the API server's own default would leave a Job's Pods behind.
2649  
2650 Pruning goes on past a failure, and says so. When a C<kinds> entry cannot be
2651 listed in one namespace -- the API server rejects the request, the request
2652 fails without a response, or the entry resolves to no usable class -- that
2653 combination is skipped with a warning (C<carp>) naming the entry, the
2654 namespace (or cluster scope) and the reason; anything stale there survives
2655 this run. A 404 is silent: the cluster does not serve that Kind, so there is
2656 nothing to prune. A delete that fails warns with the Kind, name, namespace
2657 and reason, and the next object is tried; a 404 there means the object is
2658 already gone and is silent too. A C<$SIG{__WARN__}> handler that dies while
2659 the prune runs fails the returned L<Future> with the warning instead.
2660  
2661 Returns a L<Future> that resolves to the list of applied objects (from
2662 L</ensure_all>), whether or not the pruning was complete.
2663  
2664 Arguments:
2665  
2666 =over 4
2667  
2668 =item C<label> - Label selector matching stale objects to delete (required)
2669  
2670 =item C<objects> - ArrayRef of objects/hashrefs to apply, as for L</ensure_all>
2671  
2672 =item C<kinds> - ArrayRef of resource kinds to scan for stale objects
2673  
2674 =item C<namespaces> - ArrayRef of namespaces to scan, C<undef> for
2675 cluster-scoped; defaults to cluster-scoped only
2676  
2677 =item C<propagationPolicy> - How stale objects are deleted: C<'Background'>
2678 (default), C<'Foreground'> or C<'Orphan'>, as for L</delete>
2679  
2680 =back
2681  
2682 =head2 log
2683  
2684 # One-shot mode (Future resolves to full text)
2685 my $text = $kube->log('Pod', 'my-pod',
2686 namespace => 'default',
2687 tailLines => 100,
2688 )->get;
2689  
2690 # Streaming mode (Future resolves when stream ends)
2691 $kube->log('Pod', 'my-pod',
2692 namespace => 'default',
2693 follow => 1,
2694 on_line => sub {
2695 my ($event) = @_; # Kubernetes::REST::LogEvent
2696 say $event->line;
2697 },
2698 )->get;
2699  
2700 Retrieve logs from a pod.
2701  
2702 Without C<on_line>, returns a L<Future> that resolves to the full log text.
2703  
2704 With C<on_line>, opens a streaming request and invokes the callback once per
2705 line with L<Kubernetes::REST::LogEvent> objects. The returned L<Future>
2706 resolves when the stream ends.
2707  
2708 The log is returned as raw bytes in both modes, as L<Kubernetes::REST> does;
2709 decode it yourself (C<Encode::decode('UTF-8', $text)>) when you need
2710 characters.
2711  
2712 Besides C<name>, C<namespace> and C<on_line> it takes the options
2713 C<container>, C<follow>, C<tailLines>, C<sinceSeconds>, C<sinceTime>,
2714 C<timestamps>, C<previous> and C<limitBytes>, sent as query parameters. Any
2715 other -- C<tail_lines> would otherwise fetch the whole log -- fails the
2716 L<Future> before a request is sent.
2717  
2718 =head2 port_forward
2719  
2720 my $session = $kube->port_forward('Pod', 'my-pod',
2721 namespace => 'default',
2722 ports => [8080, 8443],
2723 on_data => sub { my ($session, $port, $bytes) = @_; ... },
2724 on_port_error => sub { my ($session, $port, $message) = @_; ... },
2725 on_error => sub { my ($error) = @_; ... },
2726 )->get;
2727  
2728 $session->write_port(8080, "GET / HTTP/1.0\r\n\r\n");
2729  
2730 Create an async pod port-forward session request.
2731  
2732 Returns a L<Future> that resolves to the duplex session object returned by the
2733 transport backend. The default transport returns a
2734 L<Net::Async::Kubernetes::PortForwardSession> in port-forward mode: it has
2735 C<write_port>, C<write_channel> and C<close>; C<write_stdin> and C<resize>
2736 belong to exec/attach and croak here (see L</Channels>).
2737  
2738 To forward a local TCP port instead of driving the connection by hand, see
2739 L</port_forward_listen>.
2740  
2741 =head3 Callbacks
2742  
2743 C<on_open> receives the created session object.
2744  
2745 C<on_data> is called as C<< $on_data->($session, $port, $bytes) >> with the
2746 bytes the pod side of the forwarded connection of remote C<$port> sent, port
2747 preamble stripped.
2748  
2749 C<on_port_error> is called as C<< $on_port_error->($session, $port, $message) >>
2750 with what the Kubelet wrote on the error channel of C<$port>: the reason it
2751 could not reach the port in the pod, as text.
2752  
2753 C<on_error> is called as C<< $on_error->($error) >> for transport problems and
2754 for frames that break the protocol: a first frame on a channel that is not
2755 exactly the two-byte port number of that channel's port (wrong number, or
2756 payload in the same frame), and a frame on a channel beyond the C<2 * N>
2757 channels of the C<N> requested ports. Such a frame is not passed on as data;
2758 after a bad preamble the channel delivers nothing further.
2759  
2760 C<on_frame> receives C<($channel, $payload)> where the first byte of each
2761 binary websocket frame is decoded as Kubernetes channel id. It is raw: the
2762 preamble frames are included. It is called in addition to C<on_data> and
2763 C<on_port_error>, for every frame, before them.
2764  
2765 C<on_close> is called once when the connection ends.
2766  
2767 All callbacks run inside the event loop and must not C<< ->get >> a Future.
2768  
2769 =head3 Channels
2770  
2771 A port-forward session does not use the exec/attach channel layout of
2772 L</exec>. For each requested port, counted from 0 in the order of C<ports>,
2773 the Kubelet opens two channels: the I<data> channel C<2 * $i> and the
2774 I<error> channel C<2 * $i + 1>. With C<< ports =E<gt> [8080, 8443] >>:
2775  
2776 channel 0 data of port 8080
2777 channel 1 error of port 8080
2778 channel 2 data of port 8443
2779 channel 3 error of port 8443
2780  
2781 Channel 3 is therefore the error channel of the second port, not a status
2782 stream. Bytes for the forwarded TCP connection are sent with
2783 C<< $session->write_port($port, $bytes) >> (or
2784 C<< write_channel(2 * $i, $bytes) >>).
2785  
2786 The first frame the server sends on every channel, data and error alike, is
2787 not payload: it is the port number as two bytes, little-endian
2788 (C<unpack('v', $payload)>), in a frame of its own. The library strips it and
2789 checks it against the port the channel belongs to before C<on_data> and
2790 C<on_port_error> see anything; only C<on_frame> sees it raw.
2791  
2792 =head3 Options
2793  
2794 It takes C<name>, C<namespace>, C<ports> (one port or an arrayref of them,
2795 required), C<subprotocol> (default C<v4.channel.k8s.io>) and the callbacks
2796 C<on_open>, C<on_frame>, C<on_data>, C<on_port_error>, C<on_close> and
2797 C<on_error>. Any other option -- a misspelt C<onFrame> would otherwise be
2798 dropped, a C<subresource> would even land in the request path -- fails the
2799 L<Future> before a request is sent, naming the options C<port_forward> takes.
2800  
2801 =head2 port_forward_listen
2802  
2803 my $listener = $kube->port_forward_listen('Pod', 'my-pod',
2804 namespace => 'default',
2805 ports => { 0 => 8080, 18443 => 8443 }, # local => remote
2806 host => '127.0.0.1',
2807 on_error => sub { my ($message) = @_; warn $message },
2808 )->get;
2809  
2810 my $local = $listener->port_for(8080); # the ephemeral port picked for local 0
2811 # ... connect to 127.0.0.1:$local, as with kubectl port-forward ...
2812 $listener->stop;
2813  
2814 Like C<kubectl port-forward>: listens on local TCP ports and forwards every
2815 accepted connection to a remote port of the pod. C<ports> is a hashref
2816 C<< local =E<gt> remote >>; a local port of C<0> lets the system pick one,
2817 which L<Net::Async::Kubernetes::PortForwardListener/port_for> reports. Remote
2818 ports must be unique. C<host> is the local address to bind, default
2819 C<127.0.0.1>. C<name>, C<namespace> and C<subprotocol> are as for
2820 L</port_forward>, and the call takes the same positional or keyed C<name>.
2821  
2822 Returns a L<Future> that resolves to a L<Net::Async::Kubernetes::PortForwardListener>
2823 once all local ports listen. Every incoming connection gets a port-forward
2824 session of its own for exactly its remote port, so two connections are two
2825 websocket sessions. Data that arrives before that session is open is held
2826 and sent when it is. When either side ends (connection closed, websocket
2827 closed, error on the pod's error channel, protocol error) the other is
2828 closed too; the reason is reported to C<on_error> (C<$message>) if given.
2829 The websocket has no half-close: a client that shuts down its sending side
2830 ends the whole forward.
2831  
2832 It fails the L<Future> without a request for an unknown option, a missing
2833 name, C<ports> that is not a non-empty hashref, a local port outside
2834 0 to 65535, a remote one outside 1 to 65535, and a client that is not in a
2835 loop. Failing to bind a local port fails it too, and closes those already
2836 bound.
2837  
2838 =head2 exec
2839  
2840 my $f = $kube->exec('Pod', 'my-pod',
2841 namespace => 'default',
2842 command => ['sh', '-c', 'id'],
2843 on_frame => sub { my ($channel, $payload) = @_; ... },
2844 );
2845 my $session = $f->get;
2846  
2847 Create an async pod exec session request.
2848  
2849 Returns a L<Future> that resolves to the duplex session object returned by the
2850 transport backend. The default transport returns a
2851 L<Net::Async::Kubernetes::PortForwardSession> object.
2852  
2853 The session helper supports C<write_channel>, C<write_stdin>, C<resize>, and
2854 C<close>.
2855  
2856 C<on_open> receives the created session object.
2857  
2858 C<on_frame> receives C<($channel, $payload)> where the first byte of each
2859 binary websocket frame is decoded as Kubernetes channel id.
2860  
2861 Besides C<name>, C<namespace>, C<command> (a string or an arrayref,
2862 required), C<subprotocol> and the callbacks it takes C<container>,
2863 C<stdin>, C<stdout>, C<stderr> and C<tty>, sent as query parameters
2864 (C<stdout> and C<stderr> default to true, the others to false). Any other
2865 option -- a misspelt C<container> would otherwise run the command in the
2866 pod's default container -- fails the L<Future> before a request is sent,
2867 naming the options C<exec> takes.
2868  
2869 =head2 attach
2870  
2871 my $f = $kube->attach('Pod', 'my-pod',
2872 namespace => 'default',
2873 container => 'app',
2874 stdin => 1,
2875 stdout => 1,
2876 stderr => 1,
2877 tty => 0,
2878 on_frame => sub { my ($channel, $payload) = @_; ... },
2879 );
2880 my $session = $f->get;
2881  
2882 Create an async pod attach session request.
2883  
2884 Returns a L<Future> that resolves to the duplex session object returned by the
2885 transport backend. The default transport returns a
2886 L<Net::Async::Kubernetes::PortForwardSession> object.
2887  
2888 The session helper supports C<write_channel>, C<write_stdin>, C<resize>, and
2889 C<close>.
2890  
2891 C<on_open> receives the created session object.
2892  
2893 C<on_frame> receives C<($channel, $payload)> where the first byte of each
2894 binary websocket frame is decoded as Kubernetes channel id.
2895  
2896 It takes C<name>, C<namespace>, C<container>, C<stdin>, C<stdout>,
2897 C<stderr>, C<tty>, C<subprotocol> and the callbacks, as L</exec> does, but
2898 no C<command>. Any other option, C<command> among them, fails the L<Future>
2899 before a request is sent, naming the options C<attach> takes.
2900  
2901 =head2 cp_to_pod
2902  
2903 my $f = $kube->cp_to_pod('Pod', 'my-pod',
2904 namespace => 'default',
2905 container => 'app',
2906 local => '/tmp/local.txt',
2907 remote => '/tmp/remote.txt',
2908 );
2909 my $result = $f->get;
2910  
2911 Copy a single local file into a pod. Reads the entire local file into memory,
2912 then runs C<sh -c 'head -c "$1" > "$2"'> inside the pod via C<exec()> and
2913 streams the bytes over stdin.
2914  
2915 This is a single-file copy, not a tar-based transfer: there is no recursive
2916 directory copy, and the whole file is held in memory, so it is not suitable
2917 for very large files.
2918  
2919 Returns a L<Future> resolving to a hashref containing C<local>, C<remote>,
2920 C<bytes>, C<stderr>, and C<status>.
2921  
2922 The copy only counts as done when the pod reported a C<Success> status on the
2923 status channel (3), which the C<v4.channel.k8s.io> protocol always sends at the
2924 end. A C<Failure> status, or a connection that closes without any status
2925 (dropped connection, restarted API server), fails the L<Future>.
2926  
2927 It takes C<name>, C<namespace>, C<container>, C<local>, C<remote> and
2928 C<chunk_size> (bytes per stdin write, default 65536). Any other option fails
2929 the L<Future> before a request is sent, naming the options C<cp_to_pod>
2930 takes.
2931  
2932 =head2 cp_from_pod
2933  
2934 my $f = $kube->cp_from_pod('Pod', 'my-pod',
2935 namespace => 'default',
2936 container => 'app',
2937 remote => '/tmp/remote.txt',
2938 local => '/tmp/local.txt',
2939 );
2940 my $result = $f->get;
2941  
2942 Copy a single file out of a pod. Runs C<cat $remote> inside the pod via
2943 C<exec()>, buffers the entire stdout stream in memory, then writes it to the
2944 local file.
2945  
2946 This is a single-file copy, not a tar-based transfer: there is no recursive
2947 directory copy, and the whole file is held in memory, so it is not suitable
2948 for very large files.
2949  
2950 Returns a L<Future> resolving to a hashref containing C<local>, C<remote>,
2951 C<bytes>, C<stderr>, and C<status>.
2952  
2953 The copy only counts as done when the pod reported a C<Success> status on the
2954 status channel (3), which the C<v4.channel.k8s.io> protocol always sends at the
2955 end. A C<Failure> status, or a connection that closes without any status
2956 (dropped connection, restarted API server), fails the L<Future> and the local
2957 file is not written. A failing write of the local file (C<open>, C<print> or
2958 C<close>, e.g. a full disk) fails it as well.
2959  
2960 It takes C<name>, C<namespace>, C<container>, C<remote> and C<local>. Any
2961 other option -- C<chunk_size> belongs to L</cp_to_pod> only -- fails the
2962 L<Future> before a request is sent, naming the options C<cp_from_pod>
2963 takes.
2964  
2965 =head2 watcher
2966  
2967 my $watcher = $kube->watcher('Pod',
2968 namespace => 'default',
2969 label_selector => 'app=web',
2970 on_added => sub { my ($pod) = @_; ... },
2971 on_modified => sub { my ($pod) = @_; ... },
2972 on_deleted => sub { my ($pod) = @_; ... },
2973 );
2974  
2975 Create and register a L<Net::Async::Kubernetes::Watcher> for the specified
2976 resource type. The watcher is added as a child notifier and will start
2977 automatically when the parent is added to a loop.
2978  
2979 Returns the watcher object. An odd list of parameters croaks, as
2980 C<Invalid arguments to watcher()>, before the watcher is created -- as an
2981 unknown parameter does.
2982  
2983 Arguments:
2984  
2985 =over 4
2986  
2987 =item C<$resource> - Resource type to watch (e.g., C<'Pod'>, C<'Deployment'>)
2988  
2989 =item C<%args> - Watcher parameters (C<namespace>, C<label_selector>, callbacks, etc.)
2990  
2991 =back
2992  
2993 See L<Net::Async::Kubernetes::Watcher> for all available parameters.
2994  
2995 =head2 controller
2996  
2997 my $controller = $kube->controller(
2998 on_reconcile => sub {
2999 my ($ctx) = @_;
3000 ...
3001 },
3002 );
3003  
3004 Create and register a L<Net::Async::Kubernetes::Controller> runtime bound to
3005 this client. The controller is added as a child notifier and can register
3006 resource watches, queue reconcile work, and patch object status.
3007  
3008 Returns the controller object. An odd list of parameters croaks, as
3009 C<Invalid arguments to controller()>, before the controller is created.
3010  
3011 =head1 ERRORS
3012  
3013 The C<Future>-returning methods report every failure through the returned
3014 L<Future>:
3015  
3016 =over 4
3017  
3018 =item * Bad arguments -- an unknown resource, an object that is no
3019 Kubernetes resource, a missing name, an unknown option -- fail it with a
3020 message before any request is sent. L</expand_class>, L</update>,
3021 L</update_status>, L</ensure> and a watcher that starts croak instead, as
3022 each of them documents.
3023  
3024 =item * A response the API server refuses (status 400 and up) fails it
3025 following L<Future>'s convention for failure details:
3026 C<< ->fail($error, 'http', $response) >>. C<$error> is exactly what
3027 L<Kubernetes::REST/check_response> throws, a L<Kubernetes::REST::APIError>
3028 object, which stringifies to the message
3029 (C<Kubernetes API error (get Pod): 404 ...>).
3030 C<$response> is the L<Kubernetes::REST::HTTPResponse>, whose C<status>
3031 tells a C<404> from a C<409> without parsing the message:
3032  
3033 $kube->delete('Pod', 'web', namespace => 'default')->catch(http => sub {
3034 my ($error, $category, $response) = @_;
3035 return Future->done if $response->status == 404; # already gone
3036 return Future->fail(@_);
3037 })->get;
3038  
3039 L</ensure> and L</ensure_all> pass the failure of the request that failed
3040 on in the same form.
3041  
3042 =item * A request that gets no response at all (connection refused, a TLS
3043 error) fails it the way the HTTP transport reports it.
3044  
3045 =back
3046  
3047 A L<Net::Async::Kubernetes::Watcher> reports failures to its C<on_error>
3048 callback instead, with the HTTP status in the C<code> of the C<Status> it
3049 passes.
3050  
3051 =head1 SEE ALSO
3052  
3053 L<Net::Async::Kubernetes::Watcher>, L<Net::Async::Kubernetes::Controller>,
3054 L<Net::Async::Kubernetes::PortForwardSession>, L<Kubernetes::REST>,
3055 L<IO::Async>, L<IO::K8s>, L<Net::Async::WebSocket::Client>
3056  
3057 =head1 SUPPORT
3058  
3059 =head2 Issues
3060  
3061 Please report bugs and feature requests on GitHub at
3062 L<https://github.com/Getty/p5-net-async-kubernetes/issues>.
3063  
3064 =head2 IRC
3065  
3066 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
3067  
3068 =head1 CONTRIBUTING
3069  
3070 Contributions are welcome! Please fork the repository and submit a pull request.
3071  
3072 =head1 AUTHOR
3073  
3074 Torsten Raudssus <torsten@raudssus.de>
3075  
3076 =head1 COPYRIGHT AND LICENSE
3077  
3078 This software is copyright (c) 2026 by Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>.
3079  
3080 This is free software; you can redistribute it and/or modify it under
3081 the same terms as the Perl 5 programming language system itself.
3082  
3083 =cut
« Kubernetes/Watcher.pm ↑ Summary Kubernetes/PortForwardSession.pm »