lib/Kubernetes/REST.pm

filter: Statementstmt 89.8% 784 / 873 Branchbran 74.8% 349 / 466 Conditioncond 55.7% 164 / 294 MC/DCmcdc 30.5% 51 / 167 Subroutinesub 98.1% 103 / 105 Podpod 65.2% 30 / 46 totaltotal 75.9% 1481 / 1951 CC 375 SCAR 33.2
CC
375
Cov
79%
ensure_only
342.0
ensure
79.6
_build_path
28.1
CRAP 27.6
« blib/lib/Kubernetes/REST/CLI/Watch.pm ↑ Summary blib/lib/Kubernetes/REST/CLI/Minikube.pm »
1 package Kubernetes::REST;
2 39 our $VERSION = '1.108';
3 # ABSTRACT: A Perl REST Client for the Kubernetes API
4 39 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 39 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 39 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 39 ▶use Module::Runtime qw(require_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 39 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 39 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 39 ▶use Kubernetes::REST::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 39 ▶use Kubernetes::REST::AuthToken;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 39 ▶use Kubernetes::REST::LWPIO;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 39 ▶use Kubernetes::REST::HTTPRequest;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 39 ▶use IO::K8s;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 39 ▶use IO::K8s::List;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 39 ▶use IO::K8s::CRD;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 39 ▶use IO::K8s::Unstructured ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 39 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 39 ▶use Kubernetes::REST::WatchEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 39 ▶use Kubernetes::REST::LogEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 39 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 has server => (
24 is => 'ro',
25 required => 1,
26 232 ▶ coerce => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
27 232 my $val = $_[0];
28 232 ▶ return $val if blessed($val) && $val->isa('Kubernetes::REST::Server');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($val) and $val->isa("Kubernetes::REST::Server") 231 1 232
Condition66%2/3
builtin::blessed($val) and $val->isa("Kubernetes::REST::Server")
!ll&&!rl&&r
10231
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
29 1 Kubernetes::REST::Server->new($val);
30 },
31 39 );
32  
33  
34 has credentials => (
35 is => 'ro',
36 required => 1,
37 232 ▶ coerce => sub {
Subroutine __ANON__: called CC=4 SCAR=14.6
38 232 my $val = $_[0];
39 232 ▶ return $val if blessed($val) && $val->can('token');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($val) and $val->can("token") 231 1 232
Condition66%2/3
builtin::blessed($val) and $val->can("token")
!ll&&!rl&&r
10231
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
40 1 ▶ return Kubernetes::REST::AuthToken->new($val) if ref($val) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $val eq "HASH" 1 0 1
41 0 return $val;
42 }
43 39 );
44  
45  
46 has io => (
47 is => 'ro',
48 lazy => 1,
49 1 ▶ default => sub {
Subroutine __ANON__: called CC=7 SCAR=23.2
50 1 my $self = shift;
51 1 my $s = $self->server;
52 1 ▶ Kubernetes::REST::LWPIO->new(
Branch: 6 branches
BranchTrueFalseTotal
defined $s->ssl_cert_pem ? : 0 1 1
defined $s->ssl_cert_file ? : 0 1 1
defined $s->ssl_key_pem ? : 0 1 1
defined $s->ssl_key_file ? : 0 1 1
defined $s->ssl_ca_pem ? : 0 1 1
defined $s->ssl_ca_file ? : 0 1 1
53 ssl_verify_server => $s->ssl_verify_server,
54 (defined $s->ssl_cert_pem ? (ssl_cert_pem => $s->ssl_cert_pem) : ()),
55 (defined $s->ssl_cert_file ? (ssl_cert_file => $s->ssl_cert_file) : ()),
56 (defined $s->ssl_key_pem ? (ssl_key_pem => $s->ssl_key_pem) : ()),
57 (defined $s->ssl_key_file ? (ssl_key_file => $s->ssl_key_file) : ()),
58 (defined $s->ssl_ca_pem ? (ssl_ca_pem => $s->ssl_ca_pem) : ()),
59 (defined $s->ssl_ca_file ? (ssl_ca_file => $s->ssl_ca_file) : ()),
60 );
61 },
62 39 );
63  
64  
65 # utf8 => 1 makes encode() return UTF-8 bytes and decode() expect them, which is
66 # what HTTP::Request->content requires and what IO::K8s already assumes. See the
67 # ENCODING section below.
68 has _json => (
69 is => 'ro',
70 232 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
71 232 JSON::MaybeXS->new(utf8 => 1, canonical => 1, convert_blessed => 1);
72 },
73 39 );
74  
75 # External IO::K8s resource-map providers, mirrored onto the inner instance.
76 has with => (
77 is => 'ro',
78 228 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
79 39 );
80  
81  
82 # IO::K8s instance - configured with same resource_map
83 has k8s => (
84 is => 'ro',
85 lazy => 1,
86 predicate => '_has_k8s',
87 clearer => '_clear_k8s',
88 123 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
89 123 my $self = shift;
90 return IO::K8s->new(
91 resource_map => $self->resource_map,
92 123 ▶ with => [ @{ $self->with } ],
Branch: 1 branch
BranchTrueFalseTotal
$self->_has_openapi_spec ? : 3 120 123
93 # openapi_spec is an eager hashref on IO::K8s: handing it over here
94 # only once it has actually been fetched keeps constructing/using
95 # the inner instance from forcing the /openapi/v2 download (D12).
96 # Until then it is absent; _openapi_spec's builder rebuilds this
97 # instance once the spec exists.
98 ($self->_has_openapi_spec ? (openapi_spec => $self->_openapi_spec) : ()),
99 );
100 },
101 39 handles => [qw(
102 new_object
103 inflate
104 json_to_object
105 struct_to_object
106 object_to_json
107 object_to_struct
108 load
109 load_yaml
110 )],
111 );
112  
113  
114 # Set to 0 to use IO::K8s defaults instead of loading from cluster
115 81 ▶has resource_map_from_cluster => (is => 'ro', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
116  
117  
118 # Cluster version - fetched once per instance
119 has cluster_version => (
120 is => 'ro',
121 lazy => 1,
122 2 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
123 2 my $self = shift;
124 2 my $response = $self->_request('GET', '/version');
125 2 ▶ return 'unknown' if $response->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status >= 400 1 1 2
126 1 my $info = $self->_json->decode($response->content);
127 1 ▶ return $info->{gitVersion} // 'unknown';
Condition50%1/2
$info->{"gitVersion"} // "unknown"
l!l
10
MC/DC0%0/1
$info->{"gitVersion"} // "unknown"
$info->{"gitVersion"}
Truth table50%1/2
A
A= $info->{"gitVersion"}
Aresult
11
00
128 },
129 39 );
130  
131  
132 # Resource map - loads from cluster by default, cached per instance (lazy)
133 # The predicate is true once the map exists: passed in by the caller, or
134 # built (fetched) on first use. expand_class() keys its cheap path off it.
135 has resource_map => (
136 is => 'ro',
137 lazy => 1,
138 predicate => '_has_resource_map',
139 clearer => '_clear_resource_map',
140 100 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
141 100 my $self = shift;
142 # A private copy, never IO::K8s's shared global map: the inner IO::K8s
143 # is handed this hashref and merges any `with` providers into it with
144 # add(), which mutates it in place. Returning the global ref would leak
145 # provider Kinds into IO::K8s->default_resource_map process-wide.
146 100 ▶ return { %{ IO::K8s->default_resource_map } } unless $self->resource_map_from_cluster;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->resource_map_from_cluster 89 11 100
147 11 return $self->_load_resource_map_from_cluster;
148 },
149 39 );
150  
151  
152 # Deliberately NOT delegated to the k8s attribute like the other IO::K8s
153 # methods: building that instance forces the lazy resource_map, which on the
154 # default resource_map_from_cluster => 1 is a full GET /openapi/v2 - paid for
155 # resolving a name like 'Pod' whose answer already sits in the built-in map
156 # (karr #15).
157 166 ▶sub expand_class {
Subroutine expand_class: called CC=16 SCAR=28.4
Pod documented
158 166 my ($self, @args) = @_;
159  
160  
161 166 ▶ if ($self->resource_map_from_cluster && !$self->_has_resource_map
Branch: 1 branch
BranchTrueFalseTotal
if ($self->resource_map_from_cluster and not $self->_has_resource_map and defined $args[0] and not ref $args[0]) 18 148 166
Condition77%7/9
$self->resource_map_from_cluster and not $self->_has_resource_map and defined $args[0] and not ref $args[0]
!ll&&!rl&&r
148018
$self->resource_map_from_cluster and not $self->_has_resource_map and defined $args[0]
!ll&&!rl&&r
148018
$self->resource_map_from_cluster and not $self->_has_resource_map
!ll&&!rl&&r
142618
MC/DC50%2/4
$self->resource_map_from_cluster and not $self->_has_resource_map and defined $args[0] and not ref $args[0]
$self->resource_map_from_cluster not $self->_has_resource_map defined $args[0] not ref $args[0]
Truth table60%3/5
A and not(B) and C and not(D)
A= $self->resource_map_from_clusterB= not $self->_has_resource_mapC= defined $args[0]D= not ref $args[0]
ABCDresult
0XXX0
10XX0
110X0
11100
11111
162 && defined $args[0] && !ref $args[0]) {
163 # '+Full::Class::Name' names an exact class - no map consulted either
164 # way, and by contract it is returned without being loaded.
165 18 ▶ return substr($args[0], 1) if $args[0] =~ /^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $args[0] =~ /^\+/ 2 16 18
166 # As a class method, IO::K8s->expand_class resolves against the
167 # built-in map. Its fallback for an unknown Kind is the *name*
168 # 'IO::K8s::<Kind>' whether or not such a class exists, so a cheap
169 # answer only counts when it names a class that actually loads.
170 # Anything else falls through to the cluster-backed instance below,
171 # which fetches the cluster map exactly as it always did.
172 16 my $class = IO::K8s->expand_class(@args);
173 return $class if defined $class
174 16 ▶ && ($class->can('new') || eval { require_module($class); 1 });
Branch: 1 branch
BranchTrueFalseTotal
if defined $class and $class->can("new") || eval { do { &require_module($class); 1 } } 6 10 16
Condition83%5/6
defined $class and $class->can("new") || eval {
!ll&&!rl&&r
0106
$class->can("new") or eval {
l!l&&r!l&&!r
5110
MC/DC66%2/3
defined $class and $class->can("new") || eval { do { &require_module($class); 1 } }
defined $class $class->can("new") eval { do { &require_module($class); 1 } }
Truth table75%3/4
A and B or C
A= defined $classB= $class->can("new")C= eval { do { &require_module($class); 1 } }
ABCresult
0XX0
1000
11X1
1011
175 }
176  
177 # Fall through to the cluster-backed inner IO::K8s, which owns the
178 # resolution order (design D13, extending the 2026-08-10 exact-GVK
179 # contract):
180 # rung 1 an explicit '+Full::Class' in the caller's resource_map
181 # rung 2 provider classes merged from `with`
182 # rung 3 AutoGen from openapi_spec, once the spec has been fetched
183 # rung 5 the existing fail-closed GVK error
184 # The discovery-built map (see _resource_map_from_catalog) no longer
185 # short-circuits this order with invented IO::K8s::Api::<Group> names for
186 # groups this distribution does not ship (D12): a foreign Kind with no
187 # provider and no loaded spec now reaches rung 4/5 instead of resolving to
188 # a bogus class.
189 158 my $class = $self->k8s->expand_class(@args);
190  
191 # How IO::K8s signals "nothing resolved this Kind" depends on the argument
192 # shape, and only that exact signal may be diverted to rung 4 -- every real
193 # resolution (rungs 1-3: a '+Full::Class', a provider from `with`, a builtin
194 # or an AutoGen class) must be returned untouched, including a '+'-class
195 # that names a class not yet loaded (returned by contract without loading,
196 # so a load probe would wrongly reject it -- karr t/36 subtest 3).
197 #
198 # For a bare Kind IO::K8s fails *open*: it fabricates the name
199 # 'IO::K8s::<Kind>' whether or not such a class exists, and the fail-closed
200 # error only surfaces later when require_module() cannot load it. For an
201 # exact-GVK or domain-qualified request it fails *closed*, returning undef.
202 # Both -- and nothing else -- mean unresolved.
203 158 my ($kind, $api_version) = $self->_kind_from_expand_args(@args);
204 my $unresolved =
205 !defined $class
206 || (defined $kind
207 && $class eq "IO::K8s::$kind"
208 158 ▶ && !($class->can('new') || eval { require_module($class); 1 }));
Condition66%8/12
!defined($class) || defined $kind && $class eq "IO::K8s::$kind" && !($class->can('new') || eval {
l!l&&r!l&&!r
013145
defined $kind and $class eq "IO::K8s::$kind" and not $class->can("new") || eval {
!ll&&!rl&&r
145013
defined $kind and $class eq "IO::K8s::$kind"
!ll&&!rl&&r
2911613
$class->can('new') || eval {
l!l&&r!l&&!r
0013
MC/DC40%2/5
!defined($class) || defined $kind && $class eq "IO::K8s::$kind" && !($class->can('new') || eval { do { &require_module($class); 1 } })
!defined($class) defined $kind $class eq "IO::K8s::$kind" $class->can('new') eval { do { &require_module($class); 1 } }
Truth table50%3/6
not(A) || B and C and not(D || E)
A= !defined($class)B= defined $kindC= $class eq "IO::K8s::$kind"D= $class->can('new')E= eval { do { &require_module($class); 1 } }
ABCDEresult
1XXXX1
011001
00XXX0
010XX0
0111X0
011010
209  
210 158 ▶ return $class unless $unresolved && defined $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless $unresolved and defined $kind 145 13 158
Condition66%2/3
$unresolved and defined $kind
!ll&&!rl&&r
145013
MC/DC50%1/2
$unresolved and defined $kind
$unresolved defined $kind
Truth table66%2/3
A and B
A= $unresolvedB= defined $kind
ABresult
0X0
100
111
211  
212 # Rung 4 (D16): the Kind resolved to nothing that ships. If the cluster
213 # confirms this GVK through aggregated discovery, resolve to
214 # IO::K8s::Unstructured -- its plural and scope come from the discovery
215 # catalog at path-build time (_build_path), since Unstructured carries no
216 # api_version()/resource_plural()/Namespaced role of its own. On by default
217 # (no opt-in here, unlike bare IO::K8s): D16 gates it on discovery
218 # confirmation instead. _discovery_path_meta is a no-op (undef) unless
219 # resource_map_from_cluster is set, and by the time control reaches here the
220 # catalog was already fetched building the cluster map, so this consults a
221 # cache and never adds a round-trip. A Kind discovery does not serve stays
222 # fail-closed (rung 5): the fabricated name (or undef) is returned so the
223 # load error still names the Kind. A discovery *failure* (cluster
224 # unreachable, expired token) is deliberately treated the same as "not
225 # served" here -- rung 5, fail-closed -- with the reason kept in
226 # _discovery_error; on the CRUD path the carp from
227 # _load_resource_map_from_cluster has already named it while building the
228 # cluster map.
229 13 ▶ return 'IO::K8s::Unstructured'
Branch: 1 branch
BranchTrueFalseTotal
if $self->_discovery_path_meta($kind, $api_version) 9 4 13
230 if $self->_discovery_path_meta($kind, $api_version);
231  
232 4 return $class;
233 }
234  
235 # Extract the Kubernetes Kind (and any explicitly supplied apiVersion) from an
236 # expand_class() argument list, for the D16 rung-4 discovery-confirmation
237 # check. Only bare short names ('Widget') and domain-qualified strings
238 # ('example.com/v1/Widget') name a Kind that Unstructured should stand in for;
239 # a '+Full::Class', an 'IO::K8s::...' name or any multi-segment package name is
240 # an explicit class request and must never be diverted to Unstructured.
241 158 ▶sub _kind_from_expand_args {
Subroutine _kind_from_expand_args: called CC=7 SCAR=21.5
242 158 my ($self, $name, $api_version) = @_;
243 158 ▶ return () unless defined $name && !ref $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name 0 158 158
Condition33%1/3
defined $name and not ref $name
!ll&&!rl&&r
00158
MC/DC0%0/2
defined $name and not ref $name
defined $name not ref $name
Truth table33%1/3
A and not(B)
A= defined $nameB= not ref $name
ABresult
0X0
100
111
244 158 ▶ return () if $name =~ /^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^\+/ 0 158 158
245 158 ▶ return () if $name =~ /^IO::K8s::/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^IO::K8s::/ 28 130 158
246 130 ▶ if ($name =~ m{/}) { # 'group/version/Kind' -> ('Kind', 'group/version')
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ m[/]) 0 130 130
247 0 my ($av, $kind) = $name =~ m{\A(.*)/([^/]+)\z};
248 0 return ($kind, $av);
249 }
250 130 ▶ return () if $name =~ /::/; # a multi-segment class name, not a Kind
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /::/ 1 129 130
251 129 return ($name, $api_version);
252 }
253  
254 # Path metadata (apiVersion, resource plural, namespaced) for a Kind, read from
255 # the cached discovery catalog. This is how a Kind resolved to
256 # IO::K8s::Unstructured (D16 rung 4) gets what _build_path needs: Unstructured
257 # has apiVersion/kind on the *instance* but no api_version()/resource_plural()
258 # class method and no Namespaced role, so plural and scope cannot come from the
259 # class the way a typed resource's do -- they come from here.
260 #
261 # Returns undef (fail-closed) unless resource_map_from_cluster is set: with no
262 # cluster there is no discovery to confirm a GVK, and this must never trigger a
263 # fetch on the fetch-free path. When it does run, the catalog is already cached
264 # (building the cluster resource map fetched it), so the lookup is free.
265 #
266 # A fetch that fails outright (cluster unreachable, expired token) returns the
267 # same undef as a healthy catalog that lacks the Kind -- deliberately
268 # fail-closed (D16: an unreachable cluster must not let anything pass as
269 # confirmed) -- but the reason is kept in _discovery_error so _build_path can
270 # name it instead of claiming a missing entry.
271 #
272 # $want_api_version, when given (an Unstructured object's own apiVersion),
273 # pins the group/version; otherwise the group's discovery-preferred version
274 # wins, matching _resource_map_from_catalog and D17.
275 23 ▶sub _discovery_path_meta {
Subroutine _discovery_path_meta: called CC=15 SCAR=30.5
276 23 my ($self, $kind, $want_api_version) = @_;
277 23 ▶ return unless $self->resource_map_from_cluster;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->resource_map_from_cluster 2 21 23
278 21 my $catalog = eval { $self->_discovery };
279 21 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 2 19 21
280 2 $self->_discovery_error($error);
281 2 return;
282 }
283 19 $self->_clear_discovery_error;
284 19 ▶ return unless $catalog && $catalog->{groups};
Branch: 1 branch
BranchTrueFalseTotal
unless $catalog and $catalog->{"groups"} 0 19 19
Condition33%1/3
$catalog and $catalog->{"groups"}
!ll&&!rl&&r
0019
MC/DC0%0/2
$catalog and $catalog->{"groups"}
$catalog $catalog->{"groups"}
Truth table33%1/3
A and B
A= $catalogB= $catalog->{"groups"}
ABresult
0X0
100
111
285  
286 15 ▶ my $meta_for = sub {
Subroutine __ANON__: called CC=4 SCAR=14.3
287 15 my ($group, $version, $res) = @_;
288 return {
289 api_version => ($group eq '' ? $version : "$group/$version"),
290 resource => $res->{resource},
291 15 ▶ namespaced => ($res->{scope} && $res->{scope} eq 'Namespaced' ? 1 : 0),
Branch: 2 branches
BranchTrueFalseTotal
$group eq '' ? : 0 15 15
$res->{'scope'} && $res->{'scope'} eq 'Namespaced' ? : 13 2 15
Condition66%2/3
$res->{"scope"} and $res->{"scope"} eq "Namespaced"
!ll&&!rl&&r
0213
MC/DC50%1/2
$res->{"scope"} and $res->{"scope"} eq "Namespaced"
$res->{"scope"} $res->{"scope"} eq "Namespaced"
Truth table66%2/3
A and B
A= $res->{"scope"}B= $res->{"scope"} eq "Namespaced"
ABresult
0X0
100
111
292 };
293 19 };
294  
295 # An explicit apiVersion pins the exact group/version first.
296 19 ▶ if (defined $want_api_version && length $want_api_version) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $want_api_version and length $want_api_version) 0 19 19
Condition33%1/3
defined $want_api_version and length $want_api_version
!ll&&!rl&&r
1900
MC/DC0%0/2
defined $want_api_version and length $want_api_version
defined $want_api_version length $want_api_version
Truth table33%1/3
A and B
A= defined $want_api_versionB= length $want_api_version
ABresult
0X0
100
111
297 0 ▶ my ($g, $v) = $want_api_version =~ m{/}
Branch: 1 branch
BranchTrueFalseTotal
$want_api_version =~ m[/] ? : 0 0 0
298 ? split(m{/}, $want_api_version, 2)
299 : ('', $want_api_version);
300 0 my $res = $catalog->{groups}{$g}{versions}{$v}{kinds}{$kind};
301 0 ▶ return $meta_for->($g, $v, $res) if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 0 0 0
302 }
303  
304 # Otherwise the preferred version of whichever group serves the Kind.
305 19 for my $group (sort keys %{$catalog->{groups}}) {
306 46 my $gdata = $catalog->{groups}{$group};
307 46 ▶ my @order = @{$gdata->{version_order} // []};
Condition50%1/2
$gdata->{"version_order"} // []
l!l
460
MC/DC0%0/1
$gdata->{"version_order"} // []
$gdata->{"version_order"}
Truth table50%1/2
A
A= $gdata->{"version_order"}
Aresult
11
00
308 46 my $pref = $gdata->{preferred};
309 47 @order = ($pref, grep { $_ ne $pref } @order)
310 46 ▶ if defined $pref && grep { $_ eq $pref } @order;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pref and grep {$_ eq $pref;} @order 46 0 46
Condition33%1/3
defined $pref and grep {$_ eq $pref;} @order
!ll&&!rl&&r
0046
MC/DC0%0/2
defined $pref and grep {$_ eq $pref;} @order
defined $pref grep {$_ eq $pref;} @order
Truth table33%1/3
A and B
A= defined $prefB= grep {$_ eq $pref;} @order
ABresult
0X0
100
111
311 46 for my $version (@order) {
312 46 my $res = $gdata->{versions}{$version}{kinds}{$kind};
313 46 ▶ return $meta_for->($group, $version, $res) if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 15 31 46
314 }
315 }
316 4 return;
317 }
318  
319 # The extra _build_path arguments an IO::K8s::Unstructured resolution needs,
320 # derived from whatever identifier expand_class was given: an IO::K8s object
321 # (its kind/apiVersion accessors) or a name string (the Kind is its last
322 # '/'-delimited segment). Empty for every typed class, so typed path building
323 # is completely unchanged.
324 162 ▶sub _unstructured_hint {
Subroutine _unstructured_hint: called CC=5 SCAR=18.1
325 162 my ($self, $class, $ident) = @_;
326 162 ▶ return () unless defined $class && $class eq 'IO::K8s::Unstructured';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and $class eq "IO::K8s::Unstructured" 160 2 162
Condition66%2/3
defined $class and $class eq "IO::K8s::Unstructured"
!ll&&!rl&&r
01602
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
327 2 ▶ if (blessed($ident)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($ident)) 0 2 2
328 return (
329 0 ▶ kind => $ident->kind,
Branch: 1 branch
BranchTrueFalseTotal
defined $ident->apiVersion ? : 0 0 0
330 (defined $ident->apiVersion ? (api_version => $ident->apiVersion) : ()),
331 );
332 }
333 2 return (kind => (split m{/}, $ident)[-1]);
334 }
335  
336 # Kubernetes groups whose IO::K8s classes do NOT live under IO::K8s::Api::.
337 # Their namespace follows the upstream Go staging repository the types are
338 # generated from (apiextensions-apiserver, kube-aggregator), not the API group
339 # name, so it cannot be derived - it has to be listed here.
340 #
341 # Keyed on the full group name, because that is the only globally unique
342 # identifier: a cluster is free to serve a CRD group called
343 # apiextensions.example.com, and that group is an ordinary one.
344 39 my %NON_API_NAMESPACE = (
345 'apiextensions.k8s.io' => 'ApiextensionsApiserver::Pkg::Apis::Apiextensions',
346 'apiregistration.k8s.io' => 'KubeAggregator::Pkg::Apis::Apiregistration',
347 );
348  
349 # The same table, indexed by the IO::K8s group directory instead - the trailing
350 # segment of each namespace above is exactly that directory name. Derived, so
351 # there is still only one place to add a group.
352 my %NON_API_NAMESPACE_BY_GROUP_PATH =
353 39 map { ((split /::/)[-1] => $_) } values %NON_API_NAMESPACE;
354  
355 # Namespace below IO::K8s:: for a Kubernetes API group name as the cluster's
356 # OpenAPI spec reports it: '' for core, 'apps', 'apiextensions.k8s.io',
357 # 'cert-manager.io', ... The exception table is matched exactly on the full
358 # name - a CRD group that merely starts with 'apiextensions' is an ordinary
359 # group and must keep landing under Api::.
360 112 ▶sub _io_k8s_namespace_for_group {
Subroutine _io_k8s_namespace_for_group: called CC=3 SCAR=11.0
361 112 my ($self, $group) = @_;
362 112 ▶ return $NON_API_NAMESPACE{$group} if exists $NON_API_NAMESPACE{$group};
Branch: 1 branch
BranchTrueFalseTotal
if exists $NON_API_NAMESPACE{$group} 15 97 112
363 97 ▶ return 'Api::' . ($group eq '' ? 'Core' : ucfirst(lc((split /\./, $group)[0])));
Branch: 1 branch
BranchTrueFalseTotal
$group eq '' ? : 36 61 97
364 }
365  
366 # Namespace below IO::K8s:: for an IO::K8s group directory name - 'Core',
367 # 'Apps', 'Apiextensions'. That is the form the v0 compatibility layer carries,
368 # and it is a closed set of names this distribution ships, so unlike a group
369 # name off the wire it needs no exact-match guard.
370 55 ▶sub _io_k8s_namespace_for_group_path {
Subroutine _io_k8s_namespace_for_group_path: called CC=2 SCAR=6.9
371 55 my ($self, $group_path) = @_;
372 55 ▶ return $NON_API_NAMESPACE_BY_GROUP_PATH{$group_path} // "Api::${group_path}";
Condition100%2/2
$NON_API_NAMESPACE_BY_GROUP_PATH{$group_path} // "Api::$group_path"
l!l
946
MC/DC100%1/1
$NON_API_NAMESPACE_BY_GROUP_PATH{$group_path} // "Api::$group_path"
$NON_API_NAMESPACE_BY_GROUP_PATH{$group_path}
Truth table100%2/2
A
A= $NON_API_NAMESPACE_BY_GROUP_PATH{$group_path}
Aresult
11
00
373 }
374  
375 # Public method to build the resource map from the cluster's discovery catalog
376 30 ▶sub fetch_resource_map {
Subroutine fetch_resource_map: called CC=2 SCAR=6.9
Pod documented
377 30 my ($self) = @_;
378  
379  
380 # The cluster resource map is built from aggregated discovery, not from the
381 # multi-MB /openapi/v2 spec (design D11): a small GET /api + GET /apis gives
382 # every group, version, plural, Kind and scope. The catalog is cached in the
383 # _discovery attribute and shared by later rebuilds; /openapi/v2 stays lazy
384 # for schema_for/compare_schema only. The failure keeps this method's
385 # documented wording; the underlying error rides along.
386 30 my $catalog = eval { $self->_discovery };
387 30 ▶ croak "Could not load resource map from cluster: $@" unless $catalog;
Branch: 1 branch
BranchTrueFalseTotal
unless $catalog 5 25 30
388  
389 25 return $self->_resource_map_from_catalog($catalog);
390 }
391  
392 # Turn the cached discovery catalog into the short-name -> IO::K8s class map.
393 # The namespace comes from _io_k8s_namespace_for_group (exception tables
394 # included) and List kinds are skipped. Two rules shape which entries land:
395 #
396 # D17 preferred version: among the versions a group serves a Kind in, the
397 # version the cluster marks preferred wins the bare short name (not "stable
398 # beats alpha/beta" -- that heuristic is gone). A Kind served only outside
399 # the preferred version still maps, to its first served version, so nothing
400 # the cluster serves is dropped.
401 #
402 # D12/D13 stop inventing: an entry is recorded only when the candidate
403 # IO::K8s class actually ships. A foreign group (cilium.io, cert-manager.io)
404 # has no IO::K8s::Api::<Group> class, so its Kinds are omitted here and left
405 # to resolve through the inner IO::K8s pipeline (provider from `with` ->
406 # AutoGen from openapi_spec -> D16 Unstructured -> fail-closed) rather than
407 # short-circuiting to a bogus name. Core-API groups and the two exception
408 # groups (apiextensions/apiregistration) do ship, so their Kinds map exactly
409 # as before.
410 25 ▶sub _resource_map_from_catalog {
Subroutine _resource_map_from_catalog: called CC=11 SCAR=24.3
411 25 my ($self, $catalog) = @_;
412  
413 25 my %map;
414 25 ▶ for my $group (keys %{$catalog->{groups} // {}}) {
Condition50%1/2
$catalog->{"groups"} // {}
l!l
250
MC/DC0%0/1
$catalog->{"groups"} // {}
$catalog->{"groups"}
Truth table50%1/2
A
A= $catalog->{"groups"}
Aresult
11
00
415 81 my $gdata = $catalog->{groups}{$group};
416  
417 # D17: try the cluster's preferred version first, then the rest in
418 # discovery order; the first version to yield a shipping class for a
419 # Kind keeps the short name. Where the preferred version's class does
420 # not ship but another served version's does, the Kind still maps to
421 # that other version rather than vanishing.
422 81 ▶ my @order = @{$gdata->{version_order} // []};
Condition50%1/2
$gdata->{"version_order"} // []
l!l
810
MC/DC0%0/1
$gdata->{"version_order"} // []
$gdata->{"version_order"}
Truth table50%1/2
A
A= $gdata->{"version_order"}
Aresult
11
00
423 81 my $pref = $gdata->{preferred};
424 93 @order = ($pref, grep { $_ ne $pref } @order)
425 81 ▶ if defined $pref && grep { $_ eq $pref } @order;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pref and grep {$_ eq $pref;} @order 81 0 81
Condition33%1/3
defined $pref and grep {$_ eq $pref;} @order
!ll&&!rl&&r
0081
MC/DC0%0/2
defined $pref and grep {$_ eq $pref;} @order
defined $pref grep {$_ eq $pref;} @order
Truth table33%1/3
A and B
A= defined $prefB= grep {$_ eq $pref;} @order
ABresult
0X0
100
111
426  
427 81 for my $version (@order) {
428 93 my $kinds = $gdata->{versions}{$version}{kinds};
429 93 for my $kind (keys %$kinds) {
430 112 ▶ next if $kind =~ /List$/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind =~ /List$/ 1 111 112
431 111 ▶ next if exists $map{$kind}; # a preferred/earlier version won it
Branch: 1 branch
BranchTrueFalseTotal
if exists $map{$kind} 6 105 111
432  
433 105 my $version_path = ucfirst($version);
434 105 my $new_path = $self->_io_k8s_namespace_for_group($group)
435 . "::${version_path}::${kind}";
436  
437 # D12/D13: only record a class name this distribution ships.
438 105 ▶ next unless $self->_io_k8s_class_ships($new_path);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_io_k8s_class_ships($new_path) 38 67 105
439  
440 67 $map{$kind} = $new_path;
441 }
442 }
443 }
444  
445 25 return \%map;
446 }
447  
448 # Process-wide cache for the D12/D13 "stop inventing" loadability probe: a
449 # relative class path is either shipped (a real IO::K8s class that loads) or it
450 # is not, and that never changes within a run. Keyed by the relative path, so
451 # it is shared across instances.
452 39 my %_CLASS_SHIPS;
453  
454 # True when 'IO::K8s::<rel_path>' is a real, loadable class. The discovery map
455 # is built from group/version/Kind triples off the wire; without this probe
456 # every foreign CRD group would map to an IO::K8s::Api::<Group>::... name that
457 # has no class behind it (design D12). require the candidate once -- already
458 # loaded classes short-circuit on ->can('new') -- and remember the answer.
459 105 ▶sub _io_k8s_class_ships {
Subroutine _io_k8s_class_ships: called CC=4 SCAR=13.9
460 105 my ($self, $rel_path) = @_;
461 105 ▶ return $_CLASS_SHIPS{$rel_path} //= do {
Condition100%3/3
$_CLASS_SHIPS{$rel_path} //= do {
l!l&&r!l&&!r
77199
MC/DC100%2/2
$_CLASS_SHIPS{$rel_path} //= do { my $full = "IO::K8s::$rel_path"; $full->can("new") || eval { do { &require_module($full); 1 } } ? 1 : 0 }
$_CLASS_SHIPS{$rel_path} do { my $full = "IO::K8s::$rel_path"; $full->can("new") || eval { do { &require_module($full); 1 } } ? 1 : 0 }
Truth table100%3/3
A //= B
A= $_CLASS_SHIPS{$rel_path}B= do { my $full = "IO::K8s::$rel_path"; $full->can("new") || eval { do { &require_module($full); 1 } } ? 1 : 0 }
ABresult
1X1
011
000
462 28 my $full = "IO::K8s::$rel_path";
463 28 ▶ ($full->can('new') || eval { require_module($full); 1 }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$full->can('new') || eval { do { &require_module($full); 1 } } ? : 19 9 28
Condition100%3/3
$full->can("new") or eval {
l!l&&r!l&&!r
3169
MC/DC100%2/2
$full->can("new") or eval { do { &require_module($full); 1 } }
$full->can("new") eval { do { &require_module($full); 1 } }
Truth table100%3/3
A or B
A= $full->can("new")B= eval { do { &require_module($full); 1 } }
ABresult
1X1
011
000
464 };
465 }
466  
467 # Per-instance discovery catalog, keyed by group. Shape:
468 # { groups => { <group> => {
469 # preferred => <version>, # first version the cluster serves
470 # version_order => [ <version>, ... ], # discovery order, preferred first
471 # versions => { <version> => { kinds => {
472 # <Kind> => { resource => <plural>, scope => 'Namespaced'|'Cluster' },
473 # } } },
474 # } } }
475 # Built lazily on first use and invalidated by invalidate_discovery.
476 has _discovery => (
477 is => 'lazy',
478 predicate => '_has_discovery',
479 clearer => '_clear_discovery',
480 6 ▶ builder => sub { $_[0]->_fetch_discovery },
Subroutine _build__discovery: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
481 39 );
482  
483 # The reason ($@ text) the last discovery fetch attempted from
484 # _discovery_path_meta failed, kept so the croak in _build_path can name it: a
485 # failed fetch and a healthy catalog without the Kind both come back from
486 # _discovery_path_meta as undef (fail-closed, D16), and only this tells them
487 # apart. Cleared by the next successful fetch and by invalidate_discovery.
488 39 has _discovery_error => (
489 is => 'rw',
490 clearer => '_clear_discovery_error',
491 );
492  
493 # Aggregated discovery v2 (Kubernetes >= 1.27): GET /api and GET /apis with an
494 # Accept header selecting APIGroupDiscoveryList answer every group, version,
495 # resource plural, Kind and scope in one small response each. A server that does
496 # not understand the header ignores the as= parameter and returns the legacy
497 # document (APIVersions / APIGroupList) - detected by the kind - and the
498 # per-group APIResourceList fallback fills the catalog instead.
499 39 my $DISCOVERY_ACCEPT =
500 'application/json;g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList';
501  
502 32 ▶sub _fetch_discovery {
Subroutine _fetch_discovery: called CC=7 SCAR=19.5
503 32 my ($self) = @_;
504  
505 32 my $catalog = { groups => {} };
506  
507 32 for my $root ('/api', '/apis') {
508 57 my $response = $self->_request('GET', $root, undef,
509 headers => { Accept => $DISCOVERY_ACCEPT });
510 57 ▶ croak "discovery GET $root failed: " . $response->status
Branch: 1 branch
BranchTrueFalseTotal
if $response->status >= 400 7 50 57
511 if $response->status >= 400;
512  
513 50 my $body = $self->_json->decode($response->content);
514 50 ▶ my $kind = ref $body eq 'HASH' ? ($body->{kind} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $body eq 'HASH' ? : 50 0 50
Condition50%1/2
$body->{"kind"} // ""
l!l
500
MC/DC0%0/1
$body->{"kind"} // ""
$body->{"kind"}
Truth table50%1/2
A
A= $body->{"kind"}
Aresult
11
00
515  
516 50 ▶ if ($kind eq 'APIGroupDiscoveryList') {
Branch: 2 branches
BranchTrueFalseTotal
if ($kind eq 'APIGroupDiscoveryList') { } 48 2 50
elsif ($root eq '/api') { } 1 1 2
517 48 $self->_absorb_discovery_list($catalog, $body);
518 } elsif ($root eq '/api') {
519 1 $self->_fetch_discovery_legacy_core($catalog, $body);
520 } else {
521 1 $self->_fetch_discovery_legacy_groups($catalog, $body);
522 }
523 }
524  
525 25 return $catalog;
526 }
527  
528 # APIGroupDiscoveryList (aggregated discovery v2). Each item is one group; the
529 # order of its versions is the cluster's preference, so the first is preferred.
530 48 ▶sub _absorb_discovery_list {
Subroutine _absorb_discovery_list: called CC=15 SCAR=30.1
531 48 my ($self, $catalog, $body) = @_;
532  
533 48 ▶ for my $group_item (@{$body->{items} // []}) {
Condition50%1/2
$body->{"items"} // []
l!l
480
MC/DC0%0/1
$body->{"items"} // []
$body->{"items"}
Truth table50%1/2
A
A= $body->{"items"}
Aresult
11
00
534 78 ▶ my $group = $group_item->{metadata}{name} // '';
Condition50%1/2
$group_item->{"metadata"}{"name"} // ""
l!l
780
MC/DC0%0/1
$group_item->{"metadata"}{"name"} // ""
$group_item->{"metadata"}{"name"}
Truth table50%1/2
A
A= $group_item->{"metadata"}{"name"}
Aresult
11
00
535 78 ▶ my @versions = @{$group_item->{versions} // []};
Condition50%1/2
$group_item->{"versions"} // []
l!l
780
MC/DC0%0/1
$group_item->{"versions"} // []
$group_item->{"versions"}
Truth table50%1/2
A
A= $group_item->{"versions"}
Aresult
11
00
536 78 for my $i (0 .. $#versions) {
537 89 my $vd = $versions[$i];
538 89 my $version = $vd->{version};
539 89 ▶ next unless defined $version && length $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and length $version 0 89 89
Condition33%1/3
defined $version and length $version
!ll&&!rl&&r
0089
MC/DC0%0/2
defined $version and length $version
defined $version length $version
Truth table33%1/3
A and B
A= defined $versionB= length $version
ABresult
0X0
100
111
540 89 ▶ for my $res (@{$vd->{resources} // []}) {
Condition50%1/2
$vd->{"resources"} // []
l!l
890
MC/DC0%0/1
$vd->{"resources"} // []
$vd->{"resources"}
Truth table50%1/2
A
A= $vd->{"resources"}
Aresult
11
00
541 108 my $plural = $res->{resource};
542 108 my $rkind = $res->{responseKind}{kind};
543 108 ▶ next unless defined $plural && defined $rkind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plural and defined $rkind 0 108 108
Condition33%1/3
defined $plural and defined $rkind
!ll&&!rl&&r
00108
MC/DC0%0/2
defined $plural and defined $rkind
defined $plural defined $rkind
Truth table33%1/3
A and B
A= defined $pluralB= defined $rkind
ABresult
0X0
100
111
544 $self->_catalog_add($catalog, $group, $version, $rkind,
545 108 ▶ $plural, $res->{scope} // '');
Condition50%1/2
$res->{"scope"} // ""
l!l
1080
MC/DC0%0/1
$res->{"scope"} // ""
$res->{"scope"}
Truth table50%1/2
A
A= $res->{"scope"}
Aresult
11
00
546 }
547 # First version served = preferred version for the group.
548 $catalog->{groups}{$group}{preferred} = $version
549 89 ▶ if $i == 0 && exists $catalog->{groups}{$group};
Branch: 1 branch
BranchTrueFalseTotal
if $i == 0 and exists $catalog->{"groups"}{$group} 78 11 89
Condition66%2/3
$i == 0 and exists $catalog->{"groups"}{$group}
!ll&&!rl&&r
11078
MC/DC50%1/2
$i == 0 and exists $catalog->{"groups"}{$group}
$i == 0 exists $catalog->{"groups"}{$group}
Truth table66%2/3
A and B
A= $i == 0B= exists $catalog->{"groups"}{$group}
ABresult
0X0
100
111
550 }
551 }
552 }
553  
554 # Legacy fallback for GET /api: an APIVersions document. Each version's
555 # APIResourceList is fetched from /api/<version>.
556 1 ▶sub _fetch_discovery_legacy_core {
Subroutine _fetch_discovery_legacy_core: called CC=6 SCAR=19.1
557 1 my ($self, $catalog, $body) = @_;
558  
559 1 ▶ my @versions = @{$body->{versions} // []};
Condition50%1/2
$body->{"versions"} // []
l!l
10
MC/DC0%0/1
$body->{"versions"} // []
$body->{"versions"}
Truth table50%1/2
A
A= $body->{"versions"}
Aresult
11
00
560 1 for my $version (@versions) {
561 1 my $response = $self->_request('GET', "/api/$version");
562 1 ▶ next if $response->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status >= 400 0 1 1
563 1 my $list = $self->_json->decode($response->content);
564 1 $self->_absorb_api_resource_list($catalog, '', $version, $list);
565 }
566 $catalog->{groups}{''}{preferred} = $versions[0]
567 1 ▶ if @versions && exists $catalog->{groups}{''};
Branch: 1 branch
BranchTrueFalseTotal
if @versions and exists $catalog->{"groups"}{""} 1 0 1
Condition33%1/3
@versions and exists $catalog->{"groups"}{""}
!ll&&!rl&&r
001
MC/DC0%0/2
@versions and exists $catalog->{"groups"}{""}
@versions exists $catalog->{"groups"}{""}
Truth table33%1/3
A and B
A= @versionsB= exists $catalog->{"groups"}{""}
ABresult
0X0
100
111
568 }
569  
570 # Legacy fallback for GET /apis: an APIGroupList document. Each group/version's
571 # APIResourceList is fetched from /apis/<group>/<version>.
572 1 ▶sub _fetch_discovery_legacy_groups {
Subroutine _fetch_discovery_legacy_groups: called CC=12 SCAR=28.5
573 1 my ($self, $catalog, $body) = @_;
574  
575 1 ▶ for my $group (@{$body->{groups} // []}) {
Condition50%1/2
$body->{"groups"} // []
l!l
10
MC/DC0%0/1
$body->{"groups"} // []
$body->{"groups"}
Truth table50%1/2
A
A= $body->{"groups"}
Aresult
11
00
576 1 my $gname = $group->{name};
577 1 ▶ next unless defined $gname && length $gname;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gname and length $gname 0 1 1
Condition33%1/3
defined $gname and length $gname
!ll&&!rl&&r
001
MC/DC0%0/2
defined $gname and length $gname
defined $gname length $gname
Truth table33%1/3
A and B
A= defined $gnameB= length $gname
ABresult
0X0
100
111
578 1 ▶ for my $v (@{$group->{versions} // []}) {
Condition50%1/2
$group->{"versions"} // []
l!l
10
MC/DC0%0/1
$group->{"versions"} // []
$group->{"versions"}
Truth table50%1/2
A
A= $group->{"versions"}
Aresult
11
00
579 1 my $version = $v->{version};
580 1 ▶ next unless defined $version && length $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and length $version 0 1 1
Condition33%1/3
defined $version and length $version
!ll&&!rl&&r
001
MC/DC0%0/2
defined $version and length $version
defined $version length $version
Truth table33%1/3
A and B
A= defined $versionB= length $version
ABresult
0X0
100
111
581 1 my $response = $self->_request('GET', "/apis/$gname/$version");
582 1 ▶ next if $response->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status >= 400 0 1 1
583 1 my $list = $self->_json->decode($response->content);
584 1 $self->_absorb_api_resource_list($catalog, $gname, $version, $list);
585 }
586 1 my $pref = $group->{preferredVersion}{version};
587 $catalog->{groups}{$gname}{preferred} = $pref
588 1 ▶ if defined $pref && exists $catalog->{groups}{$gname};
Branch: 1 branch
BranchTrueFalseTotal
if defined $pref and exists $catalog->{"groups"}{$gname} 1 0 1
Condition33%1/3
defined $pref and exists $catalog->{"groups"}{$gname}
!ll&&!rl&&r
001
MC/DC0%0/2
defined $pref and exists $catalog->{"groups"}{$gname}
defined $pref exists $catalog->{"groups"}{$gname}
Truth table33%1/3
A and B
A= defined $prefB= exists $catalog->{"groups"}{$gname}
ABresult
0X0
100
111
589 }
590 }
591  
592 # APIResourceList (legacy per-group discovery). Subresource entries carry a
593 # slash in their name (pods/status) and are skipped; scope comes from the
594 # namespaced boolean.
595 2 ▶sub _absorb_api_resource_list {
Subroutine _absorb_api_resource_list: called CC=8 SCAR=21.6
596 2 my ($self, $catalog, $group, $version, $list) = @_;
597  
598 2 ▶ for my $res (@{$list->{resources} // []}) {
Condition50%1/2
$list->{"resources"} // []
l!l
20
MC/DC0%0/1
$list->{"resources"} // []
$list->{"resources"}
Truth table50%1/2
A
A= $list->{"resources"}
Aresult
11
00
599 4 my $name = $res->{name};
600 4 ▶ next unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 4 4
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
004
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
601 4 ▶ next if $name =~ m{/};
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ m[/] 1 3 4
602 3 my $kind = $res->{kind};
603 3 ▶ next unless defined $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind 0 3 3
604 3 ▶ my $scope = $res->{namespaced} ? 'Namespaced' : 'Cluster';
Branch: 1 branch
BranchTrueFalseTotal
$res->{'namespaced'} ? : 2 1 3
605 3 $self->_catalog_add($catalog, $group, $version, $kind, $name, $scope);
606 }
607 }
608  
609 # Register one Kind (plural, scope) under a group/version in the catalog,
610 # tracking version discovery order.
611 111 ▶sub _catalog_add {
Subroutine _catalog_add: called CC=3 SCAR=11.0
612 111 my ($self, $catalog, $group, $version, $kind, $plural, $scope) = @_;
613  
614 111 ▶ my $gdata = $catalog->{groups}{$group} ||= {
Condition100%2/2
$catalog->{"groups"}{$group} ||= {"preferred", undef, "version_order", [], "versions", {}}
l!l
3180
MC/DC100%1/1
$catalog->{"groups"}{$group} ||= {"preferred", undef, "version_order", [], "versions", {}}
$catalog->{"groups"}{$group}
Truth table100%2/2
A
A= $catalog->{"groups"}{$group}
Aresult
11
00
615 preferred => undef, version_order => [], versions => {},
616 };
617 111 ▶ unless (exists $gdata->{versions}{$version}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $gdata->{"versions"}{$version}) 91 20 111
618 91 $gdata->{versions}{$version} = { kinds => {} };
619 91 push @{$gdata->{version_order}}, $version;
620 }
621 111 $gdata->{versions}{$version}{kinds}{$kind} = {
622 resource => $plural,
623 scope => $scope,
624 };
625 }
626  
627 2 ▶sub invalidate_discovery {
Subroutine invalidate_discovery: called CC=3 SCAR=11.0
Pod documented
628 2 my ($self) = @_;
629  
630  
631 2 $self->_clear_discovery;
632 2 $self->_clear_discovery_error;
633 2 ▶ $self->_clear_resource_map if $self->_has_resource_map;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_resource_map 1 1 2
634 # The inner IO::K8s captured the old map at build time; drop it too so it is
635 # rebuilt from the refreshed map on next use.
636 2 ▶ $self->_clear_k8s if $self->_has_k8s;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_k8s 1 1 2
637 2 return 1;
638 }
639  
640 # Fetch full OpenAPI spec from cluster (cached). Kept lazy on purpose: the
641 # only /openapi/v2 download in the client, paid for by schema_for/compare_schema
642 # and (once resolution needs it) AutoGen, never by construction.
643 has _openapi_spec => (
644 is => 'lazy',
645 predicate => '_has_openapi_spec',
646 6 ▶ builder => sub {
Subroutine _build__openapi_spec: called CC=3 SCAR=11.0
647 6 my $self = shift;
648 6 my $response = $self->_request('GET', '/openapi/v2');
649 6 ▶ croak "Could not fetch OpenAPI spec: " . $response->status if $response->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status >= 400 0 6 6
650 6 my $spec = $self->_json->decode($response->content);
651 # D12: the inner IO::K8s was built without a spec (so building it never
652 # forced this fetch). Now that the spec exists, drop the cached instance
653 # so its next build passes it through as openapi_spec for AutoGen -- the
654 # same rebuild-on-next-use pattern invalidate_discovery uses. The clear
655 # only marks it for rebuild; nothing here re-reads k8s, so the rebuild
656 # happens after Moo has stored this spec, not during the builder.
657 6 ▶ $self->_clear_k8s if $self->_has_k8s;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_k8s 1 5 6
658 6 return $spec;
659 },
660 39 );
661  
662 # Get schema definition for a specific type
663 # $kind can be: 'Pod', 'IO::K8s::Api::Core::V1::Pod', or OpenAPI name like 'io.k8s.api.core.v1.Pod'
664 8 ▶sub schema_for {
Subroutine schema_for: called CC=4 SCAR=13.9
Pod documented
665 8 my ($self, $kind) = @_;
666  
667  
668 8 my $spec = $self->_openapi_spec;
669 8 ▶ my $defs = $spec->{definitions} // {};
Condition50%1/2
$spec->{"definitions"} // {}
l!l
80
MC/DC0%0/1
$spec->{"definitions"} // {}
$spec->{"definitions"}
Truth table50%1/2
A
A= $spec->{"definitions"}
Aresult
11
00
670  
671 # If it's already an OpenAPI definition name
672 8 ▶ if (exists $defs->{$kind}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $defs->{$kind}) 6 2 8
673 6 return $defs->{$kind};
674 }
675  
676 # Convert class name to OpenAPI definition name
677 2 my $class = $self->expand_class($kind);
678 # IO::K8s::Api::Core::V1::Pod -> io.k8s.api.core.v1.Pod
679 2 my $def_name = $class;
680 2 $def_name =~ s/^IO::K8s:://;
681 2 $def_name =~ s/::/./g;
682 2 $def_name = 'io.k8s.' . $def_name;
683 # Lowercase all path components except the final type name
684 2 my @parts = split /\./, $def_name;
685 2 $parts[$_] = lc($parts[$_]) for 0 .. $#parts - 1;
686 2 $def_name = join '.', @parts;
687  
688 2 return $defs->{$def_name};
689 }
690  
691 # Compare local class against cluster schema
692 # Returns comparison result from IO::K8s::Role::Resource->compare_to_schema
693 0 ▶sub compare_schema {
Subroutine compare_schema: not called CC=2 SCAR=17.9
Pod documented
694 0 my ($self, $kind) = @_;
695  
696  
697 0 my $class = $self->expand_class($kind);
698 0 require_module($class);
699  
700 0 my $schema = $self->schema_for($kind);
701 0 ▶ croak "Schema not found for $kind" unless $schema;
Branch: 1 branch
BranchTrueFalseTotal
unless $schema 0 0 0
702  
703 0 return $class->compare_to_schema($schema);
704 }
705  
706 # Internal wrapper with fallback for lazy loading
707 12 ▶sub _load_resource_map_from_cluster {
Subroutine _load_resource_map_from_cluster: called CC=2 SCAR=6.9
708 12 my ($self) = @_;
709 12 my $map = eval { $self->fetch_resource_map };
710 12 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 10 12
711 2 carp "Falling back to the built-in resource map: $@";
712 2 return IO::K8s->default_resource_map;
713 }
714 10 return $map;
715 }
716  
717 # V0 API compatibility - returns group wrapper objects
718 #
719 # Called as a plain function, not a method: each accessor below shares its name
720 # with the group module it wraps, so once this package is loaded Perl resolves
721 # a bareword like Kubernetes::REST::Core->new(...) against the sub instead of
722 # the class and calls it as Kubernetes::REST::Core()->new(...) - with no
723 # invocant. Returning the class name in that case puts the ->new(...) back on
724 # the class the caller was aiming at.
725 82 ▶sub _v0_group {
Subroutine _v0_group: called CC=2 SCAR=6.9
726 82 my ($group, $self) = @_;
727 82 my $class = "Kubernetes::REST::$group";
728 82 require_module($class);
729 82 ▶ return $class unless defined $self;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self 17 65 82
730 65 return $class->new(api => $self);
731 }
732  
733 15 ▶sub Core { _v0_group('Core', @_) }
Subroutine Core: called CC=1 SCAR=0.0
Pod undocumented
734 5 ▶sub Apps { _v0_group('Apps', @_) }
Subroutine Apps: called CC=1 SCAR=0.0
Pod undocumented
735 4 ▶sub Batch { _v0_group('Batch', @_) }
Subroutine Batch: called CC=1 SCAR=0.0
Pod undocumented
736 4 ▶sub Networking { _v0_group('Networking', @_) }
Subroutine Networking: called CC=1 SCAR=0.0
Pod undocumented
737 4 ▶sub Storage { _v0_group('Storage', @_) }
Subroutine Storage: called CC=1 SCAR=0.0
Pod undocumented
738 4 ▶sub Policy { _v0_group('Policy', @_) }
Subroutine Policy: called CC=1 SCAR=0.0
Pod undocumented
739 4 ▶sub Autoscaling { _v0_group('Autoscaling', @_) }
Subroutine Autoscaling: called CC=1 SCAR=0.0
Pod undocumented
740 4 ▶sub RbacAuthorization { _v0_group('RbacAuthorization', @_) }
Subroutine RbacAuthorization: called CC=1 SCAR=0.0
Pod undocumented
741 4 ▶sub Certificates { _v0_group('Certificates', @_) }
Subroutine Certificates: called CC=1 SCAR=0.0
Pod undocumented
742 4 ▶sub Coordination { _v0_group('Coordination', @_) }
Subroutine Coordination: called CC=1 SCAR=0.0
Pod undocumented
743 4 ▶sub Events { _v0_group('Events', @_) }
Subroutine Events: called CC=1 SCAR=0.0
Pod undocumented
744 4 ▶sub Scheduling { _v0_group('Scheduling', @_) }
Subroutine Scheduling: called CC=1 SCAR=0.0
Pod undocumented
745 4 ▶sub Authentication { _v0_group('Authentication', @_) }
Subroutine Authentication: called CC=1 SCAR=0.0
Pod documented
746 4 ▶sub Authorization { _v0_group('Authorization', @_) }
Subroutine Authorization: called CC=1 SCAR=0.0
Pod undocumented
747 4 ▶sub Admissionregistration { _v0_group('Admissionregistration', @_) }
Subroutine Admissionregistration: called CC=1 SCAR=0.0
Pod undocumented
748 5 ▶sub Apiextensions { _v0_group('Apiextensions', @_) }
Subroutine Apiextensions: called CC=1 SCAR=0.0
Pod undocumented
749 5 ▶sub Apiregistration { _v0_group('Apiregistration', @_) }
Subroutine Apiregistration: called CC=1 SCAR=0.0
Pod undocumented
750  
751 # Build URL path from class metadata
752 199 ▶sub _build_path {
Subroutine _build_path: called CC=23 SCAR=33.4
753 199 my ($self, $class, %args) = @_;
754  
755 199 require_module($class);
756  
757 # An Unstructured resolution (D16 rung 4) carries no api_version()/
758 # resource_plural()/Namespaced role -- its Kind is data on the instance,
759 # not a class identity -- so the path metadata comes from the discovery
760 # catalog instead of the class. The caller (a CRUD method, or a seam
761 # consumer) passes the Kind (and an object's own apiVersion) via
762 # _unstructured_hint; api_version/resource/namespaced overrides are honoured
763 # directly when given, which keeps build_path usable by async wrappers.
764 198 my ($api_version, $resource, $is_namespaced);
765 198 my ($kind_hint, $av_hint) = (delete $args{kind}, delete $args{api_version});
766 198 my $override_resource = delete $args{resource};
767 198 my $override_namespaced = delete $args{namespaced};
768 198 ▶ if ($class eq 'IO::K8s::Unstructured') {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq 'IO::K8s::Unstructured') { } 18 180 198
769 18 ▶ if (defined $override_resource && defined $override_namespaced
Branch: 1 branch
BranchTrueFalseTotal
if (defined $override_resource and defined $override_namespaced and defined $av_hint) { } 6 12 18
Condition83%5/6
defined $override_resource and defined $override_namespaced and defined $av_hint
!ll&&!rl&&r
1206
defined $override_resource and defined $override_namespaced
!ll&&!rl&&r
1116
MC/DC66%2/3
defined $override_resource and defined $override_namespaced and defined $av_hint
defined $override_resource defined $override_namespaced defined $av_hint
Truth table75%3/4
A and B and C
A= defined $override_resourceB= defined $override_namespacedC= defined $av_hint
ABCresult
0XX0
10X0
1100
1111
770 && defined $av_hint) {
771 6 ($api_version, $resource, $is_namespaced) =
772 ($av_hint, $override_resource, $override_namespaced);
773 } else {
774 12 ▶ defined $kind_hint
Branch: 1 branch
BranchTrueFalseTotal
defined $kind_hint or croak("IO::K8s::Unstructured needs a Kind to build a path (pass kind => 'Kind')") 10 2 12
775 or croak "IO::K8s::Unstructured needs a Kind to build a path"
776 . " (pass kind => 'Kind')";
777 10 my $meta = $self->_discovery_path_meta($kind_hint, $av_hint);
778 10 ▶ unless ($meta) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($meta) 4 6 10
779 # A failed fetch and a catalog without the Kind both come back
780 # undef (fail-closed, see _discovery_path_meta); only the
781 # recorded reason tells them apart, and a catalog that was
782 # never read must not be reported as one lacking an entry.
783 4 my $reason = $self->_discovery_error;
784 4 ▶ croak defined $reason
Branch: 1 branch
BranchTrueFalseTotal
defined $reason ? : 2 2 4
785 ? "discovery failed, so Kind '$kind_hint' is unconfirmed"
786 . " - cannot build a path for IO::K8s::Unstructured:"
787 . " $reason"
788 : "no discovery entry for Kind '$kind_hint' - cannot"
789 . " build a path for IO::K8s::Unstructured";
790 }
791 ($api_version, $resource, $is_namespaced) =
792 6 @{$meta}{qw(api_version resource namespaced)};
793 }
794 } else {
795 # Get metadata from class
796 180 ▶ $api_version = $class->can('api_version') ? $class->api_version : undef;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('api_version') ? : 180 0 180
797 180 ▶ croak "Cannot determine api_version for $class - override api_version() in your CRD class"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version 0 180 180
798 unless defined $api_version;
799 180 ▶ my $kind = $class->can('kind') ? $class->kind : (split('::', $class))[-1];
Branch: 1 branch
BranchTrueFalseTotal
$class->can('kind') ? : 180 0 180
800 180 $is_namespaced = $class->does('IO::K8s::Role::Namespaced');
801  
802 # Use explicit resource_plural if available, otherwise auto-pluralize
803 180 ▶ if ($class->can('resource_plural') && $class->resource_plural) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class->can('resource_plural') and $class->resource_plural) { } 180 0 180
Condition33%1/3
$class->can("resource_plural") and $class->resource_plural
!ll&&!rl&&r
00180
MC/DC0%0/2
$class->can("resource_plural") and $class->resource_plural
$class->can("resource_plural") $class->resource_plural
Truth table33%1/3
A and B
A= $class->can("resource_plural")B= $class->resource_plural
ABresult
0X0
100
111
804 180 $resource = $class->resource_plural;
805 } else {
806 0 $resource = lc($kind);
807 0 ▶ if ($resource =~ /(?:ss|sh|ch|x|z)$/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($resource =~ /(?:ss|sh|ch|x|z)$/) { } 0 0 0
elsif ($resource =~ /[^aeiou]y$/) { } 0 0 0
elsif (not $resource =~ /s$/) { } 0 0 0
808 0 $resource .= 'es'; # class -> classes, ingress -> ingresses
809 } elsif ($resource =~ /[^aeiou]y$/) {
810 0 $resource =~ s/y$/ies/; # policy -> policies
811 } elsif ($resource !~ /s$/) {
812 0 $resource .= 's'; # pod -> pods
813 }
814 }
815 }
816  
817 # Build path based on API group
818 192 my $path;
819 192 ▶ if ($api_version =~ m{/}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($api_version =~ m[/]) { } 88 104 192
820 # Has group: apps/v1 -> /apis/apps/v1/...
821 88 $path = "/apis/$api_version";
822 } else {
823 # Core: v1 -> /api/v1/...
824 104 $path = "/api/$api_version";
825 }
826  
827 192 ▶ if ($is_namespaced && $args{namespace}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_namespaced and $args{"namespace"}) 131 61 192
Condition100%3/3
$is_namespaced and $args{"namespace"}
!ll&&!rl&&r
556131
MC/DC100%2/2
$is_namespaced and $args{"namespace"}
$is_namespaced $args{"namespace"}
Truth table100%3/3
A and B
A= $is_namespacedB= $args{"namespace"}
ABresult
0X0
100
111
828 131 $path .= "/namespaces/$args{namespace}";
829 }
830  
831 192 $path .= "/$resource";
832  
833 192 ▶ if ($args{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"name"}) 111 81 192
834 111 $path .= "/$args{name}";
835 }
836  
837 # Subresource suffix: /status, /log, /exec, /attach, /portforward.
838 # Every subresource addresses one named resource - without a name the
839 # suffix would silently land on the collection endpoint instead.
840 192 ▶ if (defined $args{subresource} && length $args{subresource}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"subresource"} and length $args{"subresource"}) 44 148 192
Condition66%2/3
defined $args{"subresource"} and length $args{"subresource"}
!ll&&!rl&&r
148044
MC/DC50%1/2
defined $args{"subresource"} and length $args{"subresource"}
defined $args{"subresource"} length $args{"subresource"}
Truth table66%2/3
A and B
A= defined $args{"subresource"}B= length $args{"subresource"}
ABresult
0X0
100
111
841 croak "subresource '$args{subresource}' requires a name for $class"
842 44 ▶ unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 43 44
843 43 $path .= "/$args{subresource}";
844 }
845  
846 191 return $path;
847 }
848  
849 # ============================================================================
850 # REQUEST / RESPONSE PIPELINE
851 #
852 # The API methods (list, get, create, etc.) are built on a 3-step pipeline:
853 #
854 # 1. _prepare_request - builds an HTTPRequest (method, url, headers, body)
855 # 2. io->call - executes the request (pluggable: HTTP::Tiny, async, mock)
856 # 3. _check_response / _inflate_object / _inflate_list - processes the response
857 #
858 # This separation allows different IO backends (sync, async, mock) to slot in
859 # at step 2 without touching request preparation or response processing.
860 # ============================================================================
861  
862 252 ▶sub _prepare_request {
Subroutine _prepare_request: called CC=15 SCAR=27.4
863 252 my ($self, $method, $path, %opts) = @_;
864  
865 252 my $url = $self->server->endpoint . $path;
866 252 ▶ my $content_type = $opts{content_type} // 'application/json';
Condition100%2/2
$opts{"content_type"} // "application/json"
l!l
19233
MC/DC100%1/1
$opts{"content_type"} // "application/json"
$opts{"content_type"}
Truth table100%2/2
A
A= $opts{"content_type"}
Aresult
11
00
867 252 my $body = $opts{body};
868 252 my $parameters = $opts{parameters};
869 252 ▶ my $extra_headers = $opts{headers} // {};
Condition100%2/2
$opts{"headers"} // {}
l!l
66186
MC/DC100%1/1
$opts{"headers"} // {}
$opts{"headers"}
Truth table100%2/2
A
A= $opts{"headers"}
Aresult
11
00
870  
871 # Append query parameters to URL
872 252 ▶ if ($parameters && %$parameters) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parameters and %$parameters) 26 226 252
Condition100%3/3
$parameters and %$parameters
!ll&&!rl&&r
224226
MC/DC100%2/2
$parameters and %$parameters
$parameters %$parameters
Truth table100%3/3
A and B
A= $parametersB= %$parameters
ABresult
0X0
100
111
873 26 my @pairs;
874 26 for my $key (sort keys %$parameters) {
875 69 my $val = $parameters->{$key};
876 69 ▶ next unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 69 69
877 69 ▶ if (ref($val) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'ARRAY') { } 6 63 69
878 6 push @pairs, map { "$key=$_" } grep { defined } @$val;
879 } else {
880 63 push @pairs, "$key=$val";
881 }
882 }
883 26 ▶ if (@pairs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pairs) 26 0 26
884 26 ▶ $url .= ($url =~ /\?/ ? '&' : '?') . join('&', @pairs);
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /\?/ ? : 0 26 26
885 }
886 }
887  
888 252 my %headers = (
889 'Content-Type' => $content_type,
890 'Accept' => 'application/json',
891 );
892  
893 # Only add Authorization header when a token is available
894 # (client-certificate auth doesn't need a Bearer token)
895 252 my $token = $self->credentials->token;
896 252 ▶ if (defined $token && length $token) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $token and length $token) 251 1 252
Condition66%2/3
defined $token and length $token
!ll&&!rl&&r
01251
MC/DC50%1/2
defined $token and length $token
defined $token length $token
Truth table66%2/3
A and B
A= defined $tokenB= length $token
ABresult
0X0
100
111
897 251 $headers{'Authorization'} = 'Bearer ' . $token;
898 }
899 252 ▶ if ($extra_headers && ref($extra_headers) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($extra_headers and ref $extra_headers eq "HASH") 252 0 252
Condition33%1/3
$extra_headers and ref $extra_headers eq "HASH"
!ll&&!rl&&r
00252
MC/DC0%0/2
$extra_headers and ref $extra_headers eq "HASH"
$extra_headers ref $extra_headers eq "HASH"
Truth table33%1/3
A and B
A= $extra_headersB= ref $extra_headers eq "HASH"
ABresult
0X0
100
111
900 252 @headers{keys %$extra_headers} = values %$extra_headers;
901 }
902  
903 252 ▶ return Kubernetes::REST::HTTPRequest->new(
Branch: 1 branch
BranchTrueFalseTotal
$body ? : 56 196 252
904 method => $method,
905 url => $url,
906 headers => \%headers,
907 ($body ? (content => $self->_json->encode($body)) : ()),
908 );
909 }
910  
911 154 ▶sub _check_response {
Subroutine _check_response: called CC=3 SCAR=11.0
912 154 my ($self, $response, $context) = @_;
913 154 ▶ if ($response->status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->status >= 400) 9 145 154
914 # Response bodies are bytes; the error message is read by humans, so
915 # decode it (leniently - a truncated or non-UTF-8 body must not turn a
916 # useful API error into an encoding croak).
917 9 ▶ my $body = Encode::decode('UTF-8', $response->content // '', Encode::FB_DEFAULT);
Condition50%1/2
$response->content // ""
l!l
90
MC/DC0%0/1
$response->content // ""
$response->content
Truth table50%1/2
A
A= $response->content
Aresult
11
00
918 9 croak "Kubernetes API error ($context): "
919 . $response->status . " " . $body;
920 }
921 145 return $response;
922 }
923  
924 74 ▶sub _inflate_object {
Subroutine _inflate_object: called CC=1 SCAR=0.0
925 74 my ($self, $class, $response) = @_;
926 74 return $self->k8s->json_to_object($class, $response->content);
927 }
928  
929 39 ▶sub _inflate_list {
Subroutine _inflate_list: called CC=9 SCAR=22.5
930 39 my ($self, $class, $response) = @_;
931 39 my $struct = $self->_json->decode($response->content);
932 39 ▶ my $items = $struct->{items} // [];
Condition50%1/2
$struct->{"items"} // []
l!l
390
MC/DC0%0/1
$struct->{"items"} // []
$struct->{"items"}
Truth table50%1/2
A
A= $struct->{"items"}
Aresult
11
00
933 39 my (@objects, @dropped);
934 39 for my $i (0 .. $#$items) {
935 26 my $item = $items->[$i];
936 26 my $obj = eval { $self->k8s->struct_to_object($class, $item) };
937 26 ▶ if (defined $obj) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $obj) 22 4 26
938 22 push @objects, $obj;
939 22 next;
940 }
941 # An item the object model rejects must not disappear without a
942 # trace: the caller would read a cluster with N unreadable Pods as a
943 # cluster with N fewer Pods (karr #16). Say which items were dropped
944 # and why - typically the installed IO::K8s not knowing a field the
945 # cluster version serves.
946 4 ▶ my $err = $@ || 'inflated to undef';
Condition50%1/2
$@ || 'inflated to undef'
l!l
40
MC/DC0%0/1
$@ || 'inflated to undef'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
947 4 $err =~ s/\s+\z//;
948 my $name = ref $item eq 'HASH' && ref $item->{metadata} eq 'HASH'
949 ? $item->{metadata}{name}
950 4 ▶ : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $item eq 'HASH' && ref $item->{'metadata'} eq 'HASH' ? : 4 0 4
Condition33%1/3
ref $item eq "HASH" and ref $item->{"metadata"} eq "HASH"
!ll&&!rl&&r
004
MC/DC0%0/2
ref $item eq "HASH" and ref $item->{"metadata"} eq "HASH"
ref $item eq "HASH" ref $item->{"metadata"} eq "HASH"
Truth table33%1/3
A and B
A= ref $item eq "HASH"B= ref $item->{"metadata"} eq "HASH"
ABresult
0X0
100
111
951 4 ▶ push @dropped,
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 4 0 4
952 "item $i" . (defined $name ? " (name '$name')" : '') . ": $err";
953 }
954 39 ▶ if (@dropped) {
Branch: 1 branch
BranchTrueFalseTotal
if (@dropped) 3 36 39
955 3 carp sprintf
956 "inflate_list: dropped %d of %d %s items - the returned list is"
957 . " INCOMPLETE (often IO::K8s version drift against the cluster):\n %s",
958 scalar @dropped, scalar @$items, $class, join("\n ", @dropped);
959 }
960 38 return IO::K8s::List->new(items => \@objects, item_class => $class);
961 }
962  
963 11 ▶sub _process_watch_chunk {
Subroutine _process_watch_chunk: called CC=13 SCAR=26.3
964 11 my ($self, $class, $buffer_ref, $chunk) = @_;
965 11 $$buffer_ref .= $chunk;
966  
967 11 my @events;
968 11 ▶ while ($$buffer_ref =~ s/^([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^([^\n]*)\n//) 11 11 22
969 11 my $line = $1;
970 11 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 0 11 11
971  
972 11 my $data = eval { $self->_json->decode($line) };
973 11 ▶ next unless $data;
Branch: 1 branch
BranchTrueFalseTotal
unless $data 0 11 11
974  
975 11 ▶ my $type = $data->{type} // '';
Condition50%1/2
$data->{"type"} // ""
l!l
110
MC/DC0%0/1
$data->{"type"} // ""
$data->{"type"}
Truth table50%1/2
A
A= $data->{"type"}
Aresult
11
00
976 11 ▶ my $raw_object = $data->{object} // {};
Condition50%1/2
$data->{"object"} // {}
l!l
110
MC/DC0%0/1
$data->{"object"} // {}
$data->{"object"}
Truth table50%1/2
A
A= $data->{"object"}
Aresult
11
00
977  
978 # Track resourceVersion for resumability
979 11 my $rv;
980 11 ▶ if ($raw_object->{metadata} && $raw_object->{metadata}{resourceVersion}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_object->{"metadata"} and $raw_object->{"metadata"}{"resourceVersion"}) 10 1 11
Condition66%2/3
$raw_object->{"metadata"} and $raw_object->{"metadata"}{"resourceVersion"}
!ll&&!rl&&r
1010
MC/DC50%1/2
$raw_object->{"metadata"} and $raw_object->{"metadata"}{"resourceVersion"}
$raw_object->{"metadata"} $raw_object->{"metadata"}{"resourceVersion"}
Truth table66%2/3
A and B
A= $raw_object->{"metadata"}B= $raw_object->{"metadata"}{"resourceVersion"}
ABresult
0X0
100
111
981 10 $rv = $raw_object->{metadata}{resourceVersion};
982 }
983  
984 # Inflate the object (ERROR events stay as hashrefs)
985 11 my $object;
986 11 ▶ if ($type eq 'ERROR') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'ERROR') { } 1 10 11
987 1 $object = $raw_object;
988 } else {
989 10 ▶ $object = eval { $self->k8s->struct_to_object($class, $raw_object) }
Condition33%1/3
eval { // $raw_object
l!l&&r!l&&!r
1000
MC/DC0%0/2
eval { do { $self->k8s->struct_to_object($class, $raw_object) } } // $raw_object
eval { do { $self->k8s->struct_to_object($class, $raw_object) } } $raw_object
Truth table33%1/3
A // B
A= eval { do { $self->k8s->struct_to_object($class, $raw_object) } }B= $raw_object
ABresult
1X1
011
000
990 // $raw_object;
991 }
992  
993 push @events, {
994 event => Kubernetes::REST::WatchEvent->new(
995 type => $type,
996 object => $object,
997 raw => $raw_object,
998 ),
999 resourceVersion => $rv,
1000 is_error => ($type eq 'ERROR' ? 1 : 0),
1001 11 ▶ error_code => ($type eq 'ERROR' ? ($raw_object->{code} // 0) : 0),
Branch: 2 branches
BranchTrueFalseTotal
$type eq 'ERROR' ? : 1 10 11
$type eq 'ERROR' ? : 1 10 11
Condition50%1/2
$raw_object->{"code"} // 0
l!l
10
MC/DC0%0/1
$raw_object->{"code"} // 0
$raw_object->{"code"}
Truth table50%1/2
A
A= $raw_object->{"code"}
Aresult
11
00
1002 };
1003 }
1004  
1005 11 return @events;
1006 }
1007  
1008 11 ▶sub _process_log_chunk {
Subroutine _process_log_chunk: called CC=2 SCAR=6.9
1009 11 my ($self, $buffer_ref, $chunk) = @_;
1010 11 $$buffer_ref .= $chunk;
1011  
1012 11 my @events;
1013 11 ▶ while ($$buffer_ref =~ s/^([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^([^\n]*)\n//) 14 11 25
1014 14 my $line = $1;
1015 14 push @events, Kubernetes::REST::LogEvent->new(line => $line);
1016 }
1017  
1018 11 return @events;
1019 }
1020  
1021 # ============================================================================
1022 # PUBLIC BUILDING BLOCKS FOR ASYNC WRAPPERS
1023 #
1024 # These methods expose the internal request/response pipeline as a stable API
1025 # for async wrappers (e.g. Net::Async::Kubernetes) that need to build requests,
1026 # process responses, and handle streaming without going through the sync
1027 # convenience methods (list, get, watch, log, port_forward, exec, attach, etc.).
1028 # ============================================================================
1029  
1030 19 ▶sub build_path {
Subroutine build_path: called CC=1 SCAR=0.0
Pod documented
1031 19 my ($self, @args) = @_;
1032  
1033  
1034 19 return $self->_build_path(@args);
1035 }
1036  
1037 18 ▶sub prepare_request {
Subroutine prepare_request: called CC=1 SCAR=0.0
Pod documented
1038 18 my ($self, @args) = @_;
1039  
1040  
1041 18 return $self->_prepare_request(@args);
1042 }
1043  
1044 2 ▶sub check_response {
Subroutine check_response: called CC=1 SCAR=0.0
Pod documented
1045 2 my ($self, @args) = @_;
1046  
1047  
1048 2 return $self->_check_response(@args);
1049 }
1050  
1051 1 ▶sub inflate_object {
Subroutine inflate_object: called CC=1 SCAR=0.0
Pod documented
1052 1 my ($self, @args) = @_;
1053  
1054  
1055 1 return $self->_inflate_object(@args);
1056 }
1057  
1058 1 ▶sub inflate_list {
Subroutine inflate_list: called CC=1 SCAR=0.0
Pod documented
1059 1 my ($self, @args) = @_;
1060  
1061  
1062 1 return $self->_inflate_list(@args);
1063 }
1064  
1065 1 ▶sub process_watch_chunk {
Subroutine process_watch_chunk: called CC=1 SCAR=0.0
Pod documented
1066 1 my ($self, @args) = @_;
1067  
1068  
1069 1 return $self->_process_watch_chunk(@args);
1070 }
1071  
1072 6 ▶sub process_log_chunk {
Subroutine process_log_chunk: called CC=1 SCAR=0.0
Pod documented
1073 6 my ($self, @args) = @_;
1074  
1075  
1076 6 return $self->_process_log_chunk(@args);
1077 }
1078  
1079 # Convenience: prepare + call in one step (used by sync CRUD methods)
1080 213 ▶sub _request {
Subroutine _request: called CC=1 SCAR=0.0
1081 213 my ($self, $method, $path, $body, %opts) = @_;
1082 213 my $req = $self->_prepare_request($method, $path,
1083 body => $body,
1084 %opts,
1085 );
1086 213 return $self->io->call($req);
1087 }
1088  
1089 38 ▶sub list {
Subroutine list: called CC=4 SCAR=14.1
Pod documented
1090 38 my ($self, $short_class, %args) = @_;
1091  
1092  
1093 # Extract query parameters before building path
1094 38 my $label_selector = delete $args{labelSelector};
1095 38 my $field_selector = delete $args{fieldSelector};
1096  
1097 38 my $class = $self->expand_class($short_class);
1098 38 my $path = $self->_build_path($class, %args,
1099 $self->_unstructured_hint($class, $short_class));
1100  
1101 38 my %params;
1102 38 ▶ $params{labelSelector} = $label_selector if defined $label_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $label_selector 0 38 38
1103 38 ▶ $params{fieldSelector} = $field_selector if defined $field_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $field_selector 0 38 38
1104  
1105 38 ▶ my $response = %params
Branch: 1 branch
BranchTrueFalseTotal
%params ? : 0 38 38
1106 ? $self->_request('GET', $path, undef, parameters => \%params)
1107 : $self->_request('GET', $path);
1108 38 $self->_check_response($response, "list $short_class");
1109  
1110 38 return $self->_inflate_list($class, $response);
1111 }
1112  
1113 23 ▶sub get {
Subroutine get: called CC=6 SCAR=17.9
Pod documented
1114 23 my ($self, $short_class, @rest) = @_;
1115  
1116  
1117 # Support: get('Kind', 'name'), get('Kind', 'name', namespace => 'ns'),
1118 # get('Kind', name => 'name'), get('Kind', name => 'name', namespace => 'ns')
1119 23 my %args;
1120 23 ▶ if (@rest == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest == 1) { } 3 20 23
elsif (@rest >= 2 and not $rest[0] =~ /^(name|namespace)$/) { } 15 5 20
elsif (@rest % 2 == 0) { } 5 0 5
1121 3 $args{name} = $rest[0];
1122 ▶ } elsif (@rest >= 2 && $rest[0] !~ /^(name|namespace)$/) {
Condition100%3/3
@rest >= 2 and not $rest[0] =~ /^(name|namespace)$/
!ll&&!rl&&r
2315
MC/DC100%2/2
@rest >= 2 and not $rest[0] =~ /^(name|namespace)$/
@rest >= 2 not $rest[0] =~ /^(name|namespace)$/
Truth table100%3/3
A and not(B)
A= @rest >= 2B= not $rest[0] =~ /^(name|namespace)$/
ABresult
0X0
100
111
1123 # First arg is name, rest are key=value pairs
1124 15 $args{name} = shift @rest;
1125 15 %args = (%args, @rest);
1126 } elsif (@rest % 2 == 0) {
1127 5 %args = @rest;
1128 } else {
1129 0 croak "Invalid arguments to get()";
1130 }
1131  
1132 23 my $class = $self->expand_class($short_class);
1133 23 ▶ croak "name required for get" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 21 23
1134  
1135 21 my $path = $self->_build_path($class, %args,
1136 $self->_unstructured_hint($class, $short_class));
1137 20 my $response = $self->_request('GET', $path);
1138 20 $self->_check_response($response, "get $short_class");
1139  
1140 18 return $self->_inflate_object($class, $response);
1141 }
1142  
1143 28 ▶sub create {
Subroutine create: called CC=3 SCAR=11.4
Pod documented
1144 28 my ($self, $object) = @_;
1145  
1146  
1147 28 my $class = ref($object);
1148 28 ▶ my $namespace = $object->can('metadata') && $object->metadata
Branch: 1 branch
BranchTrueFalseTotal
$object->can('metadata') && $object->metadata ? : 28 0 28
Condition33%1/3
$object->can("metadata") and $object->metadata
!ll&&!rl&&r
0028
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
1149 ? $object->metadata->namespace
1150 : undef;
1151  
1152 28 my $path = $self->_build_path($class, namespace => $namespace,
1153 $self->_unstructured_hint($class, $object));
1154 28 my $response = $self->_request('POST', $path, $object->TO_JSON);
1155 28 $self->_check_response($response, "create " . ref($object));
1156  
1157 26 return $self->_inflate_object($class, $response);
1158 }
1159  
1160 5 ▶sub update {
Subroutine update: called CC=3 SCAR=11.1
Pod documented
1161 5 my ($self, $object) = @_;
1162  
1163  
1164 5 my $class = ref($object);
1165 5 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 5 0 5
1166 5 ▶ 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") 5 0 5
1167 5 my $namespace = $metadata->namespace;
1168  
1169 5 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1170 $self->_unstructured_hint($class, $object));
1171 5 my $response = $self->_request('PUT', $path, $object->TO_JSON);
1172 5 $self->_check_response($response, "update " . ref($object));
1173  
1174 5 return $self->_inflate_object($class, $response);
1175 }
1176  
1177 39 my %PATCH_TYPES = (
1178 strategic => 'application/strategic-merge-patch+json',
1179 merge => 'application/merge-patch+json',
1180 json => 'application/json-patch+json',
1181 );
1182  
1183 # Shared argument unpacking for patch() and patch_status(): accepts either a
1184 # blessed object or a class plus name, in both the shorthand
1185 # (patch('Pod', 'name', ...)) and the fully keyed (patch('Pod', name => ...))
1186 # call form. $label only appears in croak messages, $default_type is the patch
1187 # strategy used when the caller does not pass one.
1188 29 ▶sub _unpack_patch_args {
Subroutine _unpack_patch_args: called CC=15 SCAR=28.5
1189 29 my ($self, $label, $default_type, $class_or_object, @rest) = @_;
1190  
1191 29 my ($class, $name, $namespace, $patch, $patch_type);
1192  
1193 29 ▶ if (ref($class_or_object) && blessed($class_or_object)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_object and builtin::blessed($class_or_object)) { } 2 27 29
Condition66%2/3
ref $class_or_object and builtin::blessed($class_or_object)
!ll&&!rl&&r
2702
MC/DC50%1/2
ref $class_or_object and builtin::blessed($class_or_object)
ref $class_or_object builtin::blessed($class_or_object)
Truth table66%2/3
A and B
A= ref $class_or_objectB= builtin::blessed($class_or_object)
ABresult
0X0
100
111
1194 # Object passed: patch($object, patch => {...})
1195 2 my $object = $class_or_object;
1196 2 $class = ref($object);
1197 2 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 2 0 2
1198 2 ▶ $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
$name = $metadata->name or croak("object must have metadata.name") 2 0 2
1199 2 $namespace = $metadata->namespace;
1200 2 my %args = @rest;
1201 2 ▶ $patch = $args{patch} // croak "$label requires 'patch' parameter";
Condition33%1/3
$args{"patch"} // croak("$label requires 'patch' parameter")
l!l&&r!l&&!r
200
MC/DC0%0/2
$args{"patch"} // croak("$label requires 'patch' parameter")
$args{"patch"} croak("$label requires 'patch' parameter")
Truth table33%1/3
A // B
A= $args{"patch"}B= croak("$label requires 'patch' parameter")
ABresult
1X1
011
000
1202 2 ▶ $patch_type = $args{type} // $default_type;
Condition33%1/3
$args{"type"} // $default_type
l!l&&r!l&&!r
020
MC/DC0%0/2
$args{"type"} // $default_type
$args{"type"} $default_type
Truth table33%1/3
A // B
A= $args{"type"}B= $default_type
ABresult
1X1
011
000
1203 } else {
1204 # Class + name: patch('Pod', 'name', namespace => 'ns', patch => {...})
1205 27 my %args;
1206 27 ▶ if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|patch|type)$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|patch|type)$/) { } 18 9 27
elsif (@rest % 2 == 0) { } 7 2 9
Condition50%3/6
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|patch|type)$/
!ll&&!rl&&r
0918
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
0027
MC/DC33%1/3
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|patch|type)$/
@rest >= 1 not ref $rest[0] not $rest[0] =~ /^(name|namespace|patch|type)$/
Truth table50%2/4
A and not(B) and not(C)
A= @rest >= 1B= not ref $rest[0]C= not $rest[0] =~ /^(name|namespace|patch|type)$/
ABCresult
0XX0
10X0
1100
1111
1207 18 $args{name} = shift @rest;
1208 18 %args = (%args, @rest);
1209 } elsif (@rest % 2 == 0) {
1210 7 %args = @rest;
1211 } else {
1212 2 croak "Invalid arguments to $label()";
1213 }
1214  
1215 25 $class = $self->expand_class($class_or_object);
1216 25 ▶ $name = $args{name} or croak "name required for $label";
Branch: 1 branch
BranchTrueFalseTotal
$name = $args{"name"} or croak("name required for $label") 22 3 25
1217 22 $namespace = $args{namespace};
1218 22 ▶ $patch = $args{patch} // croak "$label requires 'patch' parameter";
Condition66%2/3
$args{"patch"} // croak("$label requires 'patch' parameter")
l!l&&r!l&&!r
1930
MC/DC0%0/2
$args{"patch"} // croak("$label requires 'patch' parameter")
$args{"patch"} croak("$label requires 'patch' parameter")
Truth table33%1/3
A // B
A= $args{"patch"}B= croak("$label requires 'patch' parameter")
ABresult
1X1
011
000
1219 19 ▶ $patch_type = $args{type} // $default_type;
Condition66%2/3
$args{"type"} // $default_type
l!l&&r!l&&!r
1360
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
1220 }
1221  
1222 21 ▶ my $content_type = $PATCH_TYPES{$patch_type}
Condition66%2/3
$PATCH_TYPES{$patch_type} // croak("Unknown patch type '${patch_type}' (use: strategic, merge, json)")
l!l&&r!l&&!r
1920
MC/DC0%0/2
$PATCH_TYPES{$patch_type} // croak("Unknown patch type '${patch_type}' (use: strategic, merge, json)")
$PATCH_TYPES{$patch_type} croak("Unknown patch type '${patch_type}' (use: strategic, merge, json)")
Truth table33%1/3
A // B
A= $PATCH_TYPES{$patch_type}B= croak("Unknown patch type '${patch_type}' (use: strategic, merge, json)")
ABresult
1X1
011
000
1223 // croak "Unknown patch type '$patch_type' (use: strategic, merge, json)";
1224  
1225 19 return ($class, $name, $namespace, $patch, $content_type);
1226 }
1227  
1228 15 ▶sub patch {
Subroutine patch: called CC=1 SCAR=0.0
Pod documented
1229 15 my ($self, $class_or_object, @rest) = @_;
1230  
1231  
1232 15 my ($class, $name, $namespace, $patch, $content_type)
1233 = $self->_unpack_patch_args('patch', 'strategic', $class_or_object, @rest);
1234  
1235 9 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1236 $self->_unstructured_hint($class, $class_or_object));
1237 9 my $response = $self->_request('PATCH', $path, $patch,
1238 content_type => $content_type);
1239 9 $self->_check_response($response, "patch $class");
1240  
1241 9 return $self->_inflate_object($class, $response);
1242 }
1243  
1244 14 ▶sub patch_status {
Subroutine patch_status: called CC=1 SCAR=0.0
Pod documented
1245 14 my ($self, $class_or_object, @rest) = @_;
1246  
1247  
1248 14 my ($class, $name, $namespace, $patch, $content_type)
1249 = $self->_unpack_patch_args('patch_status', 'merge', $class_or_object, @rest);
1250  
1251 10 my $path = $self->_build_path($class,
1252 name => $name,
1253 namespace => $namespace,
1254 subresource => 'status',
1255 $self->_unstructured_hint($class, $class_or_object),
1256 );
1257 10 my $response = $self->_request('PATCH', $path, $patch,
1258 content_type => $content_type);
1259 10 $self->_check_response($response, "patch_status $class");
1260  
1261 9 return $self->_inflate_object($class, $response);
1262 }
1263  
1264 4 ▶sub update_status {
Subroutine update_status: called CC=3 SCAR=11.0
Pod documented
1265 4 my ($self, $object) = @_;
1266  
1267  
1268 4 my $class = ref($object);
1269 4 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 4 0 4
1270 4 ▶ 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") 3 1 4
1271 3 my $namespace = $metadata->namespace;
1272  
1273 3 my $path = $self->_build_path($class,
1274 name => $name,
1275 namespace => $namespace,
1276 subresource => 'status',
1277 $self->_unstructured_hint($class, $object),
1278 );
1279 3 my $response = $self->_request('PUT', $path, $object->TO_JSON);
1280 3 $self->_check_response($response, "update_status " . ref($object));
1281  
1282 2 return $self->_inflate_object($class, $response);
1283 }
1284  
1285 13 ▶sub delete {
Subroutine delete: called CC=9 SCAR=24.3
Pod documented
1286 13 my ($self, $class_or_object, @rest) = @_;
1287  
1288  
1289 13 my ($class, $name, $namespace);
1290  
1291 13 ▶ if (ref($class_or_object)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_object) { } 0 13 13
1292 # Object passed
1293 0 my $object = $class_or_object;
1294 0 $class = ref($object);
1295 0 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 0 0 0
1296 0 ▶ $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
$name = $metadata->name or croak("object must have metadata.name") 0 0 0
1297 0 $namespace = $metadata->namespace;
1298 } else {
1299 # Support: delete('Kind', 'name'), delete('Kind', 'name', namespace => 'ns'),
1300 # delete('Kind', name => 'name'), delete('Kind', name => 'name', namespace => 'ns')
1301 13 my %args;
1302 13 ▶ if (@rest == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest == 1) { } 2 11 13
elsif (@rest >= 2 and not $rest[0] =~ /^(name|namespace)$/) { } 7 4 11
elsif (@rest % 2 == 0) { } 4 0 4
1303 2 $args{name} = $rest[0];
1304 ▶ } elsif (@rest >= 2 && $rest[0] !~ /^(name|namespace)$/) {
Condition100%3/3
@rest >= 2 and not $rest[0] =~ /^(name|namespace)$/
!ll&&!rl&&r
227
MC/DC100%2/2
@rest >= 2 and not $rest[0] =~ /^(name|namespace)$/
@rest >= 2 not $rest[0] =~ /^(name|namespace)$/
Truth table100%3/3
A and not(B)
A= @rest >= 2B= not $rest[0] =~ /^(name|namespace)$/
ABresult
0X0
100
111
1305 # First arg is name, rest are key=value pairs
1306 7 $args{name} = shift @rest;
1307 7 %args = (%args, @rest);
1308 } elsif (@rest % 2 == 0) {
1309 4 %args = @rest;
1310 } else {
1311 0 croak "Invalid arguments to delete()";
1312 }
1313  
1314 13 $class = $self->expand_class($class_or_object);
1315 13 ▶ $name = $args{name} or croak "name required for delete";
Branch: 1 branch
BranchTrueFalseTotal
$name = $args{"name"} or croak("name required for delete") 11 2 13
1316 11 $namespace = $args{namespace};
1317 }
1318  
1319 11 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1320 $self->_unstructured_hint($class, $class_or_object));
1321 11 my $response = $self->_request('DELETE', $path);
1322 11 $self->_check_response($response, "delete $class");
1323  
1324 11 return 1;
1325 }
1326  
1327 8 ▶sub ensure {
Subroutine ensure: called CC=21 SCAR=43.8
Pod documented
1328 8 my ($self, $object) = @_;
1329  
1330  
1331 8 ▶ if (ref($object) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $object eq "HASH") 1 7 8
1332 1 ▶ my $kind = $object->{kind} or croak "ensure: hashref must have 'kind'";
Branch: 1 branch
BranchTrueFalseTotal
my $kind = $object->{"kind"} or croak("ensure: hashref must have 'kind'") 1 0 1
1333 1 my $class = $self->expand_class($kind);
1334 1 $object = $self->k8s->struct_to_object($class, $object);
1335 }
1336  
1337 8 my $class = ref($object);
1338 8 ▶ croak "ensure requires an IO::K8s object or hashref" unless blessed($object);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($object) 0 8 8
1339 8 (my $kind = $class) =~ s/.*:://;
1340 8 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 8 0 8
1341 8 ▶ 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") 8 0 8
1342 8 my $namespace = $metadata->namespace;
1343  
1344 8 my @unstructured_hint = $self->_unstructured_hint($class, $object);
1345 8 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1346 @unstructured_hint);
1347  
1348 8 my $existing = eval {
1349 8 my $response = $self->_request('GET', $path);
1350 8 ▶ return undef if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 5 3 8
1351 3 $self->_check_response($response, "ensure get $kind/$name");
1352 3 $self->_inflate_object($class, $response);
1353 };
1354 8 my $get_err = $@;
1355 8 ▶ die $get_err if $get_err && $get_err !~ /\b404\b/;
Branch: 1 branch
BranchTrueFalseTotal
if $get_err and not $get_err =~ /\b404\b/ 0 8 8
Condition33%1/3
$get_err and not $get_err =~ /\b404\b/
!ll&&!rl&&r
800
MC/DC0%0/2
$get_err and not $get_err =~ /\b404\b/
$get_err not $get_err =~ /\b404\b/
Truth table33%1/3
A and not(B)
A= $get_errB= not $get_err =~ /\b404\b/
ABresult
0X0
100
111
1356  
1357 8 ▶ if ($existing) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing) 3 5 8
1358 3 ▶ return $existing if $kind eq 'PersistentVolumeClaim';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "PersistentVolumeClaim" 1 2 3
1359 2 ▶ if ($kind eq 'Job') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "Job") 0 2 2
1360 0 my $status = $existing->status;
1361 0 ▶ my $succeeded = $status && $status->succeeded;
Condition0%0/3
$status && $status->succeeded
!ll&&!rl&&r
000
MC/DC0%0/2
$status && $status->succeeded
$status $status->succeeded
Truth table0%0/3
A && B
A= $statusB= $status->succeeded
ABresult
0X0
100
111
1362 0 ▶ my $active = $status && $status->active;
Condition0%0/3
$status && $status->active
!ll&&!rl&&r
000
MC/DC0%0/2
$status && $status->active
$status $status->active
Truth table0%0/3
A && B
A= $statusB= $status->active
ABresult
0X0
100
111
1363 0 ▶ return $existing if $succeeded || $active;
Branch: 1 branch
BranchTrueFalseTotal
if $succeeded or $active 0 0 0
Condition0%0/3
$succeeded or $active
l!l&&r!l&&!r
000
MC/DC0%0/2
$succeeded or $active
$succeeded $active
Truth table0%0/3
A or B
A= $succeededB= $active
ABresult
1X1
011
000
1364 0 eval { $self->delete($existing) };
1365 0 return $self->create($object);
1366 }
1367 2 $object->metadata->resourceVersion($existing->metadata->resourceVersion);
1368 2 my $updated = eval { $self->update($object) };
1369 2 ▶ return $updated if $updated;
Branch: 1 branch
BranchTrueFalseTotal
if $updated 2 0 2
1370 0 ▶ if ($@ =~ /\b409\b/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /\b409\b/) 0 0 0
1371 0 $existing = $self->_request('GET', $path);
1372 0 $self->_check_response($existing, "ensure refetch $kind/$name");
1373 0 $existing = $self->_inflate_object($class, $existing);
1374 0 $object->metadata->resourceVersion($existing->metadata->resourceVersion);
1375 0 return $self->update($object);
1376 }
1377 0 die $@;
1378 }
1379  
1380 5 my $created = eval { $self->create($object) };
1381 5 ▶ return $created if $created;
Branch: 1 branch
BranchTrueFalseTotal
if $created 5 0 5
1382  
1383 0 ▶ if ($@ =~ /\b409\b/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /\b409\b/) 0 0 0
1384 0 my $response = $self->_request('GET', $path);
1385 0 $self->_check_response($response, "ensure post-409 get $kind/$name");
1386 0 $existing = $self->_inflate_object($class, $response);
1387 0 ▶ return $existing if $kind eq 'PersistentVolumeClaim';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "PersistentVolumeClaim" 0 0 0
1388 0 $object->metadata->resourceVersion($existing->metadata->resourceVersion);
1389 0 return $self->update($object);
1390 }
1391 0 die $@;
1392 }
1393  
1394 1 ▶sub ensure_all {
Subroutine ensure_all: called CC=1 SCAR=0.0
Pod documented
1395 1 my ($self, @objects) = @_;
1396  
1397  
1398 1 return map { $self->ensure($_) } @objects;
1399 }
1400  
1401 0 ▶sub ensure_only {
Subroutine ensure_only: not called CC=18 SCAR=58.3
Pod documented
1402 0 my ($self, %args) = @_;
1403  
1404  
1405 0 ▶ my $label = $args{label} or croak "ensure_only requires 'label'";
Branch: 1 branch
BranchTrueFalseTotal
my $label = $args{"label"} or croak("ensure_only requires 'label'") 0 0 0
1406 0 ▶ my @objects = @{$args{objects} || []};
Condition0%0/2
$args{'objects'} || []
l!l
00
MC/DC0%0/1
$args{'objects'} || []
$args{'objects'}
Truth table0%0/2
A
A= $args{'objects'}
Aresult
11
00
1407 0 ▶ my @kinds = @{$args{kinds} || []};
Condition0%0/2
$args{'kinds'} || []
l!l
00
MC/DC0%0/1
$args{'kinds'} || []
$args{'kinds'}
Truth table0%0/2
A
A= $args{'kinds'}
Aresult
11
00
1408 0 ▶ my @namespaces = @{$args{namespaces} || [undef]};
Condition0%0/2
$args{'namespaces'} || [undef]
l!l
00
MC/DC0%0/1
$args{'namespaces'} || [undef]
$args{'namespaces'}
Truth table0%0/2
A
A= $args{'namespaces'}
Aresult
11
00
1409  
1410 0 for my $obj (@objects) {
1411 0 ▶ next unless ref($obj) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $obj eq "HASH" 0 0 0
1412 0 ▶ my $kind = $obj->{kind} or croak "ensure_only: hashref must have 'kind'";
Branch: 1 branch
BranchTrueFalseTotal
my $kind = $obj->{"kind"} or croak("ensure_only: hashref must have 'kind'") 0 0 0
1413 0 my $class = $self->expand_class($kind);
1414 0 $obj = $self->k8s->struct_to_object($class, $obj);
1415 }
1416  
1417 0 my @results = $self->ensure_all(@objects);
1418  
1419 0 my %expected;
1420 0 for my $obj (@objects) {
1421 0 (my $kind = ref $obj) =~ s/.*:://;
1422 0 ▶ my $key = join("\0", $kind, $obj->metadata->namespace // '');
Condition0%0/2
$obj->metadata->namespace // ""
l!l
00
MC/DC0%0/1
$obj->metadata->namespace // ""
$obj->metadata->namespace
Truth table0%0/2
A
A= $obj->metadata->namespace
Aresult
11
00
1423 0 $expected{$key}{$obj->metadata->name} = 1;
1424 }
1425  
1426 0 for my $kind (@kinds) {
1427 0 for my $ns (@namespaces) {
1428 0 my %list_args = (labelSelector => $label);
1429 0 ▶ $list_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 0 0 0
1430 0 my $list = eval { $self->list($kind, %list_args) };
1431 0 ▶ next unless $list;
Branch: 1 branch
BranchTrueFalseTotal
unless $list 0 0 0
1432 0 for my $item (@{$list->items}) {
1433 0 ▶ my $item_ns = $item->metadata->namespace // '';
Condition0%0/2
$item->metadata->namespace // ""
l!l
00
MC/DC0%0/1
$item->metadata->namespace // ""
$item->metadata->namespace
Truth table0%0/2
A
A= $item->metadata->namespace
Aresult
11
00
1434 0 my $key = join("\0", $kind, $item_ns);
1435 0 ▶ next if $expected{$key} && $expected{$key}{$item->metadata->name};
Branch: 1 branch
BranchTrueFalseTotal
if $expected{$key} and $expected{$key}{$item->metadata->name} 0 0 0
Condition0%0/3
$expected{$key} and $expected{$key}{$item->metadata->name}
!ll&&!rl&&r
000
MC/DC0%0/2
$expected{$key} and $expected{$key}{$item->metadata->name}
$expected{$key} $expected{$key}{$item->metadata->name}
Truth table0%0/3
A and B
A= $expected{$key}B= $expected{$key}{$item->metadata->name}
ABresult
0X0
100
111
1436 0 eval { $self->delete($item) };
1437 }
1438 }
1439 }
1440  
1441 0 return @results;
1442 }
1443  
1444 5 ▶sub ensure_crd {
Subroutine ensure_crd: called CC=13 SCAR=25.7
Pod documented
1445 5 my $self = shift;
1446  
1447  
1448 5 my (@classes, %opts);
1449 5 ▶ if (@_ && ref $_[0] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[0] eq 'ARRAY') { } 2 3 5
Condition100%3/3
@_ and ref $_[0] eq "ARRAY"
!ll&&!rl&&r
122
MC/DC100%2/2
@_ and ref $_[0] eq "ARRAY"
@_ ref $_[0] eq "ARRAY"
Truth table100%3/3
A and B
A= @_B= ref $_[0] eq "ARRAY"
ABresult
0X0
100
111
1450 2 @classes = @{ shift() };
1451 2 %opts = @_;
1452 } else {
1453 3 @classes = @_;
1454 }
1455 5 ▶ croak "ensure_crd requires at least one CRD class" unless @classes;
Branch: 1 branch
BranchTrueFalseTotal
unless @classes 1 4 5
1456  
1457 4 my $storage = $opts{storage};
1458  
1459 # Group the classes by the CRD they name (metadata.name = "$plural.$group"),
1460 # preserving first-seen order so the applied order is predictable.
1461 4 my (@order, %group);
1462 4 for my $class (@classes) {
1463 6 my $single = $class->to_crd;
1464 6 my $crd_name = $single->metadata->name;
1465 6 ▶ push @order, $crd_name unless exists $group{$crd_name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $group{$crd_name} 4 2 6
1466 6 push @{ $group{$crd_name} }, { class => $class, single => $single };
1467 }
1468  
1469 4 my @crds;
1470 4 for my $crd_name (@order) {
1471 4 my $members = $group{$crd_name};
1472 4 ▶ if (@$members == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$members == 1) 2 2 4
1473 2 push @crds, $members->[0]{single};
1474 2 next;
1475 }
1476 # Two or more classes are versions of the SAME CRD: assemble one
1477 # multi-version CRD rather than apply competing single-version ones.
1478 2 my @version_classes = map { $_->{class} } @$members;
1479 2 my @versions = map { $_->{single}->spec->versions->[0]->name } @$members;
1480 my $storage_version =
1481 !defined $storage ? undef
1482 2 ▶ : ref $storage eq 'HASH' ? $storage->{$crd_name}
Branch: 2 branches
BranchTrueFalseTotal
!defined($storage) ? : 1 1 2
ref $storage eq 'HASH' ? : 0 1 1
1483 : $storage;
1484 2 ▶ croak "ensure_crd: '$crd_name' is defined by multiple classes ("
Branch: 1 branch
BranchTrueFalseTotal
unless defined $storage_version and length $storage_version 1 1 2
Condition66%2/3
defined $storage_version and length $storage_version
!ll&&!rl&&r
101
MC/DC50%1/2
defined $storage_version and length $storage_version
defined $storage_version length $storage_version
Truth table66%2/3
A and B
A= defined $storage_versionB= length $storage_version
ABresult
0X0
100
111
1485 . join(', ', @version_classes) . ") naming versions ("
1486 . join(', ', @versions) . "); pass storage => '<version>' (or "
1487 . "storage => { '$crd_name' => '<version>' }) to name the storage version"
1488 unless defined $storage_version && length $storage_version;
1489 1 push @crds,
1490 IO::K8s::CRD->new(classes => \@version_classes, storage => $storage_version);
1491 }
1492  
1493 # Apply every CRD first, then wait for each to establish (so establishment
1494 # happens in parallel), then invalidate discovery exactly once.
1495 3 $self->ensure($_) for @crds;
1496 3 my @established = map { $self->_wait_crd_established($_, %opts) } @crds;
1497 1 $self->invalidate_discovery;
1498 1 return @established;
1499 }
1500  
1501 # Poll GET on a CustomResourceDefinition by name until its Established condition
1502 # is True, or croak on timeout. A 404 during polling means "not registered yet"
1503 # and is treated as not-established, not an error.
1504 3 ▶sub _wait_crd_established {
Subroutine _wait_crd_established: called CC=9 SCAR=22.6
1505 3 my ($self, $crd, %opts) = @_;
1506  
1507 3 my $class = ref $crd;
1508 3 my $name = $crd->metadata->name;
1509 3 my $path = $self->_build_path($class, name => $name);
1510 3 ▶ my $timeout = defined $opts{timeout} ? $opts{timeout} : 30;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'timeout'} ? : 2 1 3
1511 3 ▶ my $interval = defined $opts{poll_interval} ? $opts{poll_interval} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'poll_interval'} ? : 0 3 3
1512 3 my $deadline = Time::HiRes::time() + $timeout;
1513  
1514 3 while (1) {
1515 3 my $current = eval {
1516 3 my $response = $self->_request('GET', $path);
1517 3 ▶ return undef if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 2 1 3
1518 1 $self->_check_response($response, "ensure_crd wait $name");
1519 1 $self->_inflate_object($class, $response);
1520 };
1521 3 my $err = $@;
1522 3 ▶ die $err if $err && $err !~ /\b404\b/;
Branch: 1 branch
BranchTrueFalseTotal
if $err and not $err =~ /\b404\b/ 0 3 3
Condition33%1/3
$err and not $err =~ /\b404\b/
!ll&&!rl&&r
300
MC/DC0%0/2
$err and not $err =~ /\b404\b/
$err not $err =~ /\b404\b/
Truth table33%1/3
A and not(B)
A= $errB= not $err =~ /\b404\b/
ABresult
0X0
100
111
1523  
1524 3 ▶ return $current if $current && $self->_crd_established($current);
Branch: 1 branch
BranchTrueFalseTotal
if $current and $self->_crd_established($current) 1 2 3
Condition66%2/3
$current and $self->_crd_established($current)
!ll&&!rl&&r
201
MC/DC50%1/2
$current and $self->_crd_established($current)
$current $self->_crd_established($current)
Truth table66%2/3
A and B
A= $currentB= $self->_crd_established($current)
ABresult
0X0
100
111
1525 2 ▶ last if Time::HiRes::time() >= $deadline;
Branch: 1 branch
BranchTrueFalseTotal
if &Time::HiRes::time() >= $deadline 2 0 2
1526 0 Time::HiRes::sleep($interval);
1527 }
1528  
1529 2 croak "ensure_crd: CustomResourceDefinition '$name' did not reach the "
1530 . "Established condition within ${timeout}s";
1531 }
1532  
1533 # True when a CustomResourceDefinition object carries an Established=True
1534 # condition in status.conditions.
1535 2 ▶sub _crd_established {
Subroutine _crd_established: called CC=8 SCAR=25.5
1536 2 my ($self, $crd) = @_;
1537 2 ▶ my $status = $crd->status or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $status = $crd->status or return 0 2 0 2
1538 2 ▶ my $conditions = $status->conditions or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $conditions = $status->conditions or return 0 2 0 2
1539 2 for my $cond (@$conditions) {
1540 2 ▶ return 1
Branch: 1 branch
BranchTrueFalseTotal
if ($cond->type // "") eq "Established" and ($cond->status // "") eq "True" 2 0 2
Condition42%3/7
($cond->type // "") eq "Established" and ($cond->status // "") eq "True"
!ll&&!rl&&r
002
$cond->type // ""
l!l
20
$cond->status // ""
l!l
20
MC/DC0%0/2
($cond->type // "") eq "Established" and ($cond->status // "") eq "True"
$cond->type $cond->status
Truth table33%1/3
A and B
A= $cond->typeB= $cond->status
ABresult
0X0
100
111
1541 if ($cond->type // '') eq 'Established'
1542 && ($cond->status // '') eq 'True';
1543 }
1544 0 return 0;
1545 }
1546  
1547 7 ▶sub watch {
Subroutine watch: called CC=7 SCAR=19.5
Pod documented
1548 7 my ($self, $short_class, %args) = @_;
1549  
1550  
1551 my $on_event = delete $args{on_event}
1552 7 ▶ or croak "watch requires 'on_event' callback";
Branch: 1 branch
BranchTrueFalseTotal
my $on_event = delete $args{"on_event"} or croak("watch requires 'on_event' callback") 6 1 7
1553 6 ▶ my $timeout = delete $args{timeout} // 300;
Condition100%2/2
delete $args{"timeout"} // 300
l!l
15
MC/DC100%1/1
delete $args{"timeout"} // 300
delete $args{"timeout"}
Truth table100%2/2
A
A= delete $args{"timeout"}
Aresult
11
00
1554 6 my $resource_version = delete $args{resourceVersion};
1555 6 my $label_selector = delete $args{labelSelector};
1556 6 my $field_selector = delete $args{fieldSelector};
1557  
1558 6 my $class = $self->expand_class($short_class);
1559 6 my $path = $self->_build_path($class, %args,
1560 $self->_unstructured_hint($class, $short_class));
1561  
1562 6 my %params = (
1563 watch => 'true',
1564 timeoutSeconds => $timeout,
1565 );
1566 6 ▶ $params{resourceVersion} = $resource_version if defined $resource_version;
Branch: 1 branch
BranchTrueFalseTotal
if defined $resource_version 1 5 6
1567 6 ▶ $params{labelSelector} = $label_selector if defined $label_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $label_selector 1 5 6
1568 6 ▶ $params{fieldSelector} = $field_selector if defined $field_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $field_selector 1 5 6
1569  
1570 6 my $req = $self->_prepare_request('GET', $path, parameters => \%params);
1571  
1572 6 my $buffer = '';
1573 6 my $last_rv = $resource_version;
1574 6 my $got_410 = 0;
1575  
1576 10 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1577 10 my ($chunk) = @_;
1578 10 for my $result ($self->_process_watch_chunk($class, \$buffer, $chunk)) {
1579 10 ▶ $last_rv = $result->{resourceVersion} if $result->{resourceVersion};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"resourceVersion"} 9 1 10
1580 10 ▶ $got_410 = 1 if $result->{error_code} == 410;
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"error_code"} == 410 1 9 10
1581 10 $on_event->($result->{event});
1582 }
1583 6 };
1584  
1585 6 my $response = $self->io->call_streaming($req, $data_callback);
1586  
1587 6 $self->_check_response($response, "watch $short_class");
1588  
1589 6 ▶ croak "Watch expired (410 Gone): resourceVersion too old, re-list to get a fresh resourceVersion"
Branch: 1 branch
BranchTrueFalseTotal
if $got_410 1 5 6
1590 if $got_410;
1591  
1592 5 return $last_rv;
1593 }
1594  
1595 16 ▶sub log {
Subroutine log: called CC=17 SCAR=28.5
Pod documented
1596 16 my ($self, $short_class, @rest) = @_;
1597  
1598  
1599 # Support: log('Pod', 'name', ...) and log('Pod', name => 'name', ...)
1600 16 my %args;
1601 16 ▶ if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/) { } 14 2 16
elsif (@rest % 2 == 0) { } 2 0 2
Condition50%3/6
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/
!ll&&!rl&&r
0214
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
0016
MC/DC33%1/3
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/
@rest >= 1 not ref $rest[0] not $rest[0] =~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/
Truth table50%2/4
A and not(B) and not(C)
A= @rest >= 1B= not ref $rest[0]C= not $rest[0] =~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/
ABCresult
0XX0
10X0
1100
1111
1602 14 $args{name} = shift @rest;
1603 14 %args = (%args, @rest);
1604 } elsif (@rest % 2 == 0) {
1605 2 %args = @rest;
1606 } else {
1607 0 croak "Invalid arguments to log()";
1608 }
1609  
1610 16 ▶ croak "name required for log" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 15 16
1611  
1612 15 my $on_line = delete $args{on_line};
1613 15 my $container = delete $args{container};
1614 15 my $follow = delete $args{follow};
1615 15 my $tail_lines = delete $args{tailLines};
1616 15 my $since_seconds = delete $args{sinceSeconds};
1617 15 my $since_time = delete $args{sinceTime};
1618 15 my $timestamps = delete $args{timestamps};
1619 15 my $previous = delete $args{previous};
1620 15 my $limit_bytes = delete $args{limitBytes};
1621  
1622 15 my $class = $self->expand_class($short_class);
1623 15 my $path = $self->_build_path($class, %args, subresource => 'log',
1624 $self->_unstructured_hint($class, $short_class));
1625  
1626 15 my %params;
1627 15 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 1 14 15
1628 15 ▶ $params{follow} = 'true' if $follow;
Branch: 1 branch
BranchTrueFalseTotal
if $follow 1 14 15
1629 15 ▶ $params{tailLines} = $tail_lines if defined $tail_lines;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tail_lines 1 14 15
1630 15 ▶ $params{sinceSeconds} = $since_seconds if defined $since_seconds;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since_seconds 1 14 15
1631 15 ▶ $params{sinceTime} = $since_time if defined $since_time;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since_time 1 14 15
1632 15 ▶ $params{timestamps} = 'true' if $timestamps;
Branch: 1 branch
BranchTrueFalseTotal
if $timestamps 1 14 15
1633 15 ▶ $params{previous} = 'true' if $previous;
Branch: 1 branch
BranchTrueFalseTotal
if $previous 1 14 15
1634 15 ▶ $params{limitBytes} = $limit_bytes if defined $limit_bytes;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit_bytes 1 14 15
1635  
1636 15 ▶ if ($on_line) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_line) { } 4 11 15
1637 # Streaming mode
1638 4 my $req = $self->_prepare_request('GET', $path, parameters => \%params);
1639  
1640 4 my $buffer = '';
1641 5 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1642 5 my ($chunk) = @_;
1643 5 for my $event ($self->_process_log_chunk(\$buffer, $chunk)) {
1644 5 $on_line->($event);
1645 }
1646 4 };
1647  
1648 4 my $response = $self->io->call_streaming($req, $data_callback);
1649 4 $self->_check_response($response, "log $short_class");
1650  
1651 # Process any remaining data in buffer (last line without trailing newline)
1652 4 ▶ if (length $buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $buffer) 0 4 4
1653 0 $on_line->(Kubernetes::REST::LogEvent->new(line => $buffer));
1654 }
1655  
1656 4 return;
1657 } else {
1658 # One-shot mode
1659 11 ▶ my $response = $self->_request('GET', $path, undef,
Branch: 1 branch
BranchTrueFalseTotal
%params ? : 6 5 11
1660 %params ? (parameters => \%params) : (),
1661 );
1662 11 $self->_check_response($response, "log $short_class");
1663  
1664 11 return $response->content;
1665 }
1666 }
1667  
1668 7 ▶sub port_forward {
Subroutine port_forward: called CC=16 SCAR=28.1
Pod documented
1669 7 my ($self, $short_class, @rest) = @_;
1670  
1671  
1672 7 my %args;
1673 7 ▶ if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/) { } 6 1 7
elsif (@rest % 2 == 0) { } 1 0 1
Condition50%3/6
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/
!ll&&!rl&&r
016
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
007
MC/DC33%1/3
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/
@rest >= 1 not ref $rest[0] not $rest[0] =~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/
Truth table50%2/4
A and not(B) and not(C)
A= @rest >= 1B= not ref $rest[0]C= not $rest[0] =~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/
ABCresult
0XX0
10X0
1100
1111
1674 6 $args{name} = shift @rest;
1675 6 %args = (%args, @rest);
1676 } elsif (@rest % 2 == 0) {
1677 1 %args = @rest;
1678 } else {
1679 0 croak "Invalid arguments to port_forward()";
1680 }
1681  
1682 7 ▶ croak "name required for port_forward" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 6 7
1683  
1684 6 my $ports = delete $args{ports};
1685 6 ▶ croak "ports required for port_forward" unless defined $ports;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ports 1 5 6
1686 5 ▶ $ports = [$ports] unless ref($ports) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ports eq "ARRAY" 0 5 5
1687 5 ▶ croak "ports required for port_forward" unless @$ports;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ports 1 4 5
1688 4 for my $p (@$ports) {
1689 5 ▶ croak "invalid port '$p' for port_forward"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535 2 3 5
Condition77%7/9
defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535
!ll&&!rl&&r
113
defined $p and $p =~ /^\d+$/ and $p > 0
!ll&&!rl&&r
104
defined $p and $p =~ /^\d+$/
!ll&&!rl&&r
014
MC/DC50%2/4
defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535
defined $p $p =~ /^\d+$/ $p > 0 $p <= 65535
Truth table60%3/5
A and B and C and D
A= defined $pB= $p =~ /^\d+$/C= $p > 0D= $p <= 65535
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1690 unless defined($p) && $p =~ /^\d+$/ && $p > 0 && $p <= 65535;
1691 }
1692  
1693 2 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
11
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
1694 2 my $on_open = delete $args{on_open};
1695 2 my $on_frame = delete $args{on_frame};
1696 2 my $on_close = delete $args{on_close};
1697 2 my $on_error = delete $args{on_error};
1698  
1699 2 my $class = $self->expand_class($short_class);
1700 2 my $path = $self->_build_path($class, %args, subresource => 'portforward',
1701 $self->_unstructured_hint($class, $short_class));
1702  
1703 2 my $req = $self->_prepare_request('GET', $path,
1704 parameters => { ports => $ports },
1705 headers => {
1706 Accept => '*/*',
1707 Connection => 'Upgrade',
1708 Upgrade => 'websocket',
1709 'Sec-WebSocket-Protocol' => $subprotocol,
1710 },
1711 );
1712  
1713 2 my $io = $self->io;
1714 2 ▶ unless ($io->can('call_duplex')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io->can("call_duplex")) 1 1 2
1715 1 croak "IO backend does not support port_forward(): missing call_duplex()";
1716 }
1717  
1718 1 return $io->call_duplex($req,
1719 on_open => $on_open,
1720 on_frame => $on_frame,
1721 on_close => $on_close,
1722 on_error => $on_error,
1723 );
1724 }
1725  
1726 8 ▶sub exec {
Subroutine exec: called CC=26 SCAR=32.9
Pod documented
1727 8 my ($self, $short_class, @rest) = @_;
1728  
1729  
1730 8 my %args;
1731 8 ▶ if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/) { } 7 1 8
elsif (@rest % 2 == 0) { } 1 0 1
Condition50%3/6
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
!ll&&!rl&&r
017
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
008
MC/DC33%1/3
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
@rest >= 1 not ref $rest[0] not $rest[0] =~ /^(name|namespace|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
Truth table50%2/4
A and not(B) and not(C)
A= @rest >= 1B= not ref $rest[0]C= not $rest[0] =~ /^(name|namespace|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
ABCresult
0XX0
10X0
1100
1111
1732 7 $args{name} = shift @rest;
1733 7 %args = (%args, @rest);
1734 } elsif (@rest % 2 == 0) {
1735 1 %args = @rest;
1736 } else {
1737 0 croak "Invalid arguments to exec()";
1738 }
1739  
1740 8 ▶ croak "name required for exec" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 7 8
1741  
1742 7 my $command = delete $args{command};
1743 7 ▶ croak "command required for exec" unless defined $command;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $command 1 6 7
1744 6 ▶ $command = [$command] unless ref($command) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $command eq "ARRAY" 1 5 6
1745 6 ▶ croak "command required for exec" unless @$command;
Branch: 1 branch
BranchTrueFalseTotal
unless @$command 1 5 6
1746 5 for my $part (@$command) {
1747 7 ▶ croak "invalid command element for exec"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part and not ref $part and length $part 2 5 7
Condition83%5/6
defined $part and not ref $part and length $part
!ll&&!rl&&r
205
defined $part and not ref $part
!ll&&!rl&&r
115
MC/DC66%2/3
defined $part and not ref $part and length $part
defined $part not ref $part length $part
Truth table75%3/4
A and not(B) and C
A= defined $partB= not ref $partC= length $part
ABCresult
0XX0
10X0
1100
1111
1748 unless defined($part) && !ref($part) && length $part;
1749 }
1750  
1751 3 my $container = delete $args{container};
1752 3 ▶ my $stdin = delete($args{stdin}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'stdin'} ? : 1 2 3
1753 3 ▶ my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stdout'} ? : 1 2 3
delete $args{'stdout'} ? : 1 0 1
1754 3 ▶ my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stderr'} ? : 1 2 3
delete $args{'stderr'} ? : 0 1 1
1755 3 ▶ my $tty = delete($args{tty}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'tty'} ? : 1 2 3
1756  
1757 3 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
12
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
1758 3 my $on_open = delete $args{on_open};
1759 3 my $on_frame = delete $args{on_frame};
1760 3 my $on_close = delete $args{on_close};
1761 3 my $on_error = delete $args{on_error};
1762  
1763 3 my $class = $self->expand_class($short_class);
1764 3 my $path = $self->_build_path($class, %args, subresource => 'exec',
1765 $self->_unstructured_hint($class, $short_class));
1766  
1767 3 ▶ my %params = (
Branch: 4 branches
BranchTrueFalseTotal
$stdin ? : 1 2 3
$stdout ? : 3 0 3
$stderr ? : 2 1 3
$tty ? : 1 2 3
1768 command => $command,
1769 stdin => $stdin ? 'true' : 'false',
1770 stdout => $stdout ? 'true' : 'false',
1771 stderr => $stderr ? 'true' : 'false',
1772 tty => $tty ? 'true' : 'false',
1773 );
1774 3 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 1 2 3
1775  
1776 3 my $req = $self->_prepare_request('GET', $path,
1777 parameters => \%params,
1778 headers => {
1779 Accept => '*/*',
1780 Connection => 'Upgrade',
1781 Upgrade => 'websocket',
1782 'Sec-WebSocket-Protocol' => $subprotocol,
1783 },
1784 );
1785  
1786 3 my $io = $self->io;
1787 3 ▶ unless ($io->can('call_duplex')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io->can("call_duplex")) 1 2 3
1788 1 croak "IO backend does not support exec(): missing call_duplex()";
1789 }
1790  
1791 2 return $io->call_duplex($req,
1792 on_open => $on_open,
1793 on_frame => $on_frame,
1794 on_close => $on_close,
1795 on_error => $on_error,
1796 );
1797 }
1798  
1799 4 ▶sub attach {
Subroutine attach: called CC=19 SCAR=29.8
Pod documented
1800 4 my ($self, $short_class, @rest) = @_;
1801  
1802  
1803 4 my %args;
1804 4 ▶ if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/) {
Branch: 2 branches
BranchTrueFalseTotal
if (@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/) { } 3 1 4
elsif (@rest % 2 == 0) { } 1 0 1
Condition50%3/6
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
!ll&&!rl&&r
013
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
004
MC/DC33%1/3
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
@rest >= 1 not ref $rest[0] not $rest[0] =~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
Truth table50%2/4
A and not(B) and not(C)
A= @rest >= 1B= not ref $rest[0]C= not $rest[0] =~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
ABCresult
0XX0
10X0
1100
1111
1805 3 $args{name} = shift @rest;
1806 3 %args = (%args, @rest);
1807 } elsif (@rest % 2 == 0) {
1808 1 %args = @rest;
1809 } else {
1810 0 croak "Invalid arguments to attach()";
1811 }
1812  
1813 4 ▶ croak "name required for attach" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 3 4
1814  
1815 3 my $container = delete $args{container};
1816 3 ▶ my $stdin = delete($args{stdin}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'stdin'} ? : 1 2 3
1817 3 ▶ my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stdout'} ? : 1 2 3
delete $args{'stdout'} ? : 1 0 1
1818 3 ▶ my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stderr'} ? : 1 2 3
delete $args{'stderr'} ? : 0 1 1
1819 3 ▶ my $tty = delete($args{tty}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'tty'} ? : 1 2 3
1820  
1821 3 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
12
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
1822 3 my $on_open = delete $args{on_open};
1823 3 my $on_frame = delete $args{on_frame};
1824 3 my $on_close = delete $args{on_close};
1825 3 my $on_error = delete $args{on_error};
1826  
1827 3 my $class = $self->expand_class($short_class);
1828 3 my $path = $self->_build_path($class, %args, subresource => 'attach',
1829 $self->_unstructured_hint($class, $short_class));
1830  
1831 3 ▶ my %params = (
Branch: 4 branches
BranchTrueFalseTotal
$stdin ? : 1 2 3
$stdout ? : 3 0 3
$stderr ? : 2 1 3
$tty ? : 1 2 3
1832 stdin => $stdin ? 'true' : 'false',
1833 stdout => $stdout ? 'true' : 'false',
1834 stderr => $stderr ? 'true' : 'false',
1835 tty => $tty ? 'true' : 'false',
1836 );
1837 3 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 1 2 3
1838  
1839 3 my $req = $self->_prepare_request('GET', $path,
1840 parameters => \%params,
1841 headers => {
1842 Accept => '*/*',
1843 Connection => 'Upgrade',
1844 Upgrade => 'websocket',
1845 'Sec-WebSocket-Protocol' => $subprotocol,
1846 },
1847 );
1848  
1849 3 my $io = $self->io;
1850 3 ▶ unless ($io->can('call_duplex')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io->can("call_duplex")) 1 2 3
1851 1 croak "IO backend does not support attach(): missing call_duplex()";
1852 }
1853  
1854 2 return $io->call_duplex($req,
1855 on_open => $on_open,
1856 on_frame => $on_frame,
1857 on_close => $on_close,
1858 on_error => $on_error,
1859 );
1860 }
1861  
1862 39 1;
1863  
1864 __END__
1865  
1866 =pod
1867  
1868 =encoding UTF-8
1869  
1870 =head1 NAME
1871  
1872 Kubernetes::REST - A Perl REST Client for the Kubernetes API
1873  
1874 =head1 VERSION
1875  
1876 version 1.108
1877  
1878 =head1 SYNOPSIS
1879  
1880 use Kubernetes::REST;
1881  
1882 my $api = Kubernetes::REST->new(
1883 server => {
1884 endpoint => 'https://kubernetes.local:6443',
1885 ssl_verify_server => 1,
1886 ssl_ca_file => '/path/to/ca.crt',
1887 },
1888 credentials => { token => $token },
1889 );
1890  
1891 # List all namespaces
1892 my $namespaces = $api->list('Namespace');
1893 for my $ns (@{ $namespaces->items }) {
1894 say $ns->metadata->name;
1895 }
1896  
1897 # List pods in a namespace
1898 my $pods = $api->list('Pod', namespace => 'default');
1899  
1900 # Get a specific pod
1901 my $pod = $api->get('Pod', name => 'my-pod', namespace => 'default');
1902  
1903 # Create a namespace
1904 my $ns = $api->new_object(Namespace => {
1905 metadata => { name => 'my-namespace' },
1906 });
1907 my $created = $api->create($ns);
1908  
1909 # Create multiple namespaces
1910 for my $i (1..10) {
1911 $api->create($api->new_object(Namespace =>
1912 metadata => { name => "test-ns-$i" },
1913 ));
1914 }
1915  
1916 # Update a resource (full replacement)
1917 $pod->metadata->labels({ app => 'updated' });
1918 my $updated = $api->update($pod);
1919  
1920 # Patch a resource (partial update)
1921 my $patched = $api->patch('Pod', 'my-pod',
1922 namespace => 'default',
1923 patch => { metadata => { labels => { env => 'staging' } } },
1924 );
1925  
1926 # Delete a resource
1927 $api->delete($pod);
1928 # or by name:
1929 $api->delete('Pod', name => 'my-pod', namespace => 'default');
1930  
1931 # Idempotent create-or-update (from a typed object or a manifest hashref)
1932 $api->ensure($pod);
1933 $api->ensure({
1934 apiVersion => 'v1',
1935 kind => 'Secret',
1936 metadata => { name => 'my-secret', namespace => 'default' },
1937 stringData => { password => 'hunter2' },
1938 });
1939  
1940 # Batch apply
1941 $api->ensure_all(@objects);
1942  
1943 # Apply a labeled set and prune anything with that label not in the set
1944 $api->ensure_only(
1945 label => 'app.kubernetes.io/component=queen',
1946 objects => \@rbac_objects,
1947 kinds => [qw(Role RoleBinding ClusterRoleBinding)],
1948 namespaces => ['default', undef],
1949 );
1950  
1951 =head1 DESCRIPTION
1952  
1953 This module provides a simple REST client for the Kubernetes API using IO::K8s
1954 resource classes. The IO::K8s classes know their own metadata (API version,
1955 kind, whether they're namespaced), so URL building is automatic.
1956  
1957 =head2 server
1958  
1959 Required. L<Kubernetes::REST::Server> instance or hashref with server connection configuration.
1960  
1961 server => { endpoint => 'https://kubernetes.local:6443' }
1962  
1963 Automatically coerces hashrefs to L<Kubernetes::REST::Server> objects.
1964  
1965 =head2 credentials
1966  
1967 Required. Authentication credentials. Can be a hashref, L<Kubernetes::REST::AuthToken>, or any object with a C<token()> method.
1968  
1969 credentials => { token => $bearer_token }
1970  
1971 Automatically coerces hashrefs to L<Kubernetes::REST::AuthToken> objects.
1972  
1973 =head2 io
1974  
1975 HTTP backend for making requests. Must consume L<Kubernetes::REST::Role::IO>. Defaults to L<Kubernetes::REST::LWPIO> (L<LWP::UserAgent>).
1976  
1977 To use L<HTTP::Tiny> instead:
1978  
1979 use Kubernetes::REST::HTTPTinyIO;
1980 my $api = Kubernetes::REST->new(
1981 ...,
1982 io => Kubernetes::REST::HTTPTinyIO->new(...),
1983 );
1984  
1985 See L</PLUGGABLE IO ARCHITECTURE> for custom backends.
1986  
1987 =head2 with
1988  
1989 Arrayref of external L<IO::K8s> resource-map providers (CRD bundles), passed
1990 straight through to the inner L<IO::K8s/with>. Each entry is a provider class
1991 name (or object, or plain hashref) whose typed classes are merged into the
1992 resource map, so the cluster's CRD Kinds resolve to real classes:
1993  
1994 my $api = Kubernetes::REST->new(
1995 server => { endpoint => 'https://k8s.local:6443' },
1996 credentials => { token => $token },
1997 with => ['IO::K8s::GatewayAPI'],
1998 );
1999  
2000 my $gw = $api->new_object(Gateway => { metadata => { name => 'gw' } });
2001 # => IO::K8s::GatewayAPI::V1::Gateway
2002  
2003 Defaults to C<[]>. See L<IO::K8s/with> for the accepted provider forms.
2004  
2005 =head2 k8s
2006  
2007 L<IO::K8s> instance configured with the same resource map. Automatically created when needed.
2008  
2009 Provides delegated methods: C<new_object>, C<inflate>, C<json_to_object>, C<struct_to_object>, C<object_to_json>, C<object_to_struct>, C<load>, C<load_yaml>. (C<expand_class> is implemented here rather than delegated, so that pure name resolution does not force the cluster resource-map fetch - see L</expand_class>.)
2010  
2011 Delegation is a convenience only, every one of them behaves exactly as it does on L<IO::K8s>, including its argument contract:
2012  
2013 =over
2014  
2015 =item *
2016  
2017 C<new_object> takes a short or full class name and either a hashref or a flat hash of attributes:
2018  
2019 my $ns = $api->new_object(Namespace => { metadata => { name => 'foo' } });
2020 my $ns = $api->new_object(Namespace => metadata => { name => 'foo' });
2021  
2022 =item *
2023  
2024 C<inflate> takes a hashref, or JSON as B<UTF-8 bytes> - its decoder is C<utf8 =E<gt> 1>.
2025  
2026 =item *
2027  
2028 C<json_to_object> and C<struct_to_object> auto-detect the class from the decoded C<kind> field when called with a single argument (JSON or hashref, respectively) - a leading class name is only needed to override that detection:
2029  
2030 my $pod = $api->json_to_object($json_with_kind);
2031 my $pod = $api->json_to_object('Pod', $json_string);
2032  
2033 C<object_to_json> and C<object_to_struct> are their inverses, serialising a typed object back to JSON or to a plain hashref.
2034  
2035 =item *
2036  
2037 C<load_yaml> takes a file name or YAML as B<characters>. Handing it bytes turns every non-ASCII value into mojibake, so decode first (C<Encode::decode('UTF-8', $yaml)>). A newline-free argument is taken as a file name. C<--->-separated multi-document YAML is supported - the common case for Kubernetes manifests - so this always returns an arrayref, even for a single document:
2038  
2039 for my $obj (@{ $api->load_yaml('deployment.yaml') }) {
2040 $api->create($obj);
2041 }
2042  
2043 =item *
2044  
2045 C<load> reads a C<.pk8s> manifest, which is Perl code and is C<eval>ed in-process:
2046  
2047 my $objects = $api->load('myapp.pk8s');
2048  
2049 Only load C<.pk8s> files you trust; for data-only manifests use C<load_yaml>.
2050  
2051 =back
2052  
2053 Not delegated: C<add>, which registers extra classes in the L<IO::K8s> resource map. That map is mirrored by this client's own L</resource_map> attribute, and mutating one behind the other's back makes the two disagree - reach through C<< $api->k8s->add(...) >> if you really mean to.
2054  
2055 =head2 resource_map_from_cluster
2056  
2057 Boolean. If true, dynamically loads the resource map from the cluster's OpenAPI spec. Defaults to C<1>.
2058  
2059 Set to C<0> to use L<IO::K8s> built-in resource map instead (faster startup, but may not match your cluster version).
2060  
2061 =head2 cluster_version
2062  
2063 Read-only. The Kubernetes cluster version string (e.g., C<v1.31.0>). Fetched automatically from the C</version> endpoint when first accessed.
2064  
2065 =head2 resource_map
2066  
2067 Hashref mapping short resource names to L<IO::K8s> class paths. By default loads dynamically from the cluster (if C<resource_map_from_cluster> is true) or uses L<IO::K8s> built-in map.
2068  
2069 Override for custom resources:
2070  
2071 resource_map => {
2072 %{ IO::K8s->default_resource_map },
2073 MyResource => '+My::K8s::V1::MyResource',
2074 }
2075  
2076 The C<+> prefix tells L<IO::K8s> that this is a custom class (not in the IO::K8s:: namespace).
2077  
2078 =head2 expand_class
2079  
2080 my $class = $api->expand_class('Pod');
2081 # => IO::K8s::Api::Core::V1::Pod
2082  
2083 Resolve a short resource name (C<'Pod'>), a domain-qualified name
2084 (C<'cilium.io/v2/NetworkPolicy'>), a C<+>-prefixed or an already
2085 fully-qualified class name to its L<IO::K8s> class - the same contract as
2086 L<IO::K8s/expand_class>, against this client's L</resource_map>.
2087  
2088 Pure name resolution does not cost a cluster roundtrip: as long as the
2089 resource map has not been fetched yet (and none was passed to the
2090 constructor), a name the built-in L<IO::K8s> map resolves to a loadable
2091 class is answered from that map directly. Only a name the built-in map
2092 cannot answer falls through to the cluster-backed map, fetching it on first
2093 use exactly as before.
2094  
2095 =head2 fetch_resource_map
2096  
2097 my $map = $api->fetch_resource_map;
2098  
2099 Build the resource map from the cluster's aggregated discovery documents
2100 (C<GET /api> and C<GET /apis>). Returns a hashref mapping short resource names
2101 (e.g., C<Pod>) to full L<IO::K8s> class paths.
2102  
2103 Called automatically if C<resource_map_from_cluster> is enabled.
2104  
2105 Discovery is fetched and cached once per instance (see L</invalidate_discovery>);
2106 calling this again rebuilds the map from the cached catalog rather than
2107 re-querying the cluster. It does B<not> download C</openapi/v2> - that spec is
2108 fetched lazily only when L</schema_for> or L</compare_schema> need it.
2109  
2110 B<Version selection (D17).> When a group serves a Kind in more than one
2111 version, the bare short name (C<Pod>, C<ServiceCIDR>) resolves to the version
2112 the B<cluster marks preferred> for that group - not to a fixed "stable beats
2113 alpha/beta" preference. A Kind served only outside the preferred version still
2114 maps, to its first served version.
2115  
2116 Only Kinds whose L<IO::K8s> class this distribution actually ships are recorded
2117 in the map. A CRD group with no bundled class (C<cilium.io>,
2118 C<cert-manager.io>, ...) is deliberately omitted here, so that its Kinds
2119 resolve through the inner L<IO::K8s> - a provider merged via L</with>, then
2120 AutoGen from the fetched C</openapi/v2>, and finally a fail-closed error -
2121 rather than being mapped to a class name that does not exist.
2122  
2123 =head2 invalidate_discovery
2124  
2125 $api->invalidate_discovery;
2126  
2127 Discard the cached discovery catalog and the resource map built from it, so the
2128 next resolution re-queries the cluster. Use it after a CustomResourceDefinition
2129 is installed or changed, to make the new Kind visible to this client instance.
2130  
2131 =head2 schema_for
2132  
2133 my $schema = $api->schema_for('Pod');
2134  
2135 Get the OpenAPI schema definition for a resource type from the cluster. Accepts short names (C<Pod>), full class names (C<IO::K8s::Api::Core::V1::Pod>), or OpenAPI definition names (C<io.k8s.api.core.v1.Pod>).
2136  
2137 Returns a hashref with the OpenAPI v2 schema definition.
2138  
2139 =head2 compare_schema
2140  
2141 my $result = $api->compare_schema('Pod');
2142  
2143 Compare the local L<IO::K8s> class definition against the cluster's OpenAPI schema. Useful for detecting version skew between your L<IO::K8s> installation and the cluster.
2144  
2145 Returns the comparison result from C<< $class->compare_to_schema >>, the method L<IO::K8s::Role::Resource> provides on every resource class.
2146  
2147 =head2 build_path
2148  
2149 my $class = $api->expand_class('Pod');
2150 my $path = $api->build_path($class, name => 'my-pod', namespace => 'default');
2151 # => /api/v1/namespaces/default/pods/my-pod
2152  
2153 my $status = $api->build_path($class,
2154 name => 'my-pod',
2155 namespace => 'default',
2156 subresource => 'status',
2157 );
2158 # => /api/v1/namespaces/default/pods/my-pod/status
2159  
2160 Build the REST API URL path for a resource class. Takes a fully-qualified class name (from C<expand_class>) and optional C<name>/C<namespace> arguments.
2161  
2162 The optional C<subresource> argument appends a subresource segment (C<status>, C<log>, C<exec>, C<attach>, C<portforward>) to the resource path. A subresource always addresses one named resource, so C<subresource> without C<name> croaks rather than returning a path pointing at the collection endpoint.
2163  
2164 C<build_path> also accepts C<kind>, C<api_version>, C<resource> and C<namespaced> arguments, but they matter only for L<IO::K8s::Unstructured>. For any other class they are ignored: C<api_version>, pluralisation and namespaced-ness always come from the class itself. Unstructured has no such class identity - its Kind is data on the instance - so the path metadata has to come from somewhere else:
2165  
2166 my $path = $api->build_path('IO::K8s::Unstructured',
2167 kind => 'MyCRD',
2168 api_version => 'example.com/v1',
2169 resource => 'mycrds',
2170 namespaced => 1,
2171 name => 'my-instance',
2172 namespace => 'default',
2173 );
2174 # => /apis/example.com/v1/namespaces/default/mycrds/my-instance
2175  
2176 Passing C<api_version>, C<resource> and C<namespaced> together, as above, resolves the path directly with no discovery lookup - the case for a caller (such as an async wrapper) that already knows the resource's metadata. Otherwise C<kind> is required (C<build_path> croaks without it), and resource/namespaced/apiVersion are looked up in the client's cached discovery catalog instead, preferring the cluster's preferred version unless C<api_version> pins a specific group/version; C<build_path> croaks if discovery has no entry for the Kind, and equally if the catalog could not be fetched at all (cluster unreachable, expired token) - in that case the message names that failure rather than claiming a missing entry, and the fallback stays fail-closed either way.
2177  
2178 This is a public API for async wrappers like L<Net::Async::Kubernetes> that need to construct request paths independently.
2179  
2180 =head2 prepare_request
2181  
2182 my $req = $api->prepare_request('GET', $path,
2183 parameters => \%params,
2184 body => \%body,
2185 );
2186  
2187 Build a L<Kubernetes::REST::HTTPRequest> with method, full URL, authorization
2188 headers, and optional query parameters or JSON body.
2189  
2190 Query parameter values may be scalars or arrayrefs (arrayrefs are emitted as
2191 repeated C<key=value> pairs). Extra request headers can be provided via
2192 C<headers =E<gt> \%headers>.
2193  
2194 This is a public API for async wrappers that execute HTTP requests through their own event loop.
2195  
2196 =head2 check_response
2197  
2198 $api->check_response($response, "get Pod");
2199  
2200 Validate an HTTP response. Croaks with a descriptive error if the status code is >= 400. Returns the response on success.
2201  
2202 =head2 inflate_object
2203  
2204 my $pod = $api->inflate_object($class, $response);
2205  
2206 Decode the JSON response body and inflate it into a typed L<IO::K8s> object.
2207  
2208 =head2 inflate_list
2209  
2210 my $list = $api->inflate_list($class, $response);
2211  
2212 Decode the JSON response body and inflate the C<items> array into an L<IO::K8s::List> of typed objects.
2213  
2214 An item the object model rejects - typically because the installed L<IO::K8s>
2215 does not know a field the cluster version serves - is dropped from the list,
2216 and a warning names every dropped item (index, C<metadata.name>, the
2217 inflation error) so an incomplete list is never silent. Promote it to a fatal
2218 error with C<< local $SIG{__WARN__} = sub { die @_ } >> if partial results
2219 are unacceptable to you.
2220  
2221 =head2 process_watch_chunk
2222  
2223 my @results = $api->process_watch_chunk($class, \$buffer, $chunk);
2224  
2225 Process a chunk of NDJSON watch data. Appends the chunk to the buffer, extracts complete lines, and returns a list of hashrefs with C<event> (L<Kubernetes::REST::WatchEvent>), C<resourceVersion>, C<is_error>, and C<error_code>.
2226  
2227 This is a public API for async wrappers that handle streaming watch responses through their own event loop.
2228  
2229 =head2 process_log_chunk
2230  
2231 my @events = $api->process_log_chunk(\$buffer, $chunk);
2232  
2233 Process a chunk of plain-text log data. Appends the chunk to the buffer, extracts complete lines, and returns a list of L<Kubernetes::REST::LogEvent> objects.
2234  
2235 This is a public API for async wrappers that handle streaming log responses through their own event loop.
2236  
2237 =head2 list
2238  
2239 my $list = $api->list('Pod', namespace => 'default');
2240 my $list = $api->list('Namespace', labelSelector => 'app=web');
2241  
2242 List resources. Returns an L<IO::K8s::List> object.
2243  
2244 Accepts short class names (C<Pod>) or full class paths. For namespaced resources, pass C<namespace> parameter. Omit C<namespace> to list cluster-scoped resources.
2245  
2246 Supports C<labelSelector> and C<fieldSelector> query parameters for server-side filtering.
2247  
2248 =head2 get
2249  
2250 my $pod = $api->get('Pod', name => 'my-pod', namespace => 'default');
2251 # or shorthand:
2252 my $pod = $api->get('Pod', 'my-pod', namespace => 'default');
2253  
2254 Get a single resource by name. Returns a typed L<IO::K8s> object.
2255  
2256 =head2 create
2257  
2258 my $created = $api->create($pod);
2259  
2260 Create a resource from an L<IO::K8s> object. Returns the created object with server-assigned fields (UID, resourceVersion, etc.).
2261  
2262 =head2 update
2263  
2264 my $updated = $api->update($pod);
2265  
2266 Update an existing resource. Replaces the entire object server-side. Returns the updated object.
2267  
2268 For partial updates, use L</patch> instead.
2269  
2270 =head2 patch
2271  
2272 my $patched = $api->patch('Pod', 'my-pod',
2273 namespace => 'default',
2274 patch => { metadata => { labels => { env => 'staging' } } },
2275 );
2276  
2277 # Or with an object:
2278 my $patched = $api->patch($pod,
2279 patch => { metadata => { labels => { env => 'staging' } } },
2280 );
2281  
2282 # JSON Patch (RFC 6902) instead: an array of operations, not a hashref
2283 my $patched = $api->patch('Deployment', 'my-app',
2284 namespace => 'default',
2285 type => 'json',
2286 patch => [
2287 { op => 'replace', path => '/spec/replicas', value => 3 },
2288 { op => 'add', path => '/metadata/labels/env', value => 'prod' },
2289 ],
2290 );
2291  
2292 Partially update a resource. Unlike C<update()> which replaces the entire object, C<patch()> only modifies specified fields.
2293  
2294 Required: C<patch> (a hashref, or an arrayref of operations when C<type> is
2295 C<json>) and, when passing a class rather than an object, C<name>.
2296  
2297 Optional: C<namespace> (for namespaced resources) and C<type>, the patch
2298 strategy:
2299  
2300 =over 4
2301  
2302 =item C<strategic> (default)
2303  
2304 Strategic Merge Patch. The Kubernetes-native patch type, which understands
2305 array merge semantics (e.g. adding a container to a pod spec without removing
2306 the existing ones).
2307  
2308 =item C<merge>
2309  
2310 JSON Merge Patch (RFC 7396). Simple recursive merge where C<null> values
2311 delete keys; arrays are replaced entirely.
2312  
2313 =item C<json>
2314  
2315 JSON Patch (RFC 6902): an array of operations, as in the third example above.
2316  
2317 =back
2318  
2319 Returns the full updated object from the server.
2320  
2321 =head2 patch_status
2322  
2323 my $node = $api->patch_status('OCPNode', 'cp-1',
2324 namespace => 'ocp',
2325 patch => { status => { phase => 'Ready', ip => '10.0.0.7' } },
2326 );
2327  
2328 # Or with an object:
2329 my $node = $api->patch_status($node,
2330 patch => { status => { phase => 'Ready' } },
2331 );
2332  
2333 Partially update a resource's B<status> through the C</status> subresource.
2334  
2335 Once a CustomResourceDefinition declares C<subresources: {status: {}}>, the API
2336 server strips the C<status> stanza from every write to the main endpoint -
2337 C<create>, C<update>, C<patch> and server-side apply alike - and still answers
2338 2xx. The write appears to succeed and nothing is stored. Status has to go to
2339 C</status>, which is what this method addresses.
2340  
2341 Takes the same arguments as L</patch> (object or class plus name, both call
2342 forms, the same C<type> values) and returns the full object from the server.
2343 The patch document is passed through unchanged, so it carries its own
2344 C<status> key.
2345  
2346 The default patch type is C<merge>, not C<strategic> as in L</patch>: custom
2347 resources do not support strategic merge patch and the API server rejects it
2348 with 415, and C<merge> works for built-in kinds as well. Pass
2349 C<type =E<gt> 'strategic'> explicitly when patching the status of a built-in
2350 resource and you need array merge semantics.
2351  
2352 =head2 update_status
2353  
2354 my $node = $api->update_status($node);
2355  
2356 Replace a resource's B<status> through the C</status> subresource. The whole
2357 object is sent, as with L</update>, but the server only takes its C<status>
2358 and leaves C<spec> and C<metadata> untouched. Returns the updated object.
2359  
2360 This is the read-modify-write counterpart to L</patch_status>: it needs a
2361 current C<resourceVersion> and fails with a 409 conflict when the object
2362 changed in the meantime. Prefer L</patch_status> when you are setting
2363 individual status fields.
2364  
2365 =head2 delete
2366  
2367 $api->delete($pod);
2368 # or by name:
2369 $api->delete('Pod', name => 'my-pod', namespace => 'default');
2370 # or shorthand:
2371 $api->delete('Pod', 'my-pod', namespace => 'default');
2372  
2373 Delete a resource. Returns true on success.
2374  
2375 =head2 ensure
2376  
2377 my $obj = $api->ensure($pod);
2378 # or from a plain hashref (treated as a Kubernetes manifest):
2379 my $secret = $api->ensure({
2380 apiVersion => 'v1',
2381 kind => 'Secret',
2382 metadata => { name => 'foo', namespace => 'default' },
2383 stringData => { password => 'hunter2' },
2384 });
2385  
2386 Idempotent create-or-update. Fetches the resource by kind/name/namespace; if it
2387 exists, updates it (preserving C<resourceVersion>), otherwise creates it.
2388 Returns the resulting L<IO::K8s> object.
2389  
2390 Accepts either a typed L<IO::K8s> object or a plain hashref. A hashref must
2391 carry a C<kind> field and is inflated to a typed object via
2392 L<IO::K8s/struct_to_object>. Hashref keys follow the Kubernetes API convention
2393 (camelCase, e.g. C<stringData>, not C<string_data>).
2394  
2395 Handles common race conditions:
2396  
2397 =over 4
2398  
2399 =item * 404 on initial get is treated as "does not exist" and falls through to create.
2400  
2401 =item * 409 AlreadyExists on create (resource appeared between get and create) is
2402 retried as an update.
2403  
2404 =item * 409 Conflict on update (resourceVersion changed server-side, e.g. a
2405 controller wrote status) is retried by re-fetching and re-applying.
2406  
2407 =back
2408  
2409 Special-cases for kinds with server-side mutation constraints:
2410  
2411 =over 4
2412  
2413 =item * C<PersistentVolumeClaim> - spec is immutable after creation, so an existing
2414 PVC is returned unchanged.
2415  
2416 =item * C<Job> - spec is immutable; an existing Job that is active or has
2417 succeeded is returned unchanged. A failed Job is deleted and recreated.
2418  
2419 =back
2420  
2421 =head2 ensure_all
2422  
2423 my @results = $api->ensure_all(@objects);
2424  
2425 Batch version of L</ensure>. Applies create-or-update to each object in order
2426 and returns the list of resulting objects.
2427  
2428 =head2 ensure_only
2429  
2430 $api->ensure_only(
2431 label => 'app.kubernetes.io/component=queen',
2432 objects => \@objects,
2433 kinds => [qw(Role RoleBinding ClusterRoleBinding)],
2434 namespaces => ['default', 'kube-system', undef],
2435 );
2436  
2437 Like L</ensure_all>, but also B<deletes> any resources matching the label
2438 selector in the given kinds and namespaces that are not present in C<objects>.
2439 Use this for resources where stale objects must not survive (e.g. RBAC).
2440  
2441 Pass C<undef> inside C<namespaces> to scan cluster-scoped resources. If
2442 C<namespaces> is omitted, only cluster-scoped resources are scanned.
2443  
2444 Returns the list of applied objects (from L</ensure_all>).
2445  
2446 =head2 ensure_crd
2447  
2448 # one class == one single-version CRD
2449 $api->ensure_crd('My::K8s::StaticWebSite');
2450  
2451 # several distinct CRDs at once
2452 $api->ensure_crd(@crd_classes);
2453  
2454 # with options (pass the classes as an arrayref):
2455 $api->ensure_crd(\@crd_classes, timeout => 60, poll_interval => 2);
2456  
2457 # several classes that are versions of the SAME CRD -> one multi-version CRD
2458 $api->ensure_crd(
2459 [ 'My::K8s::V1beta1::Widget', 'My::K8s::V1::Widget' ],
2460 storage => 'v1',
2461 );
2462  
2463 Install (create-or-update) one or more CustomResourceDefinitions from typed
2464 L<IO::K8s> classes, wait for each to reach the C<Established> condition, then
2465 L</invalidate_discovery> so the new Kinds resolve on this client instance.
2466  
2467 Each class's CRD manifest comes from C<< $class->to_crd >> (L<IO::K8s::CRD>).
2468 The assembled CRD is applied with L</ensure>, so re-running is idempotent.
2469 After every CRD is applied, each is polled with L</get> by name until its
2470 C<status.conditions> carries C<< type => 'Established', status => 'True' >>,
2471 subject to a timeout. Only then is the discovery cache invalidated, so the
2472 next C<create>/C<list> of a custom resource does not race the apiserver
2473 registering the Kind (the reason plain C<ensure> of the CRD is not enough:
2474 the following call almost always creates a CR, which 404s until Established).
2475  
2476 Returns the list of established CustomResourceDefinition objects (the objects
2477 read back from the final poll, carrying their C<Established> status).
2478  
2479 Arguments: the CRD classes, either as a plain list (C<ensure_crd(@classes)>)
2480 or, when options are needed, as an arrayref followed by named options
2481 (C<ensure_crd(\@classes, %opts)>).
2482  
2483 =over 4
2484  
2485 =item timeout
2486  
2487 Seconds to wait for the C<Established> condition per CRD (default 30). On
2488 expiry the call croaks, naming the CRD and that C<Established> was not
2489 reached.
2490  
2491 =item poll_interval
2492  
2493 Seconds between polls (default 1). The current state is always checked once
2494 before the timeout is consulted, so C<timeout =E<gt> 0> performs exactly one
2495 poll.
2496  
2497 =item storage
2498  
2499 Only consulted when two or more passed classes name the SAME CRD (same group,
2500 plural, kind and scope but different versions). Those are assembled into ONE
2501 multi-version CustomResourceDefinition via
2502 C<< IO::K8s::CRD->new(classes => [...], storage => ...) >> rather than applied
2503 as competing single-version CRDs. Because a class carries no marker for which
2504 version is authoritative, the storage version is not guessed: pass it as a
2505 bare version string (applies to the multi-version group) or as a hashref
2506 keyed by CRD name (C<< { 'widgets.example.com' => 'v1' } >>). A multi-version
2507 group with no storage version croaks, naming the CRD and the candidate
2508 versions.
2509  
2510 =back
2511  
2512 =head2 watch
2513  
2514 my $last_rv = $api->watch('Pod',
2515 namespace => 'default',
2516 on_event => sub {
2517 my ($event) = @_;
2518 say $event->type . ": " . $event->object->metadata->name;
2519 },
2520 timeout => 300,
2521 resourceVersion => '12345',
2522 labelSelector => 'app=web',
2523 fieldSelector => 'status.phase=Running',
2524 );
2525  
2526 Watch for changes to resources. Uses the Kubernetes Watch API with chunked transfer encoding to stream events. The call blocks until the server-side timeout expires.
2527  
2528 Required: C<on_event>, a callback invoked with a L<Kubernetes::REST::WatchEvent> for each event.
2529  
2530 Optional:
2531  
2532 =over 4
2533  
2534 =item timeout
2535  
2536 Server-side timeout in seconds (default: 300). The API server closes the
2537 connection after this many seconds.
2538  
2539 =item resourceVersion
2540  
2541 Resume watching from a specific resource version - pass the return value of a
2542 previous C<watch()> call to avoid missing events.
2543  
2544 =item labelSelector
2545  
2546 Filter by label selector (e.g. C<'app=web,env=prod'>).
2547  
2548 =item fieldSelector
2549  
2550 Filter by field selector (e.g. C<'status.phase=Running'>).
2551  
2552 =item namespace
2553  
2554 For namespaced resources, the namespace to watch.
2555  
2556 =back
2557  
2558 Returns the last C<resourceVersion> seen. Croaks on 410 Gone once the given
2559 C<resourceVersion> has expired - re-list to get a fresh one and resume from
2560 there:
2561  
2562 my $rv;
2563 while (1) {
2564 $rv = eval {
2565 $api->watch('Pod',
2566 namespace => 'default',
2567 resourceVersion => $rv,
2568 on_event => \&handle_event,
2569 );
2570 };
2571 if ($@ && $@ =~ /410 Gone/) {
2572 # resourceVersion expired, re-list to get fresh version
2573 my $list = $api->list('Pod', namespace => 'default');
2574 $rv = undef; # start fresh
2575 }
2576 }
2577  
2578 =head2 log
2579  
2580 # One-shot: get full log as string
2581 my $text = $api->log('Pod', 'my-pod',
2582 namespace => 'default',
2583 tailLines => 100,
2584 );
2585  
2586 # Streaming: callback per log line
2587 $api->log('Pod', 'my-pod',
2588 namespace => 'default',
2589 follow => 1,
2590 on_line => sub {
2591 my ($event) = @_; # Kubernetes::REST::LogEvent
2592 say $event->line;
2593 },
2594 );
2595  
2596 Retrieve logs from a pod. Supports two modes:
2597  
2598 B<One-shot> (without C<on_line>): Returns the full log text as a string.
2599  
2600 B<Streaming> (with C<on_line>): Calls the callback for each log line with a L<Kubernetes::REST::LogEvent> object. Blocks until the stream ends (or the server closes the connection).
2601  
2602 Log output is returned as raw bytes in both modes - container output is not
2603 guaranteed to be UTF-8, or even text. Decode it yourself when you know it is:
2604 C<< Encode::decode('UTF-8', $text) >>. See L</ENCODING>.
2605  
2606 The streaming mode is designed for event-based systems like L<IO::Async> — see L<Net::Async::Kubernetes> for async integration.
2607  
2608 Also accepts, for namespaced resources, C<namespace>; and as further optional
2609 arguments: C<container> (name, for multi-container pods), C<sinceSeconds> /
2610 C<sinceTime> (show only recent output), C<timestamps> (prepend a timestamp to
2611 each line), C<previous> (logs from the container's previous run, after a
2612 restart), and C<limitBytes> (byte cap on the response).
2613  
2614 =head2 port_forward
2615  
2616 my $session = $api->port_forward('Pod', 'my-pod',
2617 namespace => 'default',
2618 ports => [8080, 8443],
2619 on_frame => sub { my ($channel, $payload) = @_; ... },
2620 );
2621  
2622 Start a full-duplex pod port-forward session.
2623  
2624 Required: C<name> and C<ports> - one port number or an arrayref of them (e.g.
2625 C<[8080, 8443]>).
2626  
2627 Optional: C<namespace> (for namespaced resources), C<subprotocol> (WebSocket
2628 subprotocol, default C<v4.channel.k8s.io>), and the duplex transport callbacks
2629 C<on_open>, C<on_frame>, C<on_close>, C<on_error>, passed through to the IO
2630 backend.
2631  
2632 This method requires an IO backend that implements C<call_duplex>. The default
2633 L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> backends do not
2634 currently provide duplex transport.
2635  
2636 Returns whatever the IO backend returns for C<call_duplex> (typically a
2637 session/handle object managed by that backend).
2638  
2639 =head2 exec
2640  
2641 my $session = $api->exec('Pod', 'my-pod',
2642 namespace => 'default',
2643 command => ['sh', '-c', 'echo hello'],
2644 stdin => 0,
2645 stdout => 1,
2646 stderr => 1,
2647 tty => 0,
2648 on_frame => sub { my ($channel, $payload) = @_; ... },
2649 );
2650  
2651 Start a full-duplex pod exec session via the C</exec> subresource.
2652  
2653 Required: C<name> and C<command> - a single string or an arrayref (e.g.
2654 C<['sh', '-c', 'id']>).
2655  
2656 Optional: C<namespace>, C<container> (for multi-container pods), the stream
2657 toggles C<stdin>/C<stdout>/C<stderr>/C<tty> shown above (defaults: stdin and
2658 tty off, stdout and stderr on), C<subprotocol> (WebSocket subprotocol, default
2659 C<v4.channel.k8s.io>), and the duplex transport callbacks C<on_open>,
2660 C<on_frame>, C<on_close>, C<on_error>, passed through to the IO backend.
2661  
2662 This method requires an IO backend that implements C<call_duplex>. The default
2663 L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> backends do not
2664 currently provide duplex transport.
2665  
2666 Returns whatever the IO backend returns for C<call_duplex> (typically a
2667 session/handle object managed by that backend).
2668  
2669 =head2 attach
2670  
2671 my $session = $api->attach('Pod', 'my-pod',
2672 namespace => 'default',
2673 container => 'app',
2674 stdin => 1,
2675 stdout => 1,
2676 stderr => 1,
2677 tty => 0,
2678 on_frame => sub { my ($channel, $payload) = @_; ... },
2679 );
2680  
2681 Start a full-duplex pod attach session via the C</attach> subresource.
2682  
2683 Required: C<name>.
2684  
2685 Optional: C<namespace>, C<container> (for multi-container pods), the stream
2686 toggles C<stdin>/C<stdout>/C<stderr>/C<tty> shown above (defaults: stdin and
2687 tty off, stdout and stderr on), C<subprotocol> (WebSocket subprotocol, default
2688 C<v4.channel.k8s.io>), and the duplex transport callbacks C<on_open>,
2689 C<on_frame>, C<on_close>, C<on_error>, passed through to the IO backend.
2690  
2691 This method requires an IO backend that implements C<call_duplex>. The default
2692 L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> backends do not
2693 currently provide duplex transport.
2694  
2695 Returns whatever the IO backend returns for C<call_duplex> (typically a
2696 session/handle object managed by that backend).
2697  
2698 =head1 NAME
2699  
2700 Kubernetes::REST - A Perl REST Client for the Kubernetes API
2701  
2702 =head1 UPGRADING FROM 0.02
2703  
2704 B<WARNING: Version 1.00 contains breaking changes!>
2705  
2706 This version has been completely rewritten. Key changes that may affect your code:
2707  
2708 =over 4
2709  
2710 =item * B<New simplified API>
2711  
2712 The old method-per-operation API (e.g., C<< $api->Core->ListNamespacedPod(...) >>)
2713 has been replaced with a simple API: C<list>, C<get>, C<create>, C<update>,
2714 C<patch>, C<patch_status>, C<update_status>, C<delete>, C<ensure>,
2715 C<ensure_all>, C<ensure_only>, C<watch>, C<log>, C<port_forward>, C<exec>,
2716 C<attach>.
2717  
2718 =item * B<Old API still works but deprecated>
2719  
2720 The old API is still available for backwards compatibility but will emit deprecation
2721 warnings. Set C<$ENV{HIDE_KUBERNETES_REST_V0_API_WARNING}> to suppress warnings.
2722  
2723 =item * B<Uses IO::K8s classes>
2724  
2725 Results are now returned as typed L<IO::K8s> objects instead of raw hashrefs.
2726 Lists are returned as L<IO::K8s::List> objects.
2727  
2728 B<Note:> L<IO::K8s> has also been completely rewritten (Moose to Moo, API
2729 objects updated to a current Kubernetes release). See
2730 L<IO::K8s/"UPGRADING FROM PREVIOUS VERSIONS"> for details.
2731  
2732 =item * B<Short resource names>
2733  
2734 You can now use short names like C<'Pod'> instead of full class paths. The
2735 C<resource_map> attribute controls this mapping.
2736  
2737 =item * B<Dynamic resource map>
2738  
2739 Use C<resource_map_from_cluster =E<gt> 1> to load the resource map from the
2740 cluster's OpenAPI spec, ensuring compatibility with any Kubernetes version.
2741  
2742 =back
2743  
2744 =head1 BUILDING BLOCKS FOR ASYNC WRAPPERS
2745  
2746 Async wrappers like L<Net::Async::Kubernetes> need access to the request/response
2747 pipeline without going through the synchronous convenience methods. The following
2748 public methods provide this:
2749  
2750 =over 4
2751  
2752 =item * C<expand_class($short)> - Resolve short name to full class
2753  
2754 =item * C<build_path($class, %args)> - Build REST API URL path
2755  
2756 =item * C<prepare_request($method, $path, %opts)> - Build HTTP request with auth
2757  
2758 =item * C<check_response($response, $context)> - Validate HTTP status
2759  
2760 =item * C<inflate_object($class, $response)> - JSON to typed object
2761  
2762 =item * C<inflate_list($class, $response)> - JSON to typed list (an item the
2763 object model rejects is dropped and carped about, not silently lost - see
2764 L</inflate_list>)
2765  
2766 =item * C<process_watch_chunk($class, \$buf, $chunk)> - Parse NDJSON watch stream
2767  
2768 =item * C<process_log_chunk(\$buf, $chunk)> - Parse plain-text log stream
2769  
2770 =back
2771  
2772 Example async integration:
2773  
2774 # Build request using Kubernetes::REST
2775 my $class = $rest->expand_class('Pod');
2776 my $path = $rest->build_path($class,
2777 name => $name,
2778 namespace => $ns,
2779 subresource => 'log',
2780 );
2781 my $req = $rest->prepare_request('GET', $path, parameters => { follow => 'true' });
2782  
2783 # Execute through your own event loop
2784 my $buffer = '';
2785 $async_http->request($req->url, sub {
2786 my ($chunk) = @_;
2787 for my $event ($rest->process_log_chunk(\$buffer, $chunk)) {
2788 $on_line->($event);
2789 }
2790 });
2791  
2792 =head1 PLUGGABLE IO ARCHITECTURE
2793  
2794 The HTTP transport is decoupled from request preparation and response
2795 processing. This makes it possible to swap the default L<LWP::UserAgent>
2796 backend for L<HTTP::Tiny> or an async backend (e.g. L<Net::Async::HTTP>)
2797 without changing any API logic.
2798  
2799 The pipeline for each API call:
2800  
2801 1. prepare_request() - builds HTTPRequest (method, url, headers, body)
2802 2. io->call() - executes request (pluggable backend)
2803 3. check_response() - validates HTTP status
2804 4. inflate_object/list - decodes JSON + inflates IO::K8s objects
2805  
2806 For watch, step 2 uses C<io-E<gt>call_streaming()> and step 4 uses
2807 C<process_watch_chunk()> which parses NDJSON and inflates each event.
2808  
2809 For log, step 2 uses C<io-E<gt>call_streaming()> and step 4 uses
2810 C<process_log_chunk()> which parses plain-text lines into L<Kubernetes::REST::LogEvent> objects.
2811  
2812 To implement a custom IO backend, consume L<Kubernetes::REST::Role::IO>
2813 and implement C<call($req)> and C<call_streaming($req, $callback)>.
2814 See L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> for
2815 reference implementations.
2816  
2817 =head1 ENCODING
2818  
2819 On the wire everything is bytes; in your program everything is characters.
2820 The boundary sits in this module, and you do not have to do anything for it:
2821  
2822 =over
2823  
2824 =item *
2825  
2826 Objects you pass to C<create>, C<update>, C<patch> and friends hold ordinary
2827 Perl character strings. They are UTF-8 encoded on the way into the request
2828 body, so C<< data => { note => "Caf\x{e9} \x{a7}" } >> is applied to the
2829 cluster unchanged.
2830  
2831 =item *
2832  
2833 Objects you get back from C<get>, C<list>, C<watch> and friends hold decoded
2834 characters, so C<length> counts characters and regexes match as expected.
2835  
2836 =item *
2837  
2838 Exception messages from failed API calls are decoded too.
2839  
2840 =back
2841  
2842 Two things stay bytes on purpose:
2843  
2844 =over
2845  
2846 =item *
2847  
2848 C<log> - container output is an arbitrary byte stream, not necessarily UTF-8,
2849 and decoding it would corrupt anything binary. Decode it yourself if you know
2850 it is text: C<< Encode::decode('UTF-8', $api->log('Pod', $name)) >>. The same
2851 applies to C<< $event->line >> in streaming mode.
2852  
2853 =item *
2854  
2855 The C<content> of L<Kubernetes::REST::HTTPRequest> and
2856 L<Kubernetes::REST::HTTPResponse> - these are the raw HTTP layer. Custom IO
2857 backends must honour that; see L<Kubernetes::REST::Role::IO/Encoding contract>.
2858  
2859 =back
2860  
2861 =head1 SEE ALSO
2862  
2863 =head2 Related Modules
2864  
2865 =over
2866  
2867 =item * L<IO::K8s> - Kubernetes resource classes (required dependency)
2868  
2869 =item * L<Net::Async::Kubernetes> - Async Kubernetes client for L<IO::Async>
2870  
2871 =back
2872  
2873 =head2 Configuration and Authentication
2874  
2875 =over
2876  
2877 =item * L<Kubernetes::REST::Kubeconfig> - Load settings from kubeconfig
2878  
2879 =item * L<Kubernetes::REST::Server> - Server connection configuration
2880  
2881 =item * L<Kubernetes::REST::AuthToken> - Authentication credentials
2882  
2883 =back
2884  
2885 =head2 HTTP Backends
2886  
2887 =over
2888  
2889 =item * L<Kubernetes::REST::Role::IO> - IO interface role
2890  
2891 =item * L<Kubernetes::REST::LWPIO> - LWP::UserAgent backend (default)
2892  
2893 =item * L<Kubernetes::REST::HTTPTinyIO> - HTTP::Tiny backend
2894  
2895 =item * L<LWP::ConsoleLogger> - HTTP debugging for LWPIO
2896  
2897 =back
2898  
2899 =head2 Data Objects
2900  
2901 =over
2902  
2903 =item * L<Kubernetes::REST::WatchEvent> - Watch event object
2904  
2905 =item * L<Kubernetes::REST::LogEvent> - Log event object
2906  
2907 =item * L<Kubernetes::REST::HTTPRequest> - HTTP request object
2908  
2909 =item * L<Kubernetes::REST::HTTPResponse> - HTTP response object
2910  
2911 =back
2912  
2913 =head2 CLI Tools
2914  
2915 =over
2916  
2917 =item * L<Kubernetes::REST::CLI> - CLI base class
2918  
2919 =item * L<Kubernetes::REST::CLI::Watch> - kube_watch CLI tool
2920  
2921 =item * L<Kubernetes::REST::CLI::Role::Connection> - Shared CLI options
2922  
2923 =back
2924  
2925 =head2 Examples and Documentation
2926  
2927 =over
2928  
2929 =item * L<Kubernetes::REST::Example> - Comprehensive examples with Minikube/K3s
2930  
2931 =item * L<https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.36/> - Kubernetes API reference
2932  
2933 =back
2934  
2935 =head1 SUPPORT
2936  
2937 =head2 Issues
2938  
2939 Please report bugs and feature requests on GitHub at
2940 L<https://github.com/pplu/kubernetes-rest/issues>.
2941  
2942 =head2 IRC
2943  
2944 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
2945  
2946 =head1 CONTRIBUTING
2947  
2948 Contributions are welcome! Please fork the repository and submit a pull request.
2949  
2950 =head1 AUTHORS
2951  
2952 =over 4
2953  
2954 =item *
2955  
2956 Torsten Raudssus <getty@cpan.org>
2957  
2958 =item *
2959  
2960 Jose Luis Martinez Torres <jlmartin@cpan.org>
2961  
2962 =back
2963  
2964 =head1 COPYRIGHT AND LICENSE
2965  
2966 This software is Copyright (c) 2019-2026 by Jose Luis Martinez Torres <jlmartin@cpan.org>.
2967  
2968 This is free software, licensed under:
2969  
2970 The Apache License, Version 2.0, January 2004
2971  
2972 =cut
« blib/lib/Kubernetes/REST/CLI/Watch.pm ↑ Summary blib/lib/Kubernetes/REST/CLI/Minikube.pm »