lib/Kubernetes/REST.pm

filter: Statementstmt 98.5% 1013 / 1028 Branchbran 85.5% 467 / 546 Conditioncond 65.4% 227 / 347 MC/DCmcdc 39.9% 77 / 193 Subroutinesub 100% 130 / 130 Podpod 66.6% 32 / 48 totaltotal 84.9% 1946 / 2292 CC 436 SCAR 24.7
CC
436
Cov
89%
_build_path
31.7
exec
26.2
schema_for
19.4
CRAP 11.8
« blib/lib/Kubernetes/REST/CLI/Crd2Class.pm ↑ Summary lib/Kubernetes/REST/CLI/Minikube.pm »
1 package Kubernetes::REST;
2 63 our $VERSION = '1.109';
3 # ABSTRACT: A Perl REST Client for the Kubernetes API
4 63 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 63 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 63 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 63 ▶use Module::Runtime qw(require_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 63 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 63 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 63 ▶use Kubernetes::REST::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 63 ▶use Kubernetes::REST::AuthToken;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 63 ▶use Kubernetes::REST::LWPIO;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 63 ▶use Kubernetes::REST::HTTPRequest;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 63 ▶use IO::K8s;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 63 ▶use IO::K8s::List;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 63 ▶use IO::K8s::CRD;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 63 ▶use IO::K8s::Unstructured ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 63 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 63 ▶use Kubernetes::REST::WatchEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 63 ▶use Kubernetes::REST::LogEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 63 ▶use Kubernetes::REST::APIError;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 63 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 has server => (
25 is => 'ro',
26 required => 1,
27 440 ▶ coerce => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
28 440 my $val = $_[0];
29 440 ▶ return $val if blessed($val) && $val->isa('Kubernetes::REST::Server');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($val) and $val->isa("Kubernetes::REST::Server") 270 170 440
Condition66%2/3
builtin::blessed($val) and $val->isa("Kubernetes::REST::Server")
!ll&&!rl&&r
1700270
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
30 170 Kubernetes::REST::Server->new($val);
31 },
32 63 );
33  
34  
35 has credentials => (
36 is => 'ro',
37 required => 1,
38 440 ▶ coerce => sub {
Subroutine __ANON__: called CC=4 SCAR=14.6
39 440 my $val = $_[0];
40 440 ▶ return $val if blessed($val) && $val->can('token');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($val) and $val->can("token") 270 170 440
Condition66%2/3
builtin::blessed($val) and $val->can("token")
!ll&&!rl&&r
1700270
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
41 170 ▶ return Kubernetes::REST::AuthToken->new($val) if ref($val) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $val eq "HASH" 170 0 170
42 0 return $val;
43 }
44 63 );
45  
46  
47 has io => (
48 is => 'ro',
49 lazy => 1,
50 1 ▶ default => sub {
Subroutine __ANON__: called CC=7 SCAR=23.2
51 1 my $self = shift;
52 1 my $s = $self->server;
53 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
54 ssl_verify_server => $s->ssl_verify_server,
55 (defined $s->ssl_cert_pem ? (ssl_cert_pem => $s->ssl_cert_pem) : ()),
56 (defined $s->ssl_cert_file ? (ssl_cert_file => $s->ssl_cert_file) : ()),
57 (defined $s->ssl_key_pem ? (ssl_key_pem => $s->ssl_key_pem) : ()),
58 (defined $s->ssl_key_file ? (ssl_key_file => $s->ssl_key_file) : ()),
59 (defined $s->ssl_ca_pem ? (ssl_ca_pem => $s->ssl_ca_pem) : ()),
60 (defined $s->ssl_ca_file ? (ssl_ca_file => $s->ssl_ca_file) : ()),
61 );
62 },
63 63 );
64  
65  
66 # utf8 => 1 makes encode() return UTF-8 bytes and decode() expect them, which is
67 # what HTTP::Request->content requires and what IO::K8s already assumes. See the
68 # ENCODING section below.
69 has _json => (
70 is => 'ro',
71 440 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
72 440 JSON::MaybeXS->new(utf8 => 1, canonical => 1, convert_blessed => 1);
73 },
74 63 );
75  
76 # External IO::K8s resource-map providers, mirrored onto the inner instance.
77 has with => (
78 is => 'ro',
79 433 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
80 63 );
81  
82  
83 # IO::K8s instance - configured with same resource_map
84 has k8s => (
85 is => 'ro',
86 lazy => 1,
87 predicate => '_has_k8s',
88 clearer => '_clear_k8s',
89 248 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
90 248 my $self = shift;
91 return IO::K8s->new(
92 resource_map => $self->resource_map,
93 248 ▶ with => [ @{ $self->with } ],
Branch: 1 branch
BranchTrueFalseTotal
$self->_has_openapi_spec ? : 13 235 248
94 # openapi_spec is an eager hashref on IO::K8s: handing it over here
95 # only once it has actually been fetched keeps constructing/using
96 # the inner instance from forcing the /openapi/v2 download (D12).
97 # Until then it is absent; _fetch_openapi_spec rebuilds this
98 # instance once the spec exists.
99 ($self->_has_openapi_spec ? (openapi_spec => $self->_openapi_spec) : ()),
100 );
101 },
102 63 handles => [qw(
103 new_object
104 inflate
105 json_to_object
106 struct_to_object
107 object_to_json
108 object_to_struct
109 load
110 load_yaml
111 )],
112 );
113  
114  
115 # Set to 0 to use IO::K8s defaults instead of loading from cluster
116 126 ▶has resource_map_from_cluster => (is => 'ro', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
117  
118  
119 # Cluster version - fetched once per instance
120 has cluster_version => (
121 is => 'ro',
122 lazy => 1,
123 2 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
124 2 my $self = shift;
125 2 my $response = $self->_request('GET', '/version');
126 2 ▶ return 'unknown' if $response->status >= 400;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status >= 400 1 1 2
127 1 my $info = $self->_json->decode($response->content);
128 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
129 },
130 63 );
131  
132  
133 # Resource map - loads from cluster by default, cached per instance (lazy)
134 # The predicate is true once the map exists: passed in by the caller, or
135 # built (fetched) on first use. expand_class() keys its cheap path off it.
136 has resource_map => (
137 is => 'ro',
138 lazy => 1,
139 predicate => '_has_resource_map',
140 clearer => '_clear_resource_map',
141 # Always a hash of our own: the inner IO::K8s merges the `with` providers
142 # into this hashref in place (IO::K8s::add). A map passed to the
143 # constructor is the caller's, and the fallback of a failed cluster fetch
144 # is IO::K8s's process-wide built-in map - neither may grow by the
145 # provider Kinds (karr k57). Moo coerces the default's value too.
146 252 ▶ coerce => sub { ref $_[0] eq 'HASH' ? { %{ $_[0] } } : $_[0] },
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 252 0 252
147 214 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
148 214 my $self = shift;
149 # Built here, not passed in: absorb_discovery may rebuild it.
150 214 $self->_resource_map_built(1);
151 # A private copy, never IO::K8s's shared global map: the inner IO::K8s
152 # is handed this hashref and merges any `with` providers into it with
153 # add(), which mutates it in place. Returning the global ref would leak
154 # provider Kinds into IO::K8s->default_resource_map process-wide.
155 214 ▶ return { %{ IO::K8s->default_resource_map } } unless $self->resource_map_from_cluster;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->resource_map_from_cluster 168 46 214
156 46 return $self->_load_resource_map_from_cluster;
157 },
158 63 );
159  
160  
161 # Whether the resource map in place was built by the default above rather
162 # than passed to the constructor. absorb_discovery rebuilds a built map from
163 # the catalog it takes; a map the caller passed is theirs and stays (karr k51).
164 63 has _resource_map_built => (is => 'rw', init_arg => undef);
165  
166 # Deliberately NOT delegated to the k8s attribute like the other IO::K8s
167 # methods: building that instance forces the lazy resource_map, which on the
168 # default resource_map_from_cluster => 1 is a full GET /openapi/v2 - paid for
169 # resolving a name like 'Pod' whose answer already sits in the built-in map
170 # (karr #15).
171 372 ▶sub expand_class {
Subroutine expand_class: called CC=12 SCAR=24.9
Pod documented
172 372 my ($self, @args) = @_;
173  
174  
175 372 ▶ 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]) 44 328 372
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
328044
$self->resource_map_from_cluster and not $self->_has_resource_map and defined $args[0]
!ll&&!rl&&r
328044
$self->resource_map_from_cluster and not $self->_has_resource_map
!ll&&!rl&&r
2824644
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
176 && defined $args[0] && !ref $args[0]) {
177 # '+Full::Class::Name' names an exact class - no map consulted either
178 # way, and by contract it is returned without being loaded.
179 44 ▶ return substr($args[0], 1) if $args[0] =~ /^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $args[0] =~ /^\+/ 2 42 44
180 # As a class method, IO::K8s->expand_class resolves against the
181 # built-in map. Its fallback for an unknown Kind is the *name*
182 # 'IO::K8s::<Kind>' whether or not such a class exists, so a cheap
183 # answer only counts when it names a class that actually loads.
184 # Anything else falls through to the cluster-backed instance below,
185 # which fetches the cluster map exactly as it always did.
186 42 my $class = IO::K8s->expand_class(@args);
187 return $class if defined $class
188 42 ▶ && ($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 } } 9 33 42
Condition100%6/6
defined $class and $class->can("new") || eval {
!ll&&!rl&&r
7269
$class->can("new") or eval {
l!l&&r!l&&!r
8126
MC/DC100%3/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 table100%4/4
A and B or C
A= defined $classB= $class->can("new")C= eval { do { &require_module($class); 1 } }
ABCresult
0XX0
1000
11X1
1011
189 }
190  
191 # Fall through to the cluster-backed inner IO::K8s, which owns the
192 # resolution order (design D13, extending the 2026-08-10 exact-GVK
193 # contract):
194 # rung 1 an explicit '+Full::Class' in the caller's resource_map
195 # rung 2 provider classes merged from `with`
196 # rung 3 AutoGen from openapi_spec, once the spec has been fetched
197 # rung 5 the existing fail-closed GVK error
198 # The discovery-built map (see _resource_map_from_catalog) no longer
199 # short-circuits this order with invented IO::K8s::Api::<Group> names for
200 # groups this distribution does not ship (D12): a foreign Kind with no
201 # provider and no loaded spec now reaches rung 4/5 instead of resolving to
202 # a bogus class.
203 361 my $class = $self->k8s->expand_class(@args);
204  
205 # How IO::K8s signals "nothing resolved this Kind" depends on the argument
206 # shape, and only that exact signal may be diverted to rung 4 -- every real
207 # resolution (rungs 1-3: a '+Full::Class', a provider from `with`, a builtin
208 # or an AutoGen class) must be returned untouched, including a '+'-class
209 # that names a class not yet loaded (returned by contract without loading,
210 # so a load probe would wrongly reject it -- karr t/36 subtest 3).
211 #
212 # For a bare Kind IO::K8s fails *open*: it fabricates the name
213 # 'IO::K8s::<Kind>' whether or not such a class exists, and the fail-closed
214 # error only surfaces later when require_module() cannot load it. For an
215 # exact-GVK or domain-qualified request it fails *closed*, returning undef.
216 # Both -- and nothing else -- mean unresolved (_is_unresolved).
217 361 my ($kind, $api_version) = $self->_kind_from_expand_args(@args);
218 361 ▶ return $class unless defined $kind && $self->_is_unresolved($class, $kind);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind and $self->_is_unresolved($class, $kind) 258 103 361
Condition100%3/3
defined $kind and $self->_is_unresolved($class, $kind)
!ll&&!rl&&r
54204103
MC/DC100%2/2
defined $kind and $self->_is_unresolved($class, $kind)
defined $kind $self->_is_unresolved($class, $kind)
Truth table100%3/3
A and B
A= defined $kindB= $self->_is_unresolved($class, $kind)
ABresult
0X0
100
111
219  
220 # Rung 4 (D16): the Kind resolved to nothing that ships. If the cluster
221 # confirms this GVK through aggregated discovery, resolve to
222 # IO::K8s::Unstructured -- its plural and scope come from the discovery
223 # catalog at path-build time (_build_path), since Unstructured carries no
224 # api_version()/resource_plural()/Namespaced role of its own. On by default
225 # (no opt-in here, unlike bare IO::K8s): D16 gates it on discovery
226 # confirmation instead. _discovery_path_meta is a no-op (undef) unless
227 # resource_map_from_cluster is set, and by the time control reaches here the
228 # catalog was already fetched building the cluster map, so this consults a
229 # cache and never adds a round-trip. A Kind discovery does not serve stays
230 # fail-closed (rung 5): the fabricated name (or undef) is returned so the
231 # load error still names the Kind. A qualified name, or a Kind plus
232 # apiVersion, is confirmed only in exactly its group/version: another
233 # group or version serving the Kind leaves it at rung 5 too (karr k43).
234 # A discovery *failure* (cluster unreachable, expired token) is
235 # deliberately treated the same as "not served" here -- rung 5,
236 # fail-closed -- with the reason kept in
237 # _discovery_error; on the CRUD path the carp from
238 # _load_resource_map_from_cluster has already named it while building the
239 # cluster map.
240 103 ▶ return 'IO::K8s::Unstructured'
Branch: 1 branch
BranchTrueFalseTotal
if $self->_discovery_path_meta($kind, $api_version) 37 66 103
241 if $self->_discovery_path_meta($kind, $api_version);
242  
243 66 return $class;
244 }
245  
246 # Whether $class, what expand_class() made of a name whose Kind is $kind (from
247 # _kind_from_expand_args), is the signal that nothing resolved it: undef, or
248 # the 'IO::K8s::<Kind>' IO::K8s fabricates for a bare Kind when that class does
249 # not load (see expand_class). Every real resolution is resolved, including a
250 # '+'-class that is not loaded yet.
251 567 ▶sub _is_unresolved {
Subroutine _is_unresolved: called CC=5 SCAR=16.8
252 567 my ($self, $class, $kind) = @_;
253 567 ▶ return 1 unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 73 494 567
254 return defined $kind
255 && $class eq "IO::K8s::$kind"
256 494 ▶ && !($class->can('new') || eval { require_module($class); 1 });
Condition66%6/9
defined $kind && $class eq "IO::K8s::$kind" && !($class->can('new') || eval {
!ll&&!rl&&r
415079
defined $kind and $class eq "IO::K8s::$kind"
!ll&&!rl&&r
5236379
$class->can('new') || eval {
l!l&&r!l&&!r
0079
MC/DC50%2/4
defined $kind && $class eq "IO::K8s::$kind" && !($class->can('new') || eval { do { &require_module($class); 1 } })
defined $kind $class eq "IO::K8s::$kind" $class->can('new') eval { do { &require_module($class); 1 } }
Truth table60%3/5
A and B && not(C || D)
A= defined $kindB= $class eq "IO::K8s::$kind"C= $class->can('new')D= eval { do { &require_module($class); 1 } }
ABCDresult
0XXX0
10XX0
111X0
11010
11001
257 }
258  
259 # expand_class() for the methods that take a resource name and build a request
260 # path from its class (list, get, patch, patch_status, delete, watch, log,
261 # port_forward, exec, attach) or load it (compare_schema). A name nothing
262 # resolves croaks here, naming it the way Net::Async::Kubernetes does, before
263 # any request (karr k46) - instead of in _build_path, where require_module saw
264 # only expand_class's answer: undef for a qualified name ("argument is not a
265 # module name"), or a bare Kind's fabricated class ("Can't locate
266 # IO/K8s/<Kind>.pm", naming a module that does not exist). A discovery
267 # failure is named with it: an unreachable cluster could not confirm the name,
268 # which is not the same as a cluster that does not serve it (karr k28). Only
269 # for a name with a Kind - expand_class consulted discovery for exactly that
270 # one, so the recorded failure is this call's. expand_class itself keeps
271 # returning undef or the fabricated name: that is its public contract, and
272 # _manifest_to_object reads the undef.
273 260 ▶sub _expand_class_or_croak {
Subroutine _expand_class_or_croak: called CC=6 SCAR=18.0
274 260 my ($self, $name) = @_;
275 260 my $class = $self->expand_class($name);
276 260 my ($kind) = $self->_kind_from_expand_args($name);
277 260 ▶ return $class unless $self->_is_unresolved($class, $kind);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_is_unresolved($class, $kind) 211 49 260
278 49 ▶ my $discovery_error = defined $kind ? $self->_discovery_error : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $kind ? : 49 0 49
279 49 ▶ $discovery_error = $self->_error_reason($discovery_error) if defined $discovery_error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $discovery_error 3 46 49
280 49 ▶ croak "unknown resource '" . ($name // '(undef)') . "': no IO::K8s class"
Branch: 1 branch
BranchTrueFalseTotal
defined $discovery_error ? : 3 46 49
Condition50%1/2
$name // "(undef)"
l!l
490
MC/DC0%0/1
$name // "(undef)"
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
281 . " for this apiVersion/kind (add it to resource_map if it is a CRD)"
282 . (defined $discovery_error
283 ? "; discovery failed, so the cluster could not confirm it: $discovery_error"
284 : '');
285 }
286  
287 # A caught error - a croak's string, or an APIError - as the reason another
288 # message embeds: its text without the location it ends with. That location
289 # names a line in here, or whatever frame a lazy builder left; the message it
290 # goes into names the caller's line itself (karr k59). Once a file handle has
291 # been read, Carp's location ends ', <$fh> line N.' (or 'chunk N').
292 42 ▶sub _error_reason {
Subroutine _error_reason: called CC=1 SCAR=0.0
293 42 my ($self, $error) = @_;
294 42 my $reason = "$error";
295 42 $reason =~ s/(?: at \S+ line \d+(?:, <[^>]*> (?:line|chunk) \d+)?\.)?\s*\z//;
296 42 return $reason;
297 }
298  
299 # carp, for a warning raised while a lazy attribute is built - the discovery
300 # catalog, the resource map built from it. Carp skips the frames of Moo's
301 # generated accessors (Moo marks them internal), but not the frame where this
302 # package calls into one, so a plain carp named the line in here that first
303 # asked for the attribute (karr k63, k64). Trusting the generated accessors
304 # for this one warning lets it name the caller's line, as a warning from a
305 # plain method does. Not package-wide: that would move every other croak.
306 15 ▶sub _carp_past_builders {
Subroutine _carp_past_builders: called CC=1 SCAR=0.0
307 15 my ($self, $message) = @_;
308 15 local our @CARP_NOT = ('Method::Generate::Accessor::_Generated');
309 15 carp $message;
310 15 return;
311 }
312  
313 # Extract the Kubernetes Kind (and any explicitly supplied apiVersion) from an
314 # expand_class() argument list, for the D16 rung-4 discovery-confirmation
315 # check. Only bare short names ('Widget') and domain-qualified strings
316 # ('example.com/v1/Widget') name a Kind that Unstructured should stand in for;
317 # a '+Full::Class', an 'IO::K8s::...' name or any multi-segment package name is
318 # an explicit class request and must never be diverted to Unstructured.
319 631 ▶sub _kind_from_expand_args {
Subroutine _kind_from_expand_args: called CC=7 SCAR=19.6
320 631 my ($self, $name, $api_version) = @_;
321 631 ▶ return () unless defined $name && !ref $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name 0 631 631
Condition33%1/3
defined $name and not ref $name
!ll&&!rl&&r
00631
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
322 631 ▶ return () if $name =~ /^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^\+/ 5 626 631
323 626 ▶ return () if $name =~ /^IO::K8s::/;
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^IO::K8s::/ 100 526 626
324 526 ▶ if ($name =~ m{/}) { # 'group/version/Kind' -> ('Kind', 'group/version')
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ m[/]) 86 440 526
325 86 my ($av, $kind) = $name =~ m{\A(.*)/([^/]+)\z};
326 86 return ($kind, $av);
327 }
328 440 ▶ return () if $name =~ /::/; # a multi-segment class name, not a Kind
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /::/ 1 439 440
329 439 return ($name, $api_version);
330 }
331  
332 # Path metadata (apiVersion, resource plural, namespaced) for a Kind, read from
333 # the cached discovery catalog. This is how a Kind resolved to
334 # IO::K8s::Unstructured (D16 rung 4) gets what _build_path needs: Unstructured
335 # has apiVersion/kind on the *instance* but no api_version()/resource_plural()
336 # class method and no Namespaced role, so plural and scope cannot come from the
337 # class the way a typed resource's do -- they come from here.
338 #
339 # Returns undef (fail-closed) unless resource_map_from_cluster is set: with no
340 # cluster there is no discovery to confirm a GVK, and this must never trigger a
341 # fetch on the fetch-free path. When it does run, the catalog is already cached
342 # (building the cluster resource map fetched it), so the lookup is free.
343 #
344 # A fetch that fails outright (cluster unreachable, expired token) returns the
345 # same undef as a healthy catalog that lacks the Kind -- deliberately
346 # fail-closed (D16: an unreachable cluster must not let anything pass as
347 # confirmed) -- but the reason is kept in _discovery_error so _build_path can
348 # name it instead of claiming a missing entry.
349 #
350 # $want_api_version, when given (a qualified name's group/version, or an
351 # Unstructured object's own apiVersion), pins the group/version, and nothing
352 # else will do; without it the group's discovery-preferred version wins,
353 # matching _resource_map_from_catalog and D17.
354 140 ▶sub _discovery_path_meta {
Subroutine _discovery_path_meta: called CC=15 SCAR=27.8
355 140 my ($self, $kind, $want_api_version) = @_;
356 140 ▶ return unless $self->resource_map_from_cluster;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->resource_map_from_cluster 36 104 140
357 104 my $catalog = eval { $self->_discovery };
358 104 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 7 97 104
359 7 $self->_discovery_error($error);
360 7 return;
361 }
362 97 $self->_clear_discovery_error;
363 97 ▶ return unless $catalog && $catalog->{groups};
Branch: 1 branch
BranchTrueFalseTotal
unless $catalog and $catalog->{"groups"} 0 97 97
Condition33%1/3
$catalog and $catalog->{"groups"}
!ll&&!rl&&r
0097
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
364  
365 63 ▶ my $meta_for = sub {
Subroutine __ANON__: called CC=4 SCAR=14.3
366 63 my ($group, $version, $res) = @_;
367 return {
368 api_version => ($group eq '' ? $version : "$group/$version"),
369 resource => $res->{resource},
370 63 ▶ namespaced => ($res->{scope} && $res->{scope} eq 'Namespaced' ? 1 : 0),
Branch: 2 branches
BranchTrueFalseTotal
$group eq '' ? : 0 63 63
$res->{'scope'} && $res->{'scope'} eq 'Namespaced' ? : 61 2 63
Condition66%2/3
$res->{"scope"} and $res->{"scope"} eq "Namespaced"
!ll&&!rl&&r
0261
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
371 };
372 97 };
373  
374 # An explicit apiVersion pins the exact group/version, and only that one.
375 # It names one GVK, and a cluster that does not serve that GVK has not
376 # confirmed it (D16) - not even when another group, or another version of
377 # the same group, serves a Kind of that name. Falling back there would
378 # address that other resource: list, delete and ensure_only's prune would
379 # land in it (karr k43). The same rule as IO::K8s's exact-GVK resolution,
380 # where an explicit version never falls back to the bare Kind's.
381 97 ▶ if (defined $want_api_version && length $want_api_version) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $want_api_version and length $want_api_version) 48 49 97
Condition66%2/3
defined $want_api_version and length $want_api_version
!ll&&!rl&&r
49048
MC/DC50%1/2
defined $want_api_version and length $want_api_version
defined $want_api_version length $want_api_version
Truth table66%2/3
A and B
A= defined $want_api_versionB= length $want_api_version
ABresult
0X0
100
111
382 48 ▶ my ($g, $v) = $want_api_version =~ m{/}
Branch: 1 branch
BranchTrueFalseTotal
$want_api_version =~ m[/] ? : 48 0 48
383 ? split(m{/}, $want_api_version, 2)
384 : ('', $want_api_version);
385 48 my $res = $catalog->{groups}{$g}{versions}{$v}{kinds}{$kind};
386 48 ▶ return unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 24 24 48
387 24 return $meta_for->($g, $v, $res);
388 }
389  
390 # A bare Kind: the preferred version of whichever group serves it (D17).
391 49 for my $group (sort keys %{$catalog->{groups}}) {
392 104 my $gdata = $catalog->{groups}{$group};
393 104 ▶ my @order = @{$gdata->{version_order} // []};
Condition50%1/2
$gdata->{"version_order"} // []
l!l
1040
MC/DC0%0/1
$gdata->{"version_order"} // []
$gdata->{"version_order"}
Truth table50%1/2
A
A= $gdata->{"version_order"}
Aresult
11
00
394 104 my $pref = $gdata->{preferred};
395 105 @order = ($pref, grep { $_ ne $pref } @order)
396 104 ▶ if defined $pref && grep { $_ eq $pref } @order;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pref and grep {$_ eq $pref;} @order 104 0 104
Condition33%1/3
defined $pref and grep {$_ eq $pref;} @order
!ll&&!rl&&r
00104
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
397 104 for my $version (@order) {
398 104 my $res = $gdata->{versions}{$version}{kinds}{$kind};
399 104 ▶ return $meta_for->($group, $version, $res) if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 39 65 104
400 }
401 }
402 10 return;
403 }
404  
405 # The extra _build_path arguments an IO::K8s::Unstructured resolution needs,
406 # derived from whatever identifier expand_class was given: an IO::K8s object
407 # (its kind/apiVersion accessors) or a name string. A string is split the way
408 # expand_class split it to confirm the GVK, so a qualified
409 # 'example.org/v1/Widget' keeps its group/version and does not land in
410 # whichever other group serving a Widget discovery lists first. Empty for
411 # every typed class, so typed path building is completely unchanged.
412 348 ▶sub _unstructured_hint {
Subroutine _unstructured_hint: called CC=7 SCAR=19.7
413 348 my ($self, $class, $ident) = @_;
414 348 ▶ return () unless defined $class && $class eq 'IO::K8s::Unstructured';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and $class eq "IO::K8s::Unstructured" 324 24 348
Condition66%2/3
defined $class and $class eq "IO::K8s::Unstructured"
!ll&&!rl&&r
032424
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
415 24 ▶ if (blessed($ident)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($ident)) 15 9 24
416 return (
417 15 ▶ kind => $ident->kind,
Branch: 1 branch
BranchTrueFalseTotal
defined $ident->apiVersion ? : 15 0 15
418 (defined $ident->apiVersion ? (api_version => $ident->apiVersion) : ()),
419 );
420 }
421 9 my ($kind, $api_version) = $self->_kind_from_expand_args($ident);
422 return (
423 9 ▶ (defined $kind ? (kind => $kind) : ()),
Branch: 2 branches
BranchTrueFalseTotal
defined $kind ? : 9 0 9
defined $api_version ? : 3 6 9
424 (defined $api_version ? (api_version => $api_version) : ()),
425 );
426 }
427  
428 # Kubernetes groups whose IO::K8s classes do NOT live under IO::K8s::Api::.
429 # Their namespace follows the upstream Go staging repository the types are
430 # generated from (apiextensions-apiserver, kube-aggregator), not the API group
431 # name, so it cannot be derived - it has to be listed here.
432 #
433 # Keyed on the full group name, because that is the only globally unique
434 # identifier: a cluster is free to serve a CRD group called
435 # apiextensions.example.com, and that group is an ordinary one.
436 63 my %NON_API_NAMESPACE = (
437 'apiextensions.k8s.io' => 'ApiextensionsApiserver::Pkg::Apis::Apiextensions',
438 'apiregistration.k8s.io' => 'KubeAggregator::Pkg::Apis::Apiregistration',
439 );
440  
441 # The same table, indexed by the IO::K8s group directory instead - the trailing
442 # segment of each namespace above is exactly that directory name. Derived, so
443 # there is still only one place to add a group.
444 my %NON_API_NAMESPACE_BY_GROUP_PATH =
445 63 map { ((split /::/)[-1] => $_) } values %NON_API_NAMESPACE;
446  
447 # Namespace below IO::K8s:: for a Kubernetes API group name as the cluster's
448 # OpenAPI spec reports it: '' for core, 'apps', 'apiextensions.k8s.io',
449 # 'cert-manager.io', ... The exception table is matched exactly on the full
450 # name - a CRD group that merely starts with 'apiextensions' is an ordinary
451 # group and must keep landing under Api::.
452 179 ▶sub _io_k8s_namespace_for_group {
Subroutine _io_k8s_namespace_for_group: called CC=3 SCAR=11.0
453 179 my ($self, $group) = @_;
454 179 ▶ return $NON_API_NAMESPACE{$group} if exists $NON_API_NAMESPACE{$group};
Branch: 1 branch
BranchTrueFalseTotal
if exists $NON_API_NAMESPACE{$group} 15 164 179
455 164 ▶ return 'Api::' . ($group eq '' ? 'Core' : ucfirst(lc((split /\./, $group)[0])));
Branch: 1 branch
BranchTrueFalseTotal
$group eq '' ? : 65 99 164
456 }
457  
458 # Namespace below IO::K8s:: for an IO::K8s group directory name - 'Core',
459 # 'Apps', 'Apiextensions'. That is the form the v0 compatibility layer carries,
460 # and it is a closed set of names this distribution ships, so unlike a group
461 # name off the wire it needs no exact-match guard.
462 80 ▶sub _io_k8s_namespace_for_group_path {
Subroutine _io_k8s_namespace_for_group_path: called CC=2 SCAR=6.9
463 80 my ($self, $group_path) = @_;
464 80 ▶ 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
971
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
465 }
466  
467 # Public method to build the resource map from the cluster's discovery catalog
468 70 ▶sub fetch_resource_map {
Subroutine fetch_resource_map: called CC=2 SCAR=6.9
Pod documented
469 70 my ($self) = @_;
470  
471  
472 # The cluster resource map is built from aggregated discovery, not from the
473 # multi-MB /openapi/v2 spec (design D11): a small GET /api + GET /apis gives
474 # every group, version, plural, Kind and scope. The catalog is cached in the
475 # _discovery attribute and shared by later rebuilds; /openapi/v2 stays lazy
476 # for schema_for/compare_schema only. The failure keeps this method's
477 # documented wording; the underlying error rides along.
478 70 my $catalog = eval { $self->_discovery };
479 70 ▶ croak 'Could not load resource map from cluster: ' . $self->_error_reason($@)
Branch: 1 branch
BranchTrueFalseTotal
unless $catalog 16 54 70
480 unless $catalog;
481  
482 54 return $self->_resource_map_from_catalog($catalog);
483 }
484  
485 # Turn the cached discovery catalog into the short-name -> IO::K8s class map.
486 # The namespace comes from _io_k8s_namespace_for_group (exception tables
487 # included) and List kinds are skipped. Two rules shape which entries land:
488 #
489 # D17 preferred version: among the versions a group serves a Kind in, the
490 # version the cluster marks preferred wins the bare short name (not "stable
491 # beats alpha/beta" -- that heuristic is gone). A Kind served only outside
492 # the preferred version still maps, to its first served version, so nothing
493 # the cluster serves is dropped.
494 #
495 # D12/D13 stop inventing: an entry is recorded only when the candidate
496 # IO::K8s class actually ships. A foreign group (cilium.io, cert-manager.io)
497 # has no IO::K8s::Api::<Group> class, so its Kinds are omitted here and left
498 # to resolve through the inner IO::K8s pipeline (provider from `with` ->
499 # AutoGen from openapi_spec -> D16 Unstructured -> fail-closed) rather than
500 # short-circuiting to a bogus name. Core-API groups and the two exception
501 # groups (apiextensions/apiregistration) do ship, so their Kinds map exactly
502 # as before.
503 54 ▶sub _resource_map_from_catalog {
Subroutine _resource_map_from_catalog: called CC=11 SCAR=24.0
504 54 my ($self, $catalog) = @_;
505  
506 54 my %map;
507 54 ▶ for my $group (keys %{$catalog->{groups} // {}}) {
Condition50%1/2
$catalog->{"groups"} // {}
l!l
540
MC/DC0%0/1
$catalog->{"groups"} // {}
$catalog->{"groups"}
Truth table50%1/2
A
A= $catalog->{"groups"}
Aresult
11
00
508 140 my $gdata = $catalog->{groups}{$group};
509  
510 # D17: try the cluster's preferred version first, then the rest in
511 # discovery order; the first version to yield a shipping class for a
512 # Kind keeps the short name. Where the preferred version's class does
513 # not ship but another served version's does, the Kind still maps to
514 # that other version rather than vanishing.
515 140 ▶ my @order = @{$gdata->{version_order} // []};
Condition100%2/2
$gdata->{"version_order"} // []
l!l
1391
MC/DC100%1/1
$gdata->{"version_order"} // []
$gdata->{"version_order"}
Truth table100%2/2
A
A= $gdata->{"version_order"}
Aresult
11
00
516 140 my $pref = $gdata->{preferred};
517 152 @order = ($pref, grep { $_ ne $pref } @order)
518 140 ▶ if defined $pref && grep { $_ eq $pref } @order;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pref and grep {$_ eq $pref;} @order 139 1 140
Condition66%2/3
defined $pref and grep {$_ eq $pref;} @order
!ll&&!rl&&r
10139
MC/DC50%1/2
defined $pref and grep {$_ eq $pref;} @order
defined $pref grep {$_ eq $pref;} @order
Truth table66%2/3
A and B
A= defined $prefB= grep {$_ eq $pref;} @order
ABresult
0X0
100
111
519  
520 140 for my $version (@order) {
521 152 my $kinds = $gdata->{versions}{$version}{kinds};
522 152 for my $kind (keys %$kinds) {
523 180 ▶ next if $kind =~ /List$/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind =~ /List$/ 1 179 180
524 179 ▶ next if exists $map{$kind}; # a preferred/earlier version won it
Branch: 1 branch
BranchTrueFalseTotal
if exists $map{$kind} 7 172 179
525  
526 172 my $version_path = ucfirst($version);
527 172 my $new_path = $self->_io_k8s_namespace_for_group($group)
528 . "::${version_path}::${kind}";
529  
530 # D12/D13: only record a class name this distribution ships.
531 172 ▶ next unless $self->_io_k8s_class_ships($new_path);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_io_k8s_class_ships($new_path) 72 100 172
532  
533 100 $map{$kind} = $new_path;
534 }
535 }
536 }
537  
538 54 return \%map;
539 }
540  
541 # Process-wide cache for the D12/D13 "stop inventing" loadability probe: a
542 # relative class path is either shipped (a real IO::K8s class that loads) or it
543 # is not, and that never changes within a run. Keyed by the relative path, so
544 # it is shared across instances.
545 63 my %_CLASS_SHIPS;
546  
547 # True when 'IO::K8s::<rel_path>' is a real, loadable class. The discovery map
548 # is built from group/version/Kind triples off the wire; without this probe
549 # every foreign CRD group would map to an IO::K8s::Api::<Group>::... name that
550 # has no class behind it (design D12). require the candidate once -- already
551 # loaded classes short-circuit on ->can('new') -- and remember the answer.
552 172 ▶sub _io_k8s_class_ships {
Subroutine _io_k8s_class_ships: called CC=4 SCAR=13.9
553 172 my ($self, $rel_path) = @_;
554 172 ▶ return $_CLASS_SHIPS{$rel_path} //= do {
Condition100%3/3
$_CLASS_SHIPS{$rel_path} //= do {
l!l&&r!l&&!r
1213120
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
555 51 my $full = "IO::K8s::$rel_path";
556 51 ▶ ($full->can('new') || eval { require_module($full); 1 }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$full->can('new') || eval { do { &require_module($full); 1 } } ? : 31 20 51
Condition100%3/3
$full->can("new") or eval {
l!l&&r!l&&!r
62520
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
557 };
558 }
559  
560 # Per-instance discovery catalog, keyed by group. Shape:
561 # { groups => { <group> => {
562 # preferred => <version>, # first version the cluster serves
563 # version_order => [ <version>, ... ], # discovery order, preferred first
564 # versions => { <version> => { kinds => {
565 # <Kind> => { resource => <plural>, scope => 'Namespaced'|'Cluster' },
566 # } } },
567 # } } }
568 # Built lazily on first use - or handed over by absorb_discovery - and
569 # invalidated by invalidate_discovery.
570 has _discovery => (
571 is => 'lazy',
572 predicate => '_has_discovery',
573 clearer => '_clear_discovery',
574 writer => '_set_discovery', # absorb_discovery
575 54 ▶ builder => sub { $_[0]->_fetch_discovery },
Subroutine _build__discovery: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
576 63 );
577  
578 # The reason the last discovery fetch attempted from _discovery_path_meta
579 # failed - its $@, for an HTTP error status an APIError (karr k59), rendered
580 # with _error_reason - kept so the croak in _build_path can name it: a
581 # failed fetch and a healthy catalog without the Kind both come back from
582 # _discovery_path_meta as undef (fail-closed, D16), and only this tells them
583 # apart. Cleared by the next successful fetch and by invalidate_discovery.
584 63 has _discovery_error => (
585 is => 'rw',
586 clearer => '_clear_discovery_error',
587 );
588  
589 # Aggregated discovery v2 (Kubernetes >= 1.27): GET /api and GET /apis with an
590 # Accept header selecting APIGroupDiscoveryList answer every group, version,
591 # resource plural, Kind and scope in one small response each. A server that does
592 # not understand the header ignores the as= parameter and returns the legacy
593 # document (APIVersions / APIGroupList) - detected by the kind - and the
594 # per-group APIResourceList fallback fills the catalog instead.
595 63 my $DISCOVERY_ACCEPT =
596 'application/json;g=apidiscovery.k8s.io;v=v2;as=APIGroupDiscoveryList';
597  
598 # The two discovery documents, in the order they are read.
599 63 my @DISCOVERY_ROOTS = ('/api', '/apis');
600  
601 76 ▶sub _fetch_discovery {
Subroutine _fetch_discovery: called CC=4 SCAR=13.9
602 76 my ($self) = @_;
603  
604 76 my $catalog = { groups => {} };
605  
606 76 for my $root (@DISCOVERY_ROOTS) {
607 129 my ($body, $aggregated) = $self->_discovery_document($root,
608 $self->io->call($self->_discovery_request($root)));
609  
610 106 ▶ if ($aggregated) {
Branch: 2 branches
BranchTrueFalseTotal
if ($aggregated) { } 98 8 106
elsif ($root eq '/api') { } 4 4 8
611 98 $self->_absorb_discovery_list($catalog, $body);
612 } elsif ($root eq '/api') {
613 4 $self->_fetch_discovery_legacy_core($catalog, $body);
614 } else {
615 4 $self->_fetch_discovery_legacy_groups($catalog, $body);
616 }
617 }
618  
619 53 return $catalog;
620 }
621  
622 # The request for one discovery root: what _fetch_discovery sends, and what
623 # prepare_discovery_requests hands an async client to send.
624 131 ▶sub _discovery_request {
Subroutine _discovery_request: called CC=1 SCAR=0.0
625 131 my ($self, $root) = @_;
626 131 return $self->_prepare_request('GET', $root,
627 headers => { Accept => $DISCOVERY_ACCEPT });
628 }
629  
630 # One discovery root's response, checked and decoded - for the synchronous
631 # fetch and absorb_discovery alike. An HTTP error dies as an APIError like
632 # any other checked response, carrying the body that says why (karr k59);
633 # the second value says whether the document is aggregated discovery
634 # (APIGroupDiscoveryList) rather than the legacy one.
635 147 ▶sub _discovery_document {
Subroutine _discovery_document: called CC=3 SCAR=11.3
636 147 my ($self, $root, $response) = @_;
637 147 $self->_check_response($response, "discovery GET $root");
638 121 my $body = $self->_json->decode($response->content);
639 121 ▶ my $kind = ref $body eq 'HASH' ? ($body->{kind} // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $body eq 'HASH' ? : 121 0 121
Condition50%1/2
$body->{"kind"} // ""
l!l
1210
MC/DC0%0/1
$body->{"kind"} // ""
$body->{"kind"}
Truth table50%1/2
A
A= $body->{"kind"}
Aresult
11
00
640 121 return ($body, $kind eq 'APIGroupDiscoveryList');
641 }
642  
643 # APIGroupDiscoveryList (aggregated discovery v2). Each item is one group; the
644 # order of its versions is the cluster's preference, so the first is preferred.
645 106 ▶sub _absorb_discovery_list {
Subroutine _absorb_discovery_list: called CC=15 SCAR=29.5
646 106 my ($self, $catalog, $body) = @_;
647  
648 106 ▶ for my $group_item (@{$body->{items} // []}) {
Condition50%1/2
$body->{"items"} // []
l!l
1060
MC/DC0%0/1
$body->{"items"} // []
$body->{"items"}
Truth table50%1/2
A
A= $body->{"items"}
Aresult
11
00
649 138 ▶ my $group = $group_item->{metadata}{name} // '';
Condition50%1/2
$group_item->{"metadata"}{"name"} // ""
l!l
1380
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
650 138 ▶ my @versions = @{$group_item->{versions} // []};
Condition50%1/2
$group_item->{"versions"} // []
l!l
1380
MC/DC0%0/1
$group_item->{"versions"} // []
$group_item->{"versions"}
Truth table50%1/2
A
A= $group_item->{"versions"}
Aresult
11
00
651 138 for my $i (0 .. $#versions) {
652 150 my $vd = $versions[$i];
653 150 my $version = $vd->{version};
654 150 ▶ next unless defined $version && length $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and length $version 0 150 150
Condition33%1/3
defined $version and length $version
!ll&&!rl&&r
00150
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
655 150 ▶ for my $res (@{$vd->{resources} // []}) {
Condition50%1/2
$vd->{"resources"} // []
l!l
1500
MC/DC0%0/1
$vd->{"resources"} // []
$vd->{"resources"}
Truth table50%1/2
A
A= $vd->{"resources"}
Aresult
11
00
656 178 my $plural = $res->{resource};
657 178 my $rkind = $res->{responseKind}{kind};
658 178 ▶ next unless defined $plural && defined $rkind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plural and defined $rkind 0 178 178
Condition33%1/3
defined $plural and defined $rkind
!ll&&!rl&&r
00178
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
659 $self->_catalog_add($catalog, $group, $version, $rkind,
660 178 ▶ $plural, $res->{scope} // '');
Condition50%1/2
$res->{"scope"} // ""
l!l
1780
MC/DC0%0/1
$res->{"scope"} // ""
$res->{"scope"}
Truth table50%1/2
A
A= $res->{"scope"}
Aresult
11
00
661 }
662 # First version served = preferred version for the group.
663 $catalog->{groups}{$group}{preferred} = $version
664 150 ▶ if $i == 0 && exists $catalog->{groups}{$group};
Branch: 1 branch
BranchTrueFalseTotal
if $i == 0 and exists $catalog->{"groups"}{$group} 137 13 150
Condition100%3/3
$i == 0 and exists $catalog->{"groups"}{$group}
!ll&&!rl&&r
121137
MC/DC100%2/2
$i == 0 and exists $catalog->{"groups"}{$group}
$i == 0 exists $catalog->{"groups"}{$group}
Truth table100%3/3
A and B
A= $i == 0B= exists $catalog->{"groups"}{$group}
ABresult
0X0
100
111
665 }
666 }
667 }
668  
669 # Legacy fallback for GET /api: an APIVersions document. Each version's
670 # APIResourceList is fetched from /api/<version>.
671 4 ▶sub _fetch_discovery_legacy_core {
Subroutine _fetch_discovery_legacy_core: called CC=6 SCAR=18.0
672 4 my ($self, $catalog, $body) = @_;
673  
674 4 ▶ my @versions = @{$body->{versions} // []};
Condition50%1/2
$body->{"versions"} // []
l!l
40
MC/DC0%0/1
$body->{"versions"} // []
$body->{"versions"}
Truth table50%1/2
A
A= $body->{"versions"}
Aresult
11
00
675 4 for my $version (@versions) {
676 4 my $path = "/api/$version";
677 4 my $response = $self->_request('GET', $path);
678 4 ▶ next unless $self->_legacy_resource_list_ok($response, $version, $path);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_legacy_resource_list_ok($response, $version, $path) 1 3 4
679 3 my $list = $self->_json->decode($response->content);
680 3 $self->_absorb_api_resource_list($catalog, '', $version, $list);
681 }
682 $catalog->{groups}{''}{preferred} = $versions[0]
683 4 ▶ if @versions && exists $catalog->{groups}{''};
Branch: 1 branch
BranchTrueFalseTotal
if @versions and exists $catalog->{"groups"}{""} 3 1 4
Condition66%2/3
@versions and exists $catalog->{"groups"}{""}
!ll&&!rl&&r
013
MC/DC50%1/2
@versions and exists $catalog->{"groups"}{""}
@versions exists $catalog->{"groups"}{""}
Truth table66%2/3
A and B
A= @versionsB= exists $catalog->{"groups"}{""}
ABresult
0X0
100
111
684 }
685  
686 # Legacy fallback for GET /apis: an APIGroupList document. Each group/version's
687 # APIResourceList is fetched from /apis/<group>/<version>.
688 4 ▶sub _fetch_discovery_legacy_groups {
Subroutine _fetch_discovery_legacy_groups: called CC=12 SCAR=26.4
689 4 my ($self, $catalog, $body) = @_;
690  
691 4 ▶ for my $group (@{$body->{groups} // []}) {
Condition50%1/2
$body->{"groups"} // []
l!l
40
MC/DC0%0/1
$body->{"groups"} // []
$body->{"groups"}
Truth table50%1/2
A
A= $body->{"groups"}
Aresult
11
00
692 10 my $gname = $group->{name};
693 10 ▶ next unless defined $gname && length $gname;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gname and length $gname 0 10 10
Condition33%1/3
defined $gname and length $gname
!ll&&!rl&&r
0010
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
694 10 ▶ for my $v (@{$group->{versions} // []}) {
Condition50%1/2
$group->{"versions"} // []
l!l
100
MC/DC0%0/1
$group->{"versions"} // []
$group->{"versions"}
Truth table50%1/2
A
A= $group->{"versions"}
Aresult
11
00
695 10 my $version = $v->{version};
696 10 ▶ next unless defined $version && length $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version and length $version 0 10 10
Condition33%1/3
defined $version and length $version
!ll&&!rl&&r
0010
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
697 10 my $path = "/apis/$gname/$version";
698 10 my $response = $self->_request('GET', $path);
699 10 ▶ next unless $self->_legacy_resource_list_ok($response, "$gname/$version", $path);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_legacy_resource_list_ok($response, "$gname/$version", $path) 6 4 10
700 4 my $list = $self->_json->decode($response->content);
701 4 $self->_absorb_api_resource_list($catalog, $gname, $version, $list);
702 }
703 10 my $pref = $group->{preferredVersion}{version};
704 $catalog->{groups}{$gname}{preferred} = $pref
705 10 ▶ if defined $pref && exists $catalog->{groups}{$gname};
Branch: 1 branch
BranchTrueFalseTotal
if defined $pref and exists $catalog->{"groups"}{$gname} 4 6 10
Condition66%2/3
defined $pref and exists $catalog->{"groups"}{$gname}
!ll&&!rl&&r
064
MC/DC50%1/2
defined $pref and exists $catalog->{"groups"}{$gname}
defined $pref exists $catalog->{"groups"}{$gname}
Truth table66%2/3
A and B
A= defined $prefB= exists $catalog->{"groups"}{$gname}
ABresult
0X0
100
111
706 }
707 }
708  
709 # Whether the legacy APIResourceList response for one group/version
710 # ($api_version, fetched from $path) can be read into the catalog. An error
711 # status leaves that group/version's Kinds out of the catalog, and so out of
712 # the resource map: any other status than 404 warns, naming it and the reason
713 # the APIError gives, and the other groups are read on (karr k63). A 404 is
714 # silent - the group/version went away between the group list and this
715 # request.
716 14 ▶sub _legacy_resource_list_ok {
Subroutine _legacy_resource_list_ok: called CC=3 SCAR=11.0
717 14 my ($self, $response, $api_version, $path) = @_;
718 14 ▶ return 1 if $response->status < 400;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status < 400 7 7 14
719 7 ▶ return 0 if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 4 3 7
720 3 eval { $self->_check_response($response, "discovery GET $path") };
721 3 $self->_carp_past_builders("discovery: cannot read apiVersion '$api_version',"
722 . ' its Kinds are missing from the resource map: ' . $self->_error_reason($@));
723 3 return 0;
724 }
725  
726 # APIResourceList (legacy per-group discovery). Subresource entries carry a
727 # slash in their name (pods/status) and are skipped; scope comes from the
728 # namespaced boolean.
729 7 ▶sub _absorb_api_resource_list {
Subroutine _absorb_api_resource_list: called CC=8 SCAR=21.6
730 7 my ($self, $catalog, $group, $version, $list) = @_;
731  
732 7 ▶ for my $res (@{$list->{resources} // []}) {
Condition50%1/2
$list->{"resources"} // []
l!l
70
MC/DC0%0/1
$list->{"resources"} // []
$list->{"resources"}
Truth table50%1/2
A
A= $list->{"resources"}
Aresult
11
00
733 9 my $name = $res->{name};
734 9 ▶ next unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 9 9
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
009
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
735 9 ▶ next if $name =~ m{/};
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ m[/] 1 8 9
736 8 my $kind = $res->{kind};
737 8 ▶ next unless defined $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind 0 8 8
738 8 ▶ my $scope = $res->{namespaced} ? 'Namespaced' : 'Cluster';
Branch: 1 branch
BranchTrueFalseTotal
$res->{'namespaced'} ? : 7 1 8
739 8 $self->_catalog_add($catalog, $group, $version, $kind, $name, $scope);
740 }
741 }
742  
743 # Register one Kind (plural, scope) under a group/version in the catalog,
744 # tracking version discovery order.
745 186 ▶sub _catalog_add {
Subroutine _catalog_add: called CC=3 SCAR=11.0
746 186 my ($self, $catalog, $group, $version, $kind, $plural, $scope) = @_;
747  
748 186 ▶ my $gdata = $catalog->{groups}{$group} ||= {
Condition100%2/2
$catalog->{"groups"}{$group} ||= {"preferred", undef, "version_order", [], "versions", {}}
l!l
42144
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
749 preferred => undef, version_order => [], versions => {},
750 };
751 186 ▶ unless (exists $gdata->{versions}{$version}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $gdata->{"versions"}{$version}) 156 30 186
752 156 $gdata->{versions}{$version} = { kinds => {} };
753 156 push @{$gdata->{version_order}}, $version;
754 }
755 186 $gdata->{versions}{$version}{kinds}{$kind} = {
756 resource => $plural,
757 scope => $scope,
758 };
759 }
760  
761 8 ▶sub invalidate_discovery {
Subroutine invalidate_discovery: called CC=4 SCAR=13.9
Pod documented
762 8 my ($self) = @_;
763  
764  
765 8 $self->_clear_discovery;
766 8 $self->_clear_discovery_error;
767 # Only a map built from the catalog goes, and with it the inner IO::K8s
768 # that captured it at build time, so both are rebuilt on next use. A map
769 # passed to the constructor is the caller's: rebuilding it would drop
770 # their '+My::Class' entries (karr k52), as absorb_discovery knows too.
771 8 ▶ if ($self->_has_resource_map && $self->_resource_map_built) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_resource_map and $self->_resource_map_built) 3 5 8
Condition100%3/3
$self->_has_resource_map and $self->_resource_map_built
!ll&&!rl&&r
143
MC/DC100%2/2
$self->_has_resource_map and $self->_resource_map_built
$self->_has_resource_map $self->_resource_map_built
Truth table100%3/3
A and B
A= $self->_has_resource_mapB= $self->_resource_map_built
ABresult
0X0
100
111
772 3 $self->_clear_resource_map;
773 3 ▶ $self->_clear_k8s if $self->_has_k8s;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_k8s 2 1 3
774 }
775 8 return 1;
776 }
777  
778 1 ▶sub prepare_discovery_requests {
Subroutine prepare_discovery_requests: called CC=1 SCAR=0.0
Pod documented
779 1 my ($self) = @_;
780  
781  
782 1 return map { ($_ => $self->_discovery_request($_)) } @DISCOVERY_ROOTS;
783 }
784  
785 11 ▶sub absorb_discovery {
Subroutine absorb_discovery: called CC=9 SCAR=22.0
Pod documented
786 11 my ($self, %responses) = @_;
787  
788  
789 11 $self->_croak_unknown_args('absorb_discovery', \%responses, @DISCOVERY_ROOTS);
790 10 my @lists;
791 10 for my $root (@DISCOVERY_ROOTS) {
792 19 ▶ my $response = $responses{$root}
Branch: 1 branch
BranchTrueFalseTotal
my $response = $responses{$root} or croak("absorb_discovery requires the response for $root") 18 1 19
793 or croak "absorb_discovery requires the response for $root";
794 18 my ($body, $aggregated) = $self->_discovery_document($root, $response);
795 15 ▶ push @lists, $aggregated ? $body : undef;
Branch: 1 branch
BranchTrueFalseTotal
$aggregated ? : 13 2 15
796 }
797 # Legacy discovery needs a request per group/version on top, which only
798 # the synchronous path makes: nothing is cached, and the caller falls
799 # back to that path.
800 6 ▶ return if grep { !defined } @lists;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not defined $_;} @lists 2 4 6
801  
802 4 my $catalog = { groups => {} };
803 4 $self->_absorb_discovery_list($catalog, $_) for @lists;
804  
805 # What an earlier catalog built goes, so this one counts: a resource map
806 # built from it, and the inner IO::K8s holding that map. A map passed to
807 # the constructor stays - a caller's '+My::Class' entries must survive.
808 4 ▶ if ($self->_has_resource_map && $self->_resource_map_built) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_resource_map and $self->_resource_map_built) 1 3 4
Condition100%3/3
$self->_has_resource_map and $self->_resource_map_built
!ll&&!rl&&r
211
MC/DC100%2/2
$self->_has_resource_map and $self->_resource_map_built
$self->_has_resource_map $self->_resource_map_built
Truth table100%3/3
A and B
A= $self->_has_resource_mapB= $self->_resource_map_built
ABresult
0X0
100
111
809 1 $self->_clear_resource_map;
810 1 ▶ $self->_clear_k8s if $self->_has_k8s;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_k8s 1 0 1
811 }
812 4 $self->_clear_discovery_error;
813 4 $self->_set_discovery($catalog);
814 4 return 1;
815 }
816  
817 # The full OpenAPI spec from the cluster, once _fetch_openapi_spec has fetched
818 # it (cached). The only /openapi/v2 download in the client, paid for by
819 # schema_for/compare_schema and (once resolution needs it) AutoGen, never by
820 # construction.
821 63 has _openapi_spec => (
822 is => 'ro',
823 predicate => '_has_openapi_spec',
824 writer => '_set_openapi_spec',
825 );
826  
827 # Fetch /openapi/v2 and keep it. Not a lazy builder: an error status dies as
828 # an APIError like any other checked response, naming the caller's line (karr
829 # k55) - and a Moo-generated accessor between the caller and the check breaks
830 # Carp's trust chain, so from a builder it named a line in here. A failed
831 # fetch keeps nothing, and the next use fetches again.
832 20 ▶sub _fetch_openapi_spec {
Subroutine _fetch_openapi_spec: called CC=2 SCAR=6.9
833 20 my ($self) = @_;
834 20 my $response = $self->_request('GET', '/openapi/v2');
835 20 $self->_check_response($response, 'fetch OpenAPI spec');
836 16 my $spec = $self->_json->decode($response->content);
837 16 $self->_set_openapi_spec($spec);
838 # D12: the inner IO::K8s was built without a spec (so building it never
839 # forced this fetch). Now that the spec exists, drop the cached instance
840 # so its next build passes it through as openapi_spec for AutoGen -- the
841 # same rebuild-on-next-use pattern invalidate_discovery uses.
842 16 ▶ $self->_clear_k8s if $self->_has_k8s;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_has_k8s 3 13 16
843 16 return $spec;
844 }
845  
846 # Get schema definition for a specific type
847 # $kind can be: 'Pod', 'IO::K8s::Api::Core::V1::Pod', or OpenAPI name like 'io.k8s.api.core.v1.Pod'
848 30 ▶sub schema_for {
Subroutine schema_for: called CC=19 SCAR=29.7
Pod documented
849 30 my ($self, $kind) = @_;
850  
851  
852 30 ▶ my $spec = $self->_has_openapi_spec ? $self->_openapi_spec : $self->_fetch_openapi_spec;
Branch: 1 branch
BranchTrueFalseTotal
$self->_has_openapi_spec ? : 10 20 30
853 26 ▶ my $defs = $spec->{definitions} // {};
Condition50%1/2
$spec->{"definitions"} // {}
l!l
260
MC/DC0%0/1
$spec->{"definitions"} // {}
$spec->{"definitions"}
Truth table50%1/2
A
A= $spec->{"definitions"}
Aresult
11
00
854  
855 # If it's already an OpenAPI definition name
856 26 ▶ if (exists $defs->{$kind}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $defs->{$kind}) 7 19 26
857 7 return $defs->{$kind};
858 }
859  
860 # Convert class name to OpenAPI definition name. A name nothing resolves
861 # (expand_class answers undef for a qualified one) has no definition to
862 # look up: the same undef a missing definition gets, without turning undef
863 # into a definition name first (karr k47).
864 19 my $class = $self->expand_class($kind);
865 19 ▶ return unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 2 17 19
866 # IO::K8s::Api::Core::V1::Pod -> io.k8s.api.core.v1.Pod
867 17 my $def_name = $class;
868 17 $def_name =~ s/^IO::K8s:://;
869 17 $def_name =~ s/::/./g;
870 17 $def_name = 'io.k8s.' . $def_name;
871 # Lowercase all path components except the final type name
872 17 my @parts = split /\./, $def_name;
873 17 $parts[$_] = lc($parts[$_]) for 0 .. $#parts - 1;
874 17 $def_name = join '.', @parts;
875 17 ▶ return $defs->{$def_name} if exists $defs->{$def_name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $defs->{$def_name} 4 13 17
876  
877 # That holds for the IO::K8s::Api:: classes only. Upstream names
878 # apiextensions and apiregistration after their staging repositories
879 # (io.k8s.apiextensions-apiserver..., io.k8s.kube-aggregator...), a CRD's
880 # definition after its group (com.example.v1.Widget), and Unstructured or
881 # a '+My::Class' map onto nothing. Every Kind's definition carries
882 # x-kubernetes-group-version-kind, so the class's GVK finds it; no match
883 # stays undef (karr k54).
884 13 my ($api_version, $gvk_kind) = $self->_schema_gvk($class, $kind);
885 13 ▶ return unless defined $api_version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version 3 10 13
886 10 ▶ my ($group, $version) = $api_version =~ m{/}
Branch: 1 branch
BranchTrueFalseTotal
$api_version =~ m[/] ? : 10 0 10
887 ? split(m{/}, $api_version, 2)
888 : ('', $api_version);
889 10 for my $name (sort keys %$defs) {
890 my $gvks = ref $defs->{$name} eq 'HASH'
891 46 ▶ ? $defs->{$name}{'x-kubernetes-group-version-kind'} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $defs->{$name} eq 'HASH' ? : 46 0 46
892 46 ▶ next unless ref $gvks eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $gvks eq "ARRAY" 4 42 46
893 42 for my $gvk (grep { ref $_ eq 'HASH' } @$gvks) {
894 return $defs->{$name}
895 if ($gvk->{group} // '') eq $group
896 && ($gvk->{version} // '') eq $version
897 42 ▶ && ($gvk->{kind} // '') eq $gvk_kind;
Branch: 1 branch
BranchTrueFalseTotal
if ($gvk->{"group"} // "") eq $group and ($gvk->{"version"} // "") eq $version and ($gvk->{"kind"} // "") eq $gvk_kind 9 33 42
Condition75%9/12
($gvk->{"group"} // "") eq $group and ($gvk->{"version"} // "") eq $version and ($gvk->{"kind"} // "") eq $gvk_kind
!ll&&!rl&&r
2859
($gvk->{"group"} // "") eq $group and ($gvk->{"version"} // "") eq $version
!ll&&!rl&&r
23514
$gvk->{"group"} // ""
l!l
420
$gvk->{"version"} // ""
l!l
190
$gvk->{"kind"} // ""
l!l
140
MC/DC0%0/3
($gvk->{"group"} // "") eq $group and ($gvk->{"version"} // "") eq $version and ($gvk->{"kind"} // "") eq $gvk_kind
$gvk->{"group"} $gvk->{"version"} $gvk->{"kind"}
Truth table25%1/4
A and B and C
A= $gvk->{"group"}B= $gvk->{"version"}C= $gvk->{"kind"}
ABCresult
0XX0
10X0
1100
1111
898 }
899 }
900 1 return;
901 }
902  
903 # The apiVersion and Kind schema_for looks a definition up by, for $class as
904 # expand_class resolved $name: the class's own api_version() and kind(), or -
905 # for IO::K8s::Unstructured, whose class has neither - the Kind of the name
906 # and the apiVersion discovery confirmed for it, exactly as expand_class and
907 # _build_path read it (_discovery_path_meta). Empty when there is none.
908 13 ▶sub _schema_gvk {
Subroutine _schema_gvk: called CC=11 SCAR=25.7
909 13 my ($self, $class, $name) = @_;
910 13 ▶ if ($class eq 'IO::K8s::Unstructured') {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq "IO::K8s::Unstructured") 1 12 13
911 1 my ($kind, $api_version) = $self->_kind_from_expand_args($name);
912 1 ▶ return unless defined $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind 0 1 1
913 1 ▶ my $meta = $self->_discovery_path_meta($kind, $api_version) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $meta = $self->_discovery_path_meta($kind, $api_version) or return 1 0 1
914 1 return ($meta->{api_version}, $kind);
915 }
916 12 ▶ return unless eval { require_module($class); 1 } && $class->can('api_version');
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { &require_module($class); 1 } } and $class->can("api_version") 3 9 12
Condition66%2/3
eval { and $class->can("api_version")
!ll&&!rl&&r
309
MC/DC50%1/2
eval { do { &require_module($class); 1 } } and $class->can("api_version")
eval { do { &require_module($class); 1 } } $class->can("api_version")
Truth table66%2/3
A and B
A= eval { do { &require_module($class); 1 } }B= $class->can("api_version")
ABresult
0X0
100
111
917 # Asked as class methods, and only an answer without error counts - a
918 # class of your own may have them as instance attributes.
919 9 my $api_version = eval { $class->api_version };
920 9 ▶ return unless defined $api_version && length $api_version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version and length $api_version 0 9 9
Condition33%1/3
defined $api_version and length $api_version
!ll&&!rl&&r
009
MC/DC0%0/2
defined $api_version and length $api_version
defined $api_version length $api_version
Truth table33%1/3
A and B
A= defined $api_versionB= length $api_version
ABresult
0X0
100
111
921 9 ▶ my $kind = $class->can('kind') ? eval { $class->kind } : undef;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('kind') ? : 9 0 9
922 9 ▶ ($kind = $class) =~ s/.*::// unless defined $kind && length $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind and length $kind 0 9 9
Condition33%1/3
defined $kind and length $kind
!ll&&!rl&&r
009
MC/DC0%0/2
defined $kind and length $kind
defined $kind length $kind
Truth table33%1/3
A and B
A= defined $kindB= length $kind
ABresult
0X0
100
111
923 9 return ($api_version, $kind);
924 }
925  
926 # Compare local class against cluster schema
927 # Returns comparison result from IO::K8s::Role::Resource->compare_to_schema
928 7 ▶sub compare_schema {
Subroutine compare_schema: called CC=3 SCAR=11.0
Pod documented
929 7 my ($self, $kind) = @_;
930  
931  
932 7 my $class = $self->_expand_class_or_croak($kind);
933 # Unstructured declares only the envelope; held against a definition it
934 # would report every other field as missing locally, which says nothing
935 # about skew (karr k60). Before the /openapi/v2 download, which it would
936 # waste.
937 5 ▶ croak "compare_schema: '$kind' resolves to IO::K8s::Unstructured, which has"
Branch: 1 branch
BranchTrueFalseTotal
if $class eq "IO::K8s::Unstructured" 3 2 5
938 . " no local schema to compare (add a typed class for it to resource_map"
939 . " or with)"
940 if $class eq 'IO::K8s::Unstructured';
941 2 require_module($class);
942  
943 2 my $schema = $self->schema_for($kind);
944 1 ▶ croak "Schema not found for $kind" unless $schema;
Branch: 1 branch
BranchTrueFalseTotal
unless $schema 0 1 1
945  
946 1 return $class->compare_to_schema($schema);
947 }
948  
949 # Internal wrapper with fallback for lazy loading. It runs in the
950 # resource_map builder, most often reached through the k8s one: the warning
951 # goes through _carp_past_builders to name the caller's line, not the line of
952 # the k8s builder that asked for the map (karr k64).
953 47 ▶sub _load_resource_map_from_cluster {
Subroutine _load_resource_map_from_cluster: called CC=2 SCAR=6.9
954 47 my ($self) = @_;
955 47 my $map = eval { $self->fetch_resource_map };
956 47 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 12 35 47
957 12 $self->_carp_past_builders('Falling back to the built-in resource map: '
958 . $self->_error_reason($@));
959 12 return IO::K8s->default_resource_map;
960 }
961 35 return $map;
962 }
963  
964 # V0 API compatibility - returns group wrapper objects
965 #
966 # Called as a plain function, not a method: each accessor below shares its name
967 # with the group module it wraps, so once this package is loaded Perl resolves
968 # a bareword like Kubernetes::REST::Core->new(...) against the sub instead of
969 # the class and calls it as Kubernetes::REST::Core()->new(...) - with no
970 # invocant. Returning the class name in that case puts the ->new(...) back on
971 # the class the caller was aiming at.
972 107 ▶sub _v0_group {
Subroutine _v0_group: called CC=2 SCAR=6.9
973 107 my ($group, $self) = @_;
974 107 my $class = "Kubernetes::REST::$group";
975 107 require_module($class);
976 107 ▶ return $class unless defined $self;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self 17 90 107
977 90 return $class->new(api => $self);
978 }
979  
980 39 ▶sub Core { _v0_group('Core', @_) }
Subroutine Core: called CC=1 SCAR=0.0
Pod undocumented
981 6 ▶sub Apps { _v0_group('Apps', @_) }
Subroutine Apps: called CC=1 SCAR=0.0
Pod undocumented
982 4 ▶sub Batch { _v0_group('Batch', @_) }
Subroutine Batch: called CC=1 SCAR=0.0
Pod undocumented
983 4 ▶sub Networking { _v0_group('Networking', @_) }
Subroutine Networking: called CC=1 SCAR=0.0
Pod undocumented
984 4 ▶sub Storage { _v0_group('Storage', @_) }
Subroutine Storage: called CC=1 SCAR=0.0
Pod undocumented
985 4 ▶sub Policy { _v0_group('Policy', @_) }
Subroutine Policy: called CC=1 SCAR=0.0
Pod undocumented
986 4 ▶sub Autoscaling { _v0_group('Autoscaling', @_) }
Subroutine Autoscaling: called CC=1 SCAR=0.0
Pod undocumented
987 4 ▶sub RbacAuthorization { _v0_group('RbacAuthorization', @_) }
Subroutine RbacAuthorization: called CC=1 SCAR=0.0
Pod undocumented
988 4 ▶sub Certificates { _v0_group('Certificates', @_) }
Subroutine Certificates: called CC=1 SCAR=0.0
Pod undocumented
989 4 ▶sub Coordination { _v0_group('Coordination', @_) }
Subroutine Coordination: called CC=1 SCAR=0.0
Pod undocumented
990 4 ▶sub Events { _v0_group('Events', @_) }
Subroutine Events: called CC=1 SCAR=0.0
Pod undocumented
991 4 ▶sub Scheduling { _v0_group('Scheduling', @_) }
Subroutine Scheduling: called CC=1 SCAR=0.0
Pod undocumented
992 4 ▶sub Authentication { _v0_group('Authentication', @_) }
Subroutine Authentication: called CC=1 SCAR=0.0
Pod documented
993 4 ▶sub Authorization { _v0_group('Authorization', @_) }
Subroutine Authorization: called CC=1 SCAR=0.0
Pod undocumented
994 4 ▶sub Admissionregistration { _v0_group('Admissionregistration', @_) }
Subroutine Admissionregistration: called CC=1 SCAR=0.0
Pod undocumented
995 5 ▶sub Apiextensions { _v0_group('Apiextensions', @_) }
Subroutine Apiextensions: called CC=1 SCAR=0.0
Pod undocumented
996 5 ▶sub Apiregistration { _v0_group('Apiregistration', @_) }
Subroutine Apiregistration: called CC=1 SCAR=0.0
Pod undocumented
997  
998 # Build URL path from class metadata
999 395 ▶sub _build_path {
Subroutine _build_path: called CC=26 SCAR=34.6
1000 395 my ($self, $class, %args) = @_;
1001  
1002 395 require_module($class);
1003  
1004 # An Unstructured resolution (D16 rung 4) carries no api_version()/
1005 # resource_plural()/Namespaced role -- its Kind is data on the instance,
1006 # not a class identity -- so the path metadata comes from the discovery
1007 # catalog instead of the class. The caller (a CRUD method, or a seam
1008 # consumer) passes the Kind (and an object's own apiVersion) via
1009 # _unstructured_hint; api_version/resource/namespaced overrides are honoured
1010 # directly when given, which keeps build_path usable by async wrappers.
1011 395 my ($api_version, $resource, $is_namespaced);
1012 395 my ($kind_hint, $av_hint) = (delete $args{kind}, delete $args{api_version});
1013 395 my $override_resource = delete $args{resource};
1014 395 my $override_namespaced = delete $args{namespaced};
1015 395 ▶ if ($class eq 'IO::K8s::Unstructured') {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq 'IO::K8s::Unstructured') { } 44 351 395
1016 44 ▶ if (defined $override_resource && defined $override_namespaced
Branch: 1 branch
BranchTrueFalseTotal
if (defined $override_resource and defined $override_namespaced and defined $av_hint) { } 6 38 44
Condition83%5/6
defined $override_resource and defined $override_namespaced and defined $av_hint
!ll&&!rl&&r
3806
defined $override_resource and defined $override_namespaced
!ll&&!rl&&r
3716
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
1017 && defined $av_hint) {
1018 6 ($api_version, $resource, $is_namespaced) =
1019 ($av_hint, $override_resource, $override_namespaced);
1020 } else {
1021 38 ▶ 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')") 36 2 38
1022 or croak "IO::K8s::Unstructured needs a Kind to build a path"
1023 . " (pass kind => 'Kind')";
1024 36 my $meta = $self->_discovery_path_meta($kind_hint, $av_hint);
1025 36 ▶ unless ($meta) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($meta) 11 25 36
1026 # A failed fetch and a catalog without the Kind both come back
1027 # undef (fail-closed, see _discovery_path_meta); only the
1028 # recorded reason tells them apart, and a catalog that was
1029 # never read must not be reported as one lacking an entry. A
1030 # pinned apiVersion is named: the Kind may well be served in
1031 # another group or version, just not in this one (karr k43).
1032 11 my $reason = $self->_discovery_error;
1033 11 ▶ $reason = $self->_error_reason($reason) if defined $reason;
Branch: 1 branch
BranchTrueFalseTotal
if defined $reason 3 8 11
1034 11 ▶ my $gvk = "Kind '$kind_hint'"
Branch: 1 branch
BranchTrueFalseTotal
defined $av_hint && length $av_hint ? : 5 6 11
Condition66%2/3
defined $av_hint and length $av_hint
!ll&&!rl&&r
605
MC/DC50%1/2
defined $av_hint and length $av_hint
defined $av_hint length $av_hint
Truth table66%2/3
A and B
A= defined $av_hintB= length $av_hint
ABresult
0X0
100
111
1035 . (defined $av_hint && length $av_hint
1036 ? " in apiVersion '$av_hint'" : '');
1037 11 ▶ croak defined $reason
Branch: 1 branch
BranchTrueFalseTotal
defined $reason ? : 3 8 11
1038 ? "discovery failed, so $gvk is unconfirmed"
1039 . " - cannot build a path for IO::K8s::Unstructured:"
1040 . " $reason"
1041 : "no discovery entry for $gvk - cannot"
1042 . " build a path for IO::K8s::Unstructured";
1043 }
1044 ($api_version, $resource, $is_namespaced) =
1045 25 @{$meta}{qw(api_version resource namespaced)};
1046 }
1047 } else {
1048 # Get metadata from class
1049 351 ▶ $api_version = $class->can('api_version') ? $class->api_version : undef;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('api_version') ? : 351 0 351
1050 351 ▶ croak "Cannot determine api_version for $class - override api_version() in your CRD class"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version 0 351 351
1051 unless defined $api_version;
1052 351 ▶ my $kind = $class->can('kind') ? $class->kind : (split('::', $class))[-1];
Branch: 1 branch
BranchTrueFalseTotal
$class->can('kind') ? : 351 0 351
1053 351 $is_namespaced = $class->does('IO::K8s::Role::Namespaced');
1054  
1055 # Use explicit resource_plural if available, otherwise auto-pluralize
1056 351 ▶ if ($class->can('resource_plural') && $class->resource_plural) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class->can('resource_plural') and $class->resource_plural) { } 351 0 351
Condition33%1/3
$class->can("resource_plural") and $class->resource_plural
!ll&&!rl&&r
00351
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
1057 351 $resource = $class->resource_plural;
1058 } else {
1059 0 $resource = lc($kind);
1060 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
1061 0 $resource .= 'es'; # class -> classes, ingress -> ingresses
1062 } elsif ($resource =~ /[^aeiou]y$/) {
1063 0 $resource =~ s/y$/ies/; # policy -> policies
1064 } elsif ($resource !~ /s$/) {
1065 0 $resource .= 's'; # pod -> pods
1066 }
1067 }
1068 }
1069  
1070 # Build path based on API group
1071 382 my $path;
1072 382 ▶ if ($api_version =~ m{/}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($api_version =~ m[/]) { } 170 212 382
1073 # Has group: apps/v1 -> /apis/apps/v1/...
1074 170 $path = "/apis/$api_version";
1075 } else {
1076 # Core: v1 -> /api/v1/...
1077 212 $path = "/api/$api_version";
1078 }
1079  
1080 382 ▶ if ($is_namespaced && $args{namespace}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_namespaced and $args{"namespace"}) 304 78 382
Condition100%3/3
$is_namespaced and $args{"namespace"}
!ll&&!rl&&r
726304
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
1081 304 $path .= "/namespaces/$args{namespace}";
1082 }
1083  
1084 382 $path .= "/$resource";
1085  
1086 382 ▶ if ($args{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"name"}) 236 146 382
1087 236 $path .= "/$args{name}";
1088 }
1089  
1090 # Subresource suffix: /status, /log, /exec, /attach, /portforward.
1091 # Every subresource addresses one named resource - without a name the
1092 # suffix would silently land on the collection endpoint instead.
1093 382 ▶ if (defined $args{subresource} && length $args{subresource}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"subresource"} and length $args{"subresource"}) 64 318 382
Condition66%2/3
defined $args{"subresource"} and length $args{"subresource"}
!ll&&!rl&&r
318064
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
1094 croak "subresource '$args{subresource}' requires a name for $class"
1095 64 ▶ unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 63 64
1096 63 $path .= "/$args{subresource}";
1097 }
1098  
1099 381 return $path;
1100 }
1101  
1102 # ============================================================================
1103 # REQUEST / RESPONSE PIPELINE
1104 #
1105 # The API methods (list, get, create, etc.) are built on a 3-step pipeline:
1106 #
1107 # 1. _prepare_request - builds an HTTPRequest (method, url, headers, body)
1108 # 2. io->call - executes the request (pluggable: HTTP::Tiny, async, mock)
1109 # 3. _check_response / _inflate_object / _inflate_list - processes the response
1110 #
1111 # This separation allows different IO backends (sync, async, mock) to slot in
1112 # at step 2 without touching request preparation or response processing.
1113 # ============================================================================
1114  
1115 602 ▶sub _prepare_request {
Subroutine _prepare_request: called CC=15 SCAR=27.3
1116 602 my ($self, $method, $path, %opts) = @_;
1117  
1118 602 my $url = $self->server->endpoint . $path;
1119 602 ▶ my $content_type = $opts{content_type} // 'application/json';
Condition100%2/2
$opts{"content_type"} // "application/json"
l!l
30572
MC/DC100%1/1
$opts{"content_type"} // "application/json"
$opts{"content_type"}
Truth table100%2/2
A
A= $opts{"content_type"}
Aresult
11
00
1120 602 my $body = $opts{body};
1121 602 my $parameters = $opts{parameters};
1122 602 ▶ my $extra_headers = $opts{headers} // {};
Condition100%2/2
$opts{"headers"} // {}
l!l
143459
MC/DC100%1/1
$opts{"headers"} // {}
$opts{"headers"}
Truth table100%2/2
A
A= $opts{"headers"}
Aresult
11
00
1123  
1124 # Append query parameters to URL, keys and values through _query_escape
1125 602 ▶ if ($parameters && %$parameters) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parameters and %$parameters) 136 466 602
Condition100%3/3
$parameters and %$parameters
!ll&&!rl&&r
4642136
MC/DC100%2/2
$parameters and %$parameters
$parameters %$parameters
Truth table100%3/3
A and B
A= $parametersB= %$parameters
ABresult
0X0
100
111
1126 136 my @pairs;
1127 136 for my $key (sort keys %$parameters) {
1128 244 my $val = $parameters->{$key};
1129 244 ▶ next unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 244 244
1130 244 my $k = $self->_query_escape($key);
1131 244 ▶ if (ref($val) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'ARRAY') { } 10 234 244
1132 10 push @pairs, map { "$k=" . $self->_query_escape($_) } grep { defined } @$val;
1133 } else {
1134 234 push @pairs, "$k=" . $self->_query_escape($val);
1135 }
1136 }
1137 136 ▶ if (@pairs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pairs) 136 0 136
1138 136 ▶ $url .= ($url =~ /\?/ ? '&' : '?') . join('&', @pairs);
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /\?/ ? : 1 135 136
1139 }
1140 }
1141  
1142 602 my %headers = (
1143 'Content-Type' => $content_type,
1144 'Accept' => 'application/json',
1145 );
1146  
1147 # Only add Authorization header when a token is available
1148 # (client-certificate auth doesn't need a Bearer token)
1149 602 my $token = $self->credentials->token;
1150 602 ▶ if (defined $token && length $token) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $token and length $token) 601 1 602
Condition66%2/3
defined $token and length $token
!ll&&!rl&&r
01601
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
1151 601 $headers{'Authorization'} = 'Bearer ' . $token;
1152 }
1153 602 ▶ if ($extra_headers && ref($extra_headers) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($extra_headers and ref $extra_headers eq "HASH") 602 0 602
Condition33%1/3
$extra_headers and ref $extra_headers eq "HASH"
!ll&&!rl&&r
00602
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
1154 602 @headers{keys %$extra_headers} = values %$extra_headers;
1155 }
1156  
1157 602 ▶ return Kubernetes::REST::HTTPRequest->new(
Branch: 1 branch
BranchTrueFalseTotal
$body ? : 112 490 602
1158 method => $method,
1159 url => $url,
1160 headers => \%headers,
1161 ($body ? (content => $self->_json->encode($body)) : ()),
1162 );
1163 }
1164  
1165 # Percent-encode a query key or value - but only what would otherwise change
1166 # what the API server reads (karr k35). The server splits a query with Go's
1167 # net/url ParseQuery: into pairs at '&', dropping a pair that holds a ';'
1168 # whole, then key from value at the FIRST '=', reading '+' as a space and
1169 # '%XX' as a byte, and dropping a pair with a malformed '%'. A '#' ends the
1170 # URL before it is sent (URI and HTTP::Tiny take the rest for a fragment), and
1171 # a space, a control character or a non-ASCII byte has no place in a request
1172 # target. Those are encoded - characters as their UTF-8 bytes, the contract
1173 # the JSON body follows too. Everything else stays as it is, above all '=',
1174 # ',', '!', '/', '(', ')' and ':': the server reads them the same either way
1175 # (a value's '=' is past the first one), a selector stays readable in the URL,
1176 # and whoever compares the rendered query - this distribution's mock harness,
1177 # Net::Async::Kubernetes's - sees the string it always did. Keys go the same
1178 # way; they are the API's parameter names, none of which holds an '='.
1179 496 ▶sub _query_escape {
Subroutine _query_escape: called CC=1 SCAR=0.0
1180 496 my ($self, $string) = @_;
1181 496 my $bytes = Encode::encode('UTF-8', "$string");
1182 496 $bytes =~ s/([\x00-\x20\x7F-\xFF%&+#;])/sprintf('%%%02X', ord $1)/ge;
1183 496 return $bytes;
1184 }
1185  
1186 485 ▶sub _check_response {
Subroutine _check_response: called CC=3 SCAR=11.0
1187 485 my ($self, $response, $context) = @_;
1188 485 ▶ if ($response->status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->status >= 400) 71 414 485
1189 # Response bodies are bytes; the error message is read by humans, so
1190 # decode it (leniently - a truncated or non-UTF-8 body must not turn a
1191 # useful API error into an encoding croak).
1192 71 ▶ my $body = Encode::decode('UTF-8', $response->content // '', Encode::FB_DEFAULT);
Condition50%1/2
$response->content // ""
l!l
710
MC/DC0%0/1
$response->content // ""
$response->content
Truth table50%1/2
A
A= $response->content
Aresult
11
00
1193 # An object, so a caller can branch on the status instead of parsing
1194 # the text; it stringifies to the message this croaked with before,
1195 # at the same caller line (karr k50).
1196 71 Kubernetes::REST::APIError->throw(
1197 code => 0 + $response->status,
1198 body => $body,
1199 context => $context,
1200 response => $response,
1201 );
1202 }
1203 414 return $response;
1204 }
1205  
1206 # The name to hand IO::K8s's json_to_object()/struct_to_object() for $class.
1207 # Both resolve a name again, and a single-segment class of your own - '+Gizmo'
1208 # in the resource_map, which expand_class returns as 'Gizmo' - reads to them
1209 # as a Kind: IO::K8s::Gizmo, or whatever class the map gives the Kind Gizmo
1210 # (karr k42). A name that already is a loaded IO::K8s class, which is what
1211 # expand_class resolved and _build_path loaded, therefore goes over as
1212 # '+Class', which IO::K8s takes exactly. Any other name - a short or qualified
1213 # one a seam caller passed - is left for IO::K8s to resolve. The role check
1214 # keeps an unrelated package that merely shares a Kind's name from being
1215 # taken for the class.
1216 233 ▶sub _exact_class {
Subroutine _exact_class: called CC=7 SCAR=23.2
1217 233 my ($self, $class) = @_;
1218 233 ▶ return "+$class"
Branch: 1 branch
BranchTrueFalseTotal
if defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does") and $class->does("IO::K8s::Role::Resource") 230 3 233
Condition46%7/15
defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does") and $class->does("IO::K8s::Role::Resource")
!ll&&!rl&&r
30230
defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does")
!ll&&!rl&&r
03230
defined $class and not ref $class and length $class and not $class =~ /\A\+/
!ll&&!rl&&r
00233
defined $class and not ref $class and length $class
!ll&&!rl&&r
00233
defined $class and not ref $class
!ll&&!rl&&r
00233
MC/DC16%1/6
defined $class and not ref $class and length $class and not $class =~ /\A\+/ and $class->can("does") and $class->does("IO::K8s::Role::Resource")
defined $class not ref $class length $class not $class =~ /\A\+/ $class->can("does") $class->does("IO::K8s::Role::Resource")
Truth table28%2/7
A and not(B) and C and not(D) and E and F
A= defined $classB= not ref $classC= length $classD= not $class =~ /\A\+/E= $class->can("does")F= $class->does("IO::K8s::Role::Resource")
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
1219 if defined $class && !ref $class && length $class && $class !~ /\A\+/
1220 && $class->can('does') && $class->does('IO::K8s::Role::Resource');
1221 3 return $class;
1222 }
1223  
1224 156 ▶sub _inflate_object {
Subroutine _inflate_object: called CC=1 SCAR=0.0
1225 156 my ($self, $class, $response) = @_;
1226 156 return $self->k8s->json_to_object($self->_exact_class($class), $response->content);
1227 }
1228  
1229 63 ▶sub _inflate_list {
Subroutine _inflate_list: called CC=9 SCAR=22.5
1230 63 my ($self, $class, $response) = @_;
1231 63 my $struct = $self->_json->decode($response->content);
1232 63 ▶ my $items = $struct->{items} // [];
Condition50%1/2
$struct->{"items"} // []
l!l
630
MC/DC0%0/1
$struct->{"items"} // []
$struct->{"items"}
Truth table50%1/2
A
A= $struct->{"items"}
Aresult
11
00
1233 63 my $exact_class = $self->_exact_class($class);
1234 63 my (@objects, @dropped);
1235 63 for my $i (0 .. $#$items) {
1236 63 my $item = $items->[$i];
1237 63 my $obj = eval { $self->k8s->struct_to_object($exact_class, $item) };
1238 63 ▶ if (defined $obj) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $obj) 59 4 63
1239 59 push @objects, $obj;
1240 59 next;
1241 }
1242 # An item the object model rejects must not disappear without a
1243 # trace: the caller would read a cluster with N unreadable Pods as a
1244 # cluster with N fewer Pods (karr #16). Say which items were dropped
1245 # and why - typically the installed IO::K8s not knowing a field the
1246 # cluster version serves.
1247 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
1248 4 $err =~ s/\s+\z//;
1249 my $name = ref $item eq 'HASH' && ref $item->{metadata} eq 'HASH'
1250 ? $item->{metadata}{name}
1251 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
1252 4 ▶ push @dropped,
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 4 0 4
1253 "item $i" . (defined $name ? " (name '$name')" : '') . ": $err";
1254 }
1255 63 ▶ if (@dropped) {
Branch: 1 branch
BranchTrueFalseTotal
if (@dropped) 3 60 63
1256 3 carp sprintf
1257 "inflate_list: dropped %d of %d %s items - the returned list is"
1258 . " INCOMPLETE (often IO::K8s version drift against the cluster):\n %s",
1259 scalar @dropped, scalar @$items, $class, join("\n ", @dropped);
1260 }
1261 62 return IO::K8s::List->new(items => \@objects, item_class => $class);
1262 }
1263  
1264 14 ▶sub _process_watch_chunk {
Subroutine _process_watch_chunk: called CC=13 SCAR=26.0
1265 14 my ($self, $class, $buffer_ref, $chunk) = @_;
1266 14 $$buffer_ref .= $chunk;
1267  
1268 14 my $exact_class = $self->_exact_class($class);
1269 14 my @events;
1270 14 ▶ while ($$buffer_ref =~ s/^([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^([^\n]*)\n//) 14 14 28
1271 14 my $line = $1;
1272 14 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 0 14 14
1273  
1274 14 my $data = eval { $self->_json->decode($line) };
1275 14 ▶ next unless $data;
Branch: 1 branch
BranchTrueFalseTotal
unless $data 0 14 14
1276  
1277 14 ▶ my $type = $data->{type} // '';
Condition50%1/2
$data->{"type"} // ""
l!l
140
MC/DC0%0/1
$data->{"type"} // ""
$data->{"type"}
Truth table50%1/2
A
A= $data->{"type"}
Aresult
11
00
1278 14 ▶ my $raw_object = $data->{object} // {};
Condition50%1/2
$data->{"object"} // {}
l!l
140
MC/DC0%0/1
$data->{"object"} // {}
$data->{"object"}
Truth table50%1/2
A
A= $data->{"object"}
Aresult
11
00
1279  
1280 # Track resourceVersion for resumability
1281 14 my $rv;
1282 14 ▶ if ($raw_object->{metadata} && $raw_object->{metadata}{resourceVersion}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_object->{"metadata"} and $raw_object->{"metadata"}{"resourceVersion"}) 10 4 14
Condition100%3/3
$raw_object->{"metadata"} and $raw_object->{"metadata"}{"resourceVersion"}
!ll&&!rl&&r
1310
MC/DC100%2/2
$raw_object->{"metadata"} and $raw_object->{"metadata"}{"resourceVersion"}
$raw_object->{"metadata"} $raw_object->{"metadata"}{"resourceVersion"}
Truth table100%3/3
A and B
A= $raw_object->{"metadata"}B= $raw_object->{"metadata"}{"resourceVersion"}
ABresult
0X0
100
111
1283 10 $rv = $raw_object->{metadata}{resourceVersion};
1284 }
1285  
1286 # Inflate the object (ERROR events stay as hashrefs)
1287 14 my $object;
1288 14 ▶ if ($type eq 'ERROR') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'ERROR') { } 1 13 14
1289 1 $object = $raw_object;
1290 } else {
1291 13 ▶ $object = eval { $self->k8s->struct_to_object($exact_class, $raw_object) }
Condition33%1/3
eval { // $raw_object
l!l&&r!l&&!r
1300
MC/DC0%0/2
eval { do { $self->k8s->struct_to_object($exact_class, $raw_object) } } // $raw_object
eval { do { $self->k8s->struct_to_object($exact_class, $raw_object) } } $raw_object
Truth table33%1/3
A // B
A= eval { do { $self->k8s->struct_to_object($exact_class, $raw_object) } }B= $raw_object
ABresult
1X1
011
000
1292 // $raw_object;
1293 }
1294  
1295 push @events, {
1296 event => Kubernetes::REST::WatchEvent->new(
1297 type => $type,
1298 object => $object,
1299 raw => $raw_object,
1300 ),
1301 resourceVersion => $rv,
1302 is_error => ($type eq 'ERROR' ? 1 : 0),
1303 14 ▶ error_code => ($type eq 'ERROR' ? ($raw_object->{code} // 0) : 0),
Branch: 2 branches
BranchTrueFalseTotal
$type eq 'ERROR' ? : 1 13 14
$type eq 'ERROR' ? : 1 13 14
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
1304 };
1305 }
1306  
1307 14 return @events;
1308 }
1309  
1310 11 ▶sub _process_log_chunk {
Subroutine _process_log_chunk: called CC=2 SCAR=6.9
1311 11 my ($self, $buffer_ref, $chunk) = @_;
1312 11 $$buffer_ref .= $chunk;
1313  
1314 11 my @events;
1315 11 ▶ while ($$buffer_ref =~ s/^([^\n]*)\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$buffer_ref =~ s/^([^\n]*)\n//) 14 11 25
1316 14 my $line = $1;
1317 14 push @events, Kubernetes::REST::LogEvent->new(line => $line);
1318 }
1319  
1320 11 return @events;
1321 }
1322  
1323 # ============================================================================
1324 # PUBLIC BUILDING BLOCKS FOR ASYNC WRAPPERS
1325 #
1326 # These methods expose the internal request/response pipeline as a stable API
1327 # for async wrappers (e.g. Net::Async::Kubernetes) that need to build requests,
1328 # process responses, and handle streaming without going through the sync
1329 # convenience methods (list, get, watch, log, port_forward, exec, attach, etc.).
1330 # ============================================================================
1331  
1332 26 ▶sub build_path {
Subroutine build_path: called CC=1 SCAR=0.0
Pod documented
1333 26 my ($self, @args) = @_;
1334  
1335  
1336 26 return $self->_build_path(@args);
1337 }
1338  
1339 74 ▶sub prepare_request {
Subroutine prepare_request: called CC=1 SCAR=0.0
Pod documented
1340 74 my ($self, @args) = @_;
1341  
1342  
1343 74 return $self->_prepare_request(@args);
1344 }
1345  
1346 5 ▶sub check_response {
Subroutine check_response: called CC=1 SCAR=0.0
Pod documented
1347 5 my ($self, @args) = @_;
1348  
1349  
1350 5 return $self->_check_response(@args);
1351 }
1352  
1353 5 ▶sub inflate_object {
Subroutine inflate_object: called CC=1 SCAR=0.0
Pod documented
1354 5 my ($self, @args) = @_;
1355  
1356  
1357 5 return $self->_inflate_object(@args);
1358 }
1359  
1360 2 ▶sub inflate_list {
Subroutine inflate_list: called CC=1 SCAR=0.0
Pod documented
1361 2 my ($self, @args) = @_;
1362  
1363  
1364 2 return $self->_inflate_list(@args);
1365 }
1366  
1367 2 ▶sub process_watch_chunk {
Subroutine process_watch_chunk: called CC=1 SCAR=0.0
Pod documented
1368 2 my ($self, @args) = @_;
1369  
1370  
1371 2 return $self->_process_watch_chunk(@args);
1372 }
1373  
1374 6 ▶sub process_log_chunk {
Subroutine process_log_chunk: called CC=1 SCAR=0.0
Pod documented
1375 6 my ($self, @args) = @_;
1376  
1377  
1378 6 return $self->_process_log_chunk(@args);
1379 }
1380  
1381 # Convenience: prepare + call in one step (used by sync CRUD methods)
1382 369 ▶sub _request {
Subroutine _request: called CC=1 SCAR=0.0
1383 369 my ($self, $method, $path, $body, %opts) = @_;
1384 369 my $req = $self->_prepare_request($method, $path,
1385 body => $body,
1386 %opts,
1387 );
1388 369 return $self->io->call($req);
1389 }
1390  
1391 66 ▶sub list {
Subroutine list: called CC=1 SCAR=0.0
Pod documented
1392 66 my ($self, $short_class, %args) = @_;
1393  
1394  
1395 # A misspelt option is not ignored (karr k58): label_selector listed
1396 # unfiltered, namespce across the cluster. name and subresource are out
1397 # too: they made the request a GET of one object, read as an empty list.
1398 66 $self->_croak_unknown_args('list', \%args, qw(namespace labelSelector fieldSelector));
1399 58 my ($class, $response) = $self->_list_request($short_class, %args);
1400 49 $self->_check_response($response, "list $short_class");
1401  
1402 46 return $self->_inflate_list($class, $response);
1403 }
1404  
1405 # list() up to the response, unchecked: returns the resolved class and the raw
1406 # response. ensure_only() needs the status itself - a 404 there means the Kind
1407 # is not served, not a failure - and must not read it back out of the text
1408 # _check_response croaks with.
1409 81 ▶sub _list_request {
Subroutine _list_request: called CC=4 SCAR=13.9
1410 81 my ($self, $short_class, %args) = @_;
1411  
1412 # Extract query parameters before building path
1413 81 my $label_selector = delete $args{labelSelector};
1414 81 my $field_selector = delete $args{fieldSelector};
1415  
1416 81 my $class = $self->_expand_class_or_croak($short_class);
1417 68 my $path = $self->_build_path($class, %args,
1418 $self->_unstructured_hint($class, $short_class));
1419  
1420 68 my %params;
1421 68 ▶ $params{labelSelector} = $label_selector if defined $label_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $label_selector 21 47 68
1422 68 ▶ $params{fieldSelector} = $field_selector if defined $field_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $field_selector 2 66 68
1423  
1424 68 ▶ my $response = %params
Branch: 1 branch
BranchTrueFalseTotal
%params ? : 21 47 68
1425 ? $self->_request('GET', $path, undef, parameters => \%params)
1426 : $self->_request('GET', $path);
1427 68 return ($class, $response);
1428 }
1429  
1430 57 ▶sub get {
Subroutine get: called CC=6 SCAR=17.9
Pod documented
1431 57 my ($self, $short_class, @rest) = @_;
1432  
1433  
1434 # Support: get('Kind', 'name'), get('Kind', 'name', namespace => 'ns'),
1435 # get('Kind', name => 'name'), get('Kind', name => 'name', namespace => 'ns'),
1436 # each with subresource => ... as well
1437 57 my %args;
1438 57 ▶ if (@rest == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest == 1) { } 3 54 57
elsif (@rest >= 2 and not $rest[0] =~ /^(name|namespace|subresource)$/) { } 35 19 54
elsif (@rest % 2 == 0) { } 19 0 19
1439 3 $args{name} = $rest[0];
1440 ▶ } elsif (@rest >= 2 && $rest[0] !~ /^(name|namespace|subresource)$/) {
Condition100%3/3
@rest >= 2 and not $rest[0] =~ /^(name|namespace|subresource)$/
!ll&&!rl&&r
21735
MC/DC100%2/2
@rest >= 2 and not $rest[0] =~ /^(name|namespace|subresource)$/
@rest >= 2 not $rest[0] =~ /^(name|namespace|subresource)$/
Truth table100%3/3
A and not(B)
A= @rest >= 2B= not $rest[0] =~ /^(name|namespace|subresource)$/
ABresult
0X0
100
111
1441 # First arg is name, rest are key=value pairs
1442 35 $args{name} = shift @rest;
1443 35 %args = (%args, @rest);
1444 } elsif (@rest % 2 == 0) {
1445 19 %args = @rest;
1446 } else {
1447 0 croak "Invalid arguments to get()";
1448 }
1449 # A misspelt option is not ignored (karr k58). subresource is build_path's
1450 # and works: status answers with the object.
1451 57 $self->_croak_unknown_args('get', \%args, qw(name namespace subresource));
1452  
1453 53 my $class = $self->_expand_class_or_croak($short_class);
1454 44 ▶ croak "name required for get" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 2 42 44
1455  
1456 42 my $path = $self->_build_path($class, %args,
1457 $self->_unstructured_hint($class, $short_class));
1458 42 my $response = $self->_request('GET', $path);
1459 42 $self->_check_response($response, "get $short_class");
1460  
1461 32 return $self->_inflate_object($class, $response);
1462 }
1463  
1464 29 ▶sub create {
Subroutine create: called CC=1 SCAR=0.0
Pod documented
1465 29 my ($self, $object) = @_;
1466  
1467  
1468 29 my ($class, $response) = $self->_create_request($object);
1469 28 $self->_check_response($response, "create $class");
1470  
1471 25 return $self->_inflate_object($class, $response);
1472 }
1473  
1474 # create() up to the response, unchecked, for the same reason as
1475 # _list_request: ensure() takes a 409 as its cue that the object appeared
1476 # since its GET, and must read that off the status, not out of the text
1477 # _check_response croaks with (karr k44).
1478 57 ▶sub _create_request {
Subroutine _create_request: called CC=3 SCAR=11.8
1479 57 my ($self, $object) = @_;
1480  
1481 57 my $class = ref($object);
1482 57 ▶ my $namespace = $object->can('metadata') && $object->metadata
Branch: 1 branch
BranchTrueFalseTotal
$object->can('metadata') && $object->metadata ? : 57 0 57
Condition33%1/3
$object->can("metadata") and $object->metadata
!ll&&!rl&&r
0057
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
1483 ? $object->metadata->namespace
1484 : undef;
1485  
1486 57 my $path = $self->_build_path($class, namespace => $namespace,
1487 $self->_unstructured_hint($class, $object));
1488 56 return ($class, $self->_request('POST', $path, $object->TO_JSON));
1489 }
1490  
1491 8 ▶sub update {
Subroutine update: called CC=1 SCAR=0.0
Pod documented
1492 8 my ($self, $object) = @_;
1493  
1494  
1495 8 my ($class, $response) = $self->_update_request($object);
1496 7 $self->_check_response($response, "update $class");
1497  
1498 5 return $self->_inflate_object($class, $response);
1499 }
1500  
1501 # update() up to the response, unchecked, like _create_request: ensure()
1502 # re-fetches and retries on a 409 Conflict and must tell it apart by status.
1503 20 ▶sub _update_request {
Subroutine _update_request: called CC=3 SCAR=11.2
1504 20 my ($self, $object) = @_;
1505  
1506 20 my $class = ref($object);
1507 20 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 20 0 20
1508 20 ▶ 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") 20 0 20
1509 20 my $namespace = $metadata->namespace;
1510  
1511 20 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1512 $self->_unstructured_hint($class, $object));
1513 19 return ($class, $self->_request('PUT', $path, $object->TO_JSON));
1514 }
1515  
1516 63 my %PATCH_TYPES = (
1517 strategic => 'application/strategic-merge-patch+json',
1518 merge => 'application/merge-patch+json',
1519 json => 'application/json-patch+json',
1520 );
1521  
1522 # Shared argument unpacking for patch() and patch_status(): accepts either a
1523 # blessed object or a class plus name, in both the shorthand
1524 # (patch('Pod', 'name', ...)) and the fully keyed (patch('Pod', name => ...))
1525 # call form. $label only appears in croak messages, $default_type is the patch
1526 # strategy used when the caller does not pass one.
1527 #
1528 # Any argument it does not read croaks before anything is sent (karr k61): a
1529 # misspelt namespce patched the object of that name at cluster scope, a
1530 # patch_type => 'merge' went out as a strategic merge patch. An object names
1531 # itself, so with one only the patch and its type are taken.
1532 62 ▶sub _unpack_patch_args {
Subroutine _unpack_patch_args: called CC=15 SCAR=28.1
1533 62 my ($self, $label, $default_type, $class_or_object, @rest) = @_;
1534  
1535 62 my ($class, $name, $namespace, $patch, $patch_type);
1536  
1537 62 ▶ if (ref($class_or_object) && blessed($class_or_object)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_object and builtin::blessed($class_or_object)) { } 12 50 62
Condition66%2/3
ref $class_or_object and builtin::blessed($class_or_object)
!ll&&!rl&&r
50012
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
1538 # Object passed: patch($object, patch => {...})
1539 12 my $object = $class_or_object;
1540 12 my %args = @rest;
1541 12 $self->_croak_unknown_args($label, \%args, qw(patch type));
1542 4 $class = ref($object);
1543 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
1544 4 ▶ $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
$name = $metadata->name or croak("object must have metadata.name") 4 0 4
1545 4 $namespace = $metadata->namespace;
1546 4 ▶ $patch = $args{patch} // croak "$label requires 'patch' parameter";
Condition33%1/3
$args{"patch"} // croak("$label requires 'patch' parameter")
l!l&&r!l&&!r
400
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
1547 4 ▶ $patch_type = $args{type} // $default_type;
Condition66%2/3
$args{"type"} // $default_type
l!l&&r!l&&!r
130
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
1548 } else {
1549 # Class + name: patch('Pod', 'name', namespace => 'ns', patch => {...})
1550 50 my %args;
1551 50 ▶ 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)$/) { } 31 19 50
elsif (@rest % 2 == 0) { } 17 2 19
Condition50%3/6
@rest >= 1 and not ref $rest[0] and not $rest[0] =~ /^(name|namespace|patch|type)$/
!ll&&!rl&&r
01931
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
0050
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
1552 31 $args{name} = shift @rest;
1553 31 %args = (%args, @rest);
1554 } elsif (@rest % 2 == 0) {
1555 17 %args = @rest;
1556 } else {
1557 2 croak "Invalid arguments to $label()";
1558 }
1559 48 $self->_croak_unknown_args($label, \%args, qw(name namespace patch type));
1560  
1561 38 $class = $self->_expand_class_or_croak($class_or_object);
1562 34 ▶ $name = $args{name} or croak "name required for $label";
Branch: 1 branch
BranchTrueFalseTotal
$name = $args{"name"} or croak("name required for $label") 31 3 34
1563 31 $namespace = $args{namespace};
1564 31 ▶ $patch = $args{patch} // croak "$label requires 'patch' parameter";
Condition66%2/3
$args{"patch"} // croak("$label requires 'patch' parameter")
l!l&&r!l&&!r
2830
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
1565 28 ▶ $patch_type = $args{type} // $default_type;
Condition66%2/3
$args{"type"} // $default_type
l!l&&r!l&&!r
16120
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
1566 }
1567  
1568 32 ▶ 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
3020
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
1569 // croak "Unknown patch type '$patch_type' (use: strategic, merge, json)";
1570  
1571 30 return ($class, $name, $namespace, $patch, $content_type);
1572 }
1573  
1574 32 ▶sub patch {
Subroutine patch: called CC=1 SCAR=0.0
Pod documented
1575 32 my ($self, $class_or_object, @rest) = @_;
1576  
1577  
1578 32 my ($class, $name, $namespace, $patch, $content_type)
1579 = $self->_unpack_patch_args('patch', 'strategic', $class_or_object, @rest);
1580  
1581 15 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1582 $self->_unstructured_hint($class, $class_or_object));
1583 15 my $response = $self->_request('PATCH', $path, $patch,
1584 content_type => $content_type);
1585 15 $self->_check_response($response, "patch $class");
1586  
1587 14 return $self->_inflate_object($class, $response);
1588 }
1589  
1590 30 ▶sub patch_status {
Subroutine patch_status: called CC=1 SCAR=0.0
Pod documented
1591 30 my ($self, $class_or_object, @rest) = @_;
1592  
1593  
1594 30 my ($class, $name, $namespace, $patch, $content_type)
1595 = $self->_unpack_patch_args('patch_status', 'merge', $class_or_object, @rest);
1596  
1597 15 my $path = $self->_build_path($class,
1598 name => $name,
1599 namespace => $namespace,
1600 subresource => 'status',
1601 $self->_unstructured_hint($class, $class_or_object),
1602 );
1603 15 my $response = $self->_request('PATCH', $path, $patch,
1604 content_type => $content_type);
1605 15 $self->_check_response($response, "patch_status $class");
1606  
1607 14 return $self->_inflate_object($class, $response);
1608 }
1609  
1610 7 ▶sub update_status {
Subroutine update_status: called CC=3 SCAR=11.0
Pod documented
1611 7 my ($self, $object) = @_;
1612  
1613  
1614 7 my $class = ref($object);
1615 7 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 7 0 7
1616 7 ▶ 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") 6 1 7
1617 6 my $namespace = $metadata->namespace;
1618  
1619 6 my $path = $self->_build_path($class,
1620 name => $name,
1621 namespace => $namespace,
1622 subresource => 'status',
1623 $self->_unstructured_hint($class, $object),
1624 );
1625 6 my $response = $self->_request('PUT', $path, $object->TO_JSON);
1626 6 $self->_check_response($response, "update_status " . ref($object));
1627  
1628 5 return $self->_inflate_object($class, $response);
1629 }
1630  
1631 40 ▶sub delete {
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
1632 40 my ($self, $class_or_object, @rest) = @_;
1633  
1634  
1635 40 my ($class, $response) = $self->_delete_request($class_or_object, @rest);
1636 25 $self->_check_response($response, "delete $class");
1637  
1638 24 return 1;
1639 }
1640  
1641 # delete() up to the response, unchecked: returns the resolved class and the
1642 # raw response, for the same reason as _list_request - ensure_only() treats a
1643 # 404 (already gone) differently from a failure.
1644 #
1645 # propagationPolicy goes out as the query parameter the API server reads
1646 # DeleteOptions from. Any other argument croaks before anything is sent: a
1647 # misspelt propagationPolicy that was silently dropped would leave a Job's
1648 # Pods orphaned (karr k49).
1649 56 ▶sub _delete_request {
Subroutine _delete_request: called CC=11 SCAR=24.1
1650 56 my ($self, $class_or_object, @rest) = @_;
1651  
1652 56 my ($class, $name, $namespace, %args);
1653  
1654 56 ▶ if (ref($class_or_object)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_object) { } 25 31 56
1655 # Object passed: delete($object), delete($object, propagationPolicy => ...)
1656 25 my $object = $class_or_object;
1657 25 ▶ croak "Invalid arguments to delete()" if @rest % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rest % 2 0 25 25
1658 25 %args = @rest;
1659 25 $self->_croak_unknown_args('delete', \%args, 'propagationPolicy');
1660 23 $self->_propagation_policy_or_croak('delete', $args{propagationPolicy});
1661 23 $class = ref($object);
1662 23 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 23 0 23
1663 23 ▶ $name = $metadata->name or croak "object must have metadata.name";
Branch: 1 branch
BranchTrueFalseTotal
$name = $metadata->name or croak("object must have metadata.name") 23 0 23
1664 23 $namespace = $metadata->namespace;
1665 } else {
1666 # Support: delete('Kind', 'name'), delete('Kind', 'name', namespace => 'ns'),
1667 # delete('Kind', name => 'name'), delete('Kind', name => 'name', namespace => 'ns'),
1668 # each with propagationPolicy => ... as well
1669 31 ▶ if (@rest == 1) {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest == 1) { } 2 29 31
elsif (@rest >= 2 and not $rest[0] =~ /^(name|namespace|propagationPolicy)$/) { } 21 8 29
elsif (@rest % 2 == 0) { } 8 0 8
1670 2 $args{name} = $rest[0];
1671 ▶ } elsif (@rest >= 2 && $rest[0] !~ /^(name|namespace|propagationPolicy)$/) {
Condition100%3/3
@rest >= 2 and not $rest[0] =~ /^(name|namespace|propagationPolicy)$/
!ll&&!rl&&r
2621
MC/DC100%2/2
@rest >= 2 and not $rest[0] =~ /^(name|namespace|propagationPolicy)$/
@rest >= 2 not $rest[0] =~ /^(name|namespace|propagationPolicy)$/
Truth table100%3/3
A and not(B)
A= @rest >= 2B= not $rest[0] =~ /^(name|namespace|propagationPolicy)$/
ABresult
0X0
100
111
1672 # First arg is name, rest are key=value pairs
1673 21 $args{name} = shift @rest;
1674 21 %args = (%args, @rest);
1675 } elsif (@rest % 2 == 0) {
1676 8 %args = @rest;
1677 } else {
1678 0 croak "Invalid arguments to delete()";
1679 }
1680 31 $self->_croak_unknown_args('delete', \%args,
1681 qw(name namespace propagationPolicy));
1682 29 $self->_propagation_policy_or_croak('delete', $args{propagationPolicy});
1683  
1684 28 $class = $self->_expand_class_or_croak($class_or_object);
1685 21 ▶ $name = $args{name} or croak "name required for delete";
Branch: 1 branch
BranchTrueFalseTotal
$name = $args{"name"} or croak("name required for delete") 19 2 21
1686 19 $namespace = $args{namespace};
1687 }
1688  
1689 42 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1690 $self->_unstructured_hint($class, $class_or_object));
1691 41 my $policy = $args{propagationPolicy};
1692 41 ▶ return ($class, defined $policy
Branch: 1 branch
BranchTrueFalseTotal
defined $policy ? : 25 16 41
1693 ? $self->_request('DELETE', $path, undef,
1694 parameters => { propagationPolicy => $policy })
1695 : $self->_request('DELETE', $path));
1696 }
1697  
1698 # The propagationPolicy values DeleteOptions takes.
1699 63 my @PROPAGATION_POLICIES = qw(Background Foreground Orphan);
1700  
1701 # Croak unless $policy is undef (none given) or one of @PROPAGATION_POLICIES.
1702 # $label only appears in the message.
1703 75 ▶sub _propagation_policy_or_croak {
Subroutine _propagation_policy_or_croak: called CC=3 SCAR=11.0
1704 75 my ($self, $label, $policy) = @_;
1705 75 ▶ return $policy if !defined $policy || grep { $_ eq $policy } @PROPAGATION_POLICIES;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $policy or grep {$_ eq $policy;} @PROPAGATION_POLICIES 73 2 75
Condition100%3/3
not defined $policy or grep {$_ eq $policy;} @PROPAGATION_POLICIES
l!l&&r!l&&!r
26472
MC/DC100%2/2
not defined $policy or grep {$_ eq $policy;} @PROPAGATION_POLICIES
not defined $policy grep {$_ eq $policy;} @PROPAGATION_POLICIES
Truth table100%3/3
not(A) or B
A= not defined $policyB= grep {$_ eq $policy;} @PROPAGATION_POLICIES
ABresult
1X1
011
000
1706 2 croak "Unknown propagationPolicy '$policy' for $label() (use: "
1707 . join(', ', @PROPAGATION_POLICIES) . ")";
1708 }
1709  
1710 # Croak on the first key of %$args that is not in @allowed, naming it and
1711 # what is allowed, instead of ignoring it. $label only appears in the message.
1712 373 ▶sub _croak_unknown_args {
Subroutine _croak_unknown_args: called CC=2 SCAR=6.9
1713 373 my ($self, $label, $args, @allowed) = @_;
1714 373 my %allowed = map { $_ => 1 } @allowed;
1715 373 my ($unknown) = sort grep { !$allowed{$_} } keys %$args;
1716 373 ▶ return unless defined $unknown;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $unknown 307 66 373
1717 66 croak "Unknown argument '$unknown' to $label() (allowed: "
1718 . join(', ', @allowed) . ")";
1719 }
1720  
1721 # Shared hashref handling for ensure() and ensure_only(): turns a manifest into
1722 # a typed object. A manifest's apiVersion is authoritative - with one, the
1723 # class is resolved as that exact group/version/Kind, and an apiVersion no
1724 # class serves croaks instead of falling back to the version the bare Kind
1725 # happens to map to (HorizontalPodAutoscaler alone means autoscaling/v2, a
1726 # different endpoint and schema than an autoscaling/v1 manifest). Without an
1727 # apiVersion the bare Kind resolves as it always did, and a Kind nothing
1728 # resolves croaks naming it, as for every method taking a resource name -
1729 # not with the module loader's "Can't locate IO/K8s/<Kind>.pm" (karr k48).
1730 # Either way the class is resolved here, so it goes to struct_to_object with
1731 # its '+': IO::K8s takes it as that exact class instead of resolving the name
1732 # again (see _exact_class; the class need not be loaded yet, so this does not
1733 # ask it). $label only appears in croak messages.
1734 24 ▶sub _manifest_to_object {
Subroutine _manifest_to_object: called CC=5 SCAR=16.2
1735 24 my ($self, $label, $manifest) = @_;
1736 24 ▶ my $kind = $manifest->{kind} or croak "$label: hashref must have 'kind'";
Branch: 1 branch
BranchTrueFalseTotal
my $kind = $manifest->{"kind"} or croak("${label}: hashref must have 'kind'") 24 0 24
1737 24 my $api_version = $manifest->{apiVersion};
1738  
1739 24 ▶ return $self->k8s->struct_to_object('+' . $self->_expand_class_or_croak($kind), $manifest)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version and length $api_version 5 19 24
Condition66%2/3
defined $api_version and length $api_version
!ll&&!rl&&r
5019
MC/DC50%1/2
defined $api_version and length $api_version
defined $api_version length $api_version
Truth table66%2/3
A and B
A= defined $api_versionB= length $api_version
ABresult
0X0
100
111
1740 unless defined $api_version && length $api_version;
1741  
1742 19 ▶ my $class = $self->expand_class($kind, $api_version)
Condition100%3/3
$self->expand_class($kind, $api_version) // croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
l!l&&r!l&&!r
1621
MC/DC0%0/2
$self->expand_class($kind, $api_version) // croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
$self->expand_class($kind, $api_version) croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
Truth table33%1/3
A // B
A= $self->expand_class($kind, $api_version)B= croak("${label}: no IO::K8s class for apiVersion '${api_version}', kind '${kind}'" . ' (add it to resource_map if it is a CRD)')
ABresult
1X1
011
000
1743 // croak "$label: no IO::K8s class for apiVersion '$api_version', kind '$kind'"
1744 . " (add it to resource_map if it is a CRD)";
1745 16 return $self->k8s->struct_to_object("+$class", $manifest);
1746 }
1747  
1748 # The apiVersion and Kind an object is an instance of, for ensure() and
1749 # ensure_only() to tell resources apart by. A typed object answers from its
1750 # class (api_version(), kind()); IO::K8s::Unstructured from its instance data,
1751 # since its class name says nothing about what it holds. The last segment of a
1752 # class name is not enough on its own: a CRD is free to reuse a built-in Kind
1753 # name in its own group.
1754 85 ▶sub _api_version_and_kind {
Subroutine _api_version_and_kind: called CC=6 SCAR=19.0
1755 85 my ($self, $object) = @_;
1756 85 ▶ my $api_version = ref($object) eq 'IO::K8s::Unstructured' ? $object->apiVersion
Branch: 2 branches
BranchTrueFalseTotal
ref $object eq 'IO::K8s::Unstructured' ? : 11 74 85
$object->can('api_version') ? : 74 0 74
1757 : $object->can('api_version') ? $object->api_version
1758 : undef;
1759 85 ▶ my $kind = $object->can('kind') ? $object->kind : undef;
Branch: 1 branch
BranchTrueFalseTotal
$object->can('kind') ? : 85 0 85
1760 85 ▶ ($kind = ref $object) =~ s/.*::// unless defined $kind;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kind 0 85 85
1761 85 ▶ return ($api_version // '', $kind);
Condition50%1/2
$api_version // ""
l!l
850
MC/DC0%0/1
$api_version // ""
$api_version
Truth table50%1/2
A
A= $api_version
Aresult
11
00
1762 }
1763  
1764 51 ▶sub ensure {
Subroutine ensure: called CC=17 SCAR=28.4
Pod documented
1765 51 my ($self, $object, @extra) = @_;
1766  
1767  
1768 # Nothing after the object is read (karr k58): namespace => ... would not
1769 # move it, a second object would not be applied.
1770 51 ▶ croak 'Invalid arguments to ensure(): it takes one object or hashref'
Branch: 1 branch
BranchTrueFalseTotal
if @extra 2 49 51
1771 . ' (ensure_all takes several)'
1772 if @extra;
1773 49 ▶ $object = $self->_manifest_to_object('ensure', $object) if ref($object) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $object eq "HASH" 15 34 49
1774  
1775 45 my $class = ref($object);
1776 45 ▶ croak "ensure requires an IO::K8s object or hashref" unless blessed($object);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($object) 0 45 45
1777 45 my ($api_version, $kind) = $self->_api_version_and_kind($object);
1778 # The special cases below are the built-in core v1 PersistentVolumeClaim
1779 # and batch/v1 Job only. The apiVersion is compared exactly, not just its
1780 # group: the Job branch reads batch/v1's status fields and deletes what it
1781 # takes for a failed Job, so an apiVersion it was not written for falls
1782 # through to the plain update, where a mismatch fails loudly instead.
1783 45 ▶ my $is_pvc = $api_version eq 'v1' && $kind eq 'PersistentVolumeClaim';
Condition100%3/3
$api_version eq 'v1' && $kind eq 'PersistentVolumeClaim'
!ll&&!rl&&r
27162
MC/DC100%2/2
$api_version eq 'v1' && $kind eq 'PersistentVolumeClaim'
$api_version eq 'v1' $kind eq 'PersistentVolumeClaim'
Truth table100%3/3
A && B
A= $api_version eq 'v1'B= $kind eq 'PersistentVolumeClaim'
ABresult
0X0
100
111
1784 45 ▶ my $is_job = $api_version eq 'batch/v1' && $kind eq 'Job';
Condition66%2/3
$api_version eq 'batch/v1' && $kind eq 'Job'
!ll&&!rl&&r
3906
MC/DC50%1/2
$api_version eq 'batch/v1' && $kind eq 'Job'
$api_version eq 'batch/v1' $kind eq 'Job'
Truth table66%2/3
A && B
A= $api_version eq 'batch/v1'B= $kind eq 'Job'
ABresult
0X0
100
111
1785 45 ▶ my $metadata = $object->metadata or croak "object must have metadata";
Branch: 1 branch
BranchTrueFalseTotal
my $metadata = $object->metadata or croak("object must have metadata") 45 0 45
1786 45 ▶ 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") 45 0 45
1787 45 my $namespace = $metadata->namespace;
1788  
1789 45 my @unstructured_hint = $self->_unstructured_hint($class, $object);
1790 45 my $path = $self->_build_path($class, name => $name, namespace => $namespace,
1791 @unstructured_hint);
1792  
1793 # Every branch below is taken on the status of the response, never on the
1794 # text of an error: a 500 or 422 whose message merely contains "404" or
1795 # "409" is a failure, not a missing object or a conflict (karr k44).
1796 44 my $existing;
1797 44 my $response = $self->_request('GET', $path);
1798 44 ▶ unless ($response->status == 404) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->status == 404) 16 28 44
1799 16 $self->_check_response($response, "ensure get $kind/$name");
1800 15 $existing = $self->_inflate_object($class, $response);
1801 }
1802  
1803 43 ▶ unless ($existing) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($existing) 28 15 43
1804 28 (undef, $response) = $self->_create_request($object);
1805 28 ▶ unless ($response->status == 409) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->status == 409) 23 5 28
1806 23 $self->_check_response($response, "create $class");
1807 22 return $self->_inflate_object($class, $response);
1808 }
1809 # 409 AlreadyExists: it appeared between the GET and the POST. From
1810 # here on it is an existing object like any other, special cases
1811 # included - a Job must not get a PUT onto its immutable Pod template.
1812 5 $response = $self->_request('GET', $path);
1813 5 $self->_check_response($response, "ensure post-409 get $kind/$name");
1814 5 $existing = $self->_inflate_object($class, $response);
1815 }
1816  
1817 20 ▶ return $existing if $is_pvc;
Branch: 1 branch
BranchTrueFalseTotal
if $is_pvc 2 18 20
1818 18 ▶ if ($is_job) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_job) 6 12 18
1819 # Read from TO_JSON, not status(): an IO::K8s::Unstructured Job has
1820 # no status accessor, its status rides in the unknown-fields bag.
1821 6 ▶ my $status = $existing->TO_JSON->{status} || {};
Condition50%1/2
$existing->TO_JSON->{'status'} || {}
l!l
60
MC/DC0%0/1
$existing->TO_JSON->{'status'} || {}
$existing->TO_JSON->{'status'}
Truth table50%1/2
A
A= $existing->TO_JSON->{'status'}
Aresult
11
00
1822 6 ▶ return $existing if $status->{succeeded} || $status->{active};
Branch: 1 branch
BranchTrueFalseTotal
if $status->{"succeeded"} or $status->{"active"} 3 3 6
Condition100%3/3
$status->{"succeeded"} or $status->{"active"}
l!l&&r!l&&!r
213
MC/DC100%2/2
$status->{"succeeded"} or $status->{"active"}
$status->{"succeeded"} $status->{"active"}
Truth table100%3/3
A or B
A= $status->{"succeeded"}B= $status->{"active"}
ABresult
1X1
011
000
1823 # Background, or the failed Job's Pods would be orphaned - the API
1824 # default for a Job (karr k49) - and the old Job is gone at once, so
1825 # the create does not run into it.
1826 3 eval { $self->delete($existing, propagationPolicy => 'Background') };
1827 3 return $self->create($object);
1828 }
1829 12 $object->metadata->resourceVersion($existing->metadata->resourceVersion);
1830 12 (undef, $response) = $self->_update_request($object);
1831 12 ▶ unless ($response->status == 409) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->status == 409) 11 1 12
1832 11 $self->_check_response($response, "update $class");
1833 10 return $self->_inflate_object($class, $response);
1834 }
1835 # 409 Conflict: the resourceVersion moved on server-side. Re-fetch it and
1836 # retry once; a second conflict croaks.
1837 1 $response = $self->_request('GET', $path);
1838 1 $self->_check_response($response, "ensure refetch $kind/$name");
1839 1 $existing = $self->_inflate_object($class, $response);
1840 1 $object->metadata->resourceVersion($existing->metadata->resourceVersion);
1841 1 return $self->update($object);
1842 }
1843  
1844 20 ▶sub ensure_all {
Subroutine ensure_all: called CC=1 SCAR=0.0
Pod documented
1845 20 my ($self, @objects) = @_;
1846  
1847  
1848 20 return map { $self->ensure($_) } @objects;
1849 }
1850  
1851 26 ▶sub ensure_only {
Subroutine ensure_only: called CC=18 SCAR=28.9
Pod documented
1852 26 my ($self, %args) = @_;
1853  
1854  
1855 # A misspelt option is not ignored, before anything is applied: a
1856 # propagation_policy typo would prune with Background, a namespace typo
1857 # scan cluster scope only (karr k53).
1858 26 $self->_croak_unknown_args('ensure_only', \%args,
1859 qw(label objects kinds namespaces propagationPolicy));
1860 23 ▶ my $label = $args{label} or croak "ensure_only requires 'label'";
Branch: 1 branch
BranchTrueFalseTotal
my $label = $args{"label"} or croak("ensure_only requires 'label'") 23 0 23
1861 23 ▶ my @objects = @{$args{objects} || []};
Condition50%1/2
$args{'objects'} || []
l!l
230
MC/DC0%0/1
$args{'objects'} || []
$args{'objects'}
Truth table50%1/2
A
A= $args{'objects'}
Aresult
11
00
1862 23 ▶ my @kinds = @{$args{kinds} || []};
Condition50%1/2
$args{'kinds'} || []
l!l
230
MC/DC0%0/1
$args{'kinds'} || []
$args{'kinds'}
Truth table50%1/2
A
A= $args{'kinds'}
Aresult
11
00
1863 23 ▶ my @namespaces = @{$args{namespaces} || [undef]};
Condition100%2/2
$args{'namespaces'} || [undef]
l!l
212
MC/DC100%1/1
$args{'namespaces'} || [undef]
$args{'namespaces'}
Truth table100%2/2
A
A= $args{'namespaces'}
Aresult
11
00
1864 # Background by default, as kubectl delete does: a pruned Job would
1865 # otherwise orphan its Pods (karr k49). Checked before anything is applied.
1866 my $propagation = $self->_propagation_policy_or_croak('ensure_only',
1867 23 ▶ $args{propagationPolicy} // 'Background');
Condition100%2/2
$args{"propagationPolicy"} // "Background"
l!l
221
MC/DC100%1/1
$args{"propagationPolicy"} // "Background"
$args{"propagationPolicy"}
Truth table100%2/2
A
A= $args{"propagationPolicy"}
Aresult
11
00
1868  
1869 22 for my $obj (@objects) {
1870 19 ▶ $obj = $self->_manifest_to_object('ensure_only', $obj) if ref($obj) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $obj eq "HASH" 9 10 19
1871 }
1872  
1873 19 my @results = $self->ensure_all(@objects);
1874  
1875 # (group, Kind, namespace, name), taken from the object on both sides -
1876 # never from the kinds entry, which may be qualified ('autoscaling/v1/...')
1877 # and would then match nothing, deleting the objects just applied. Group
1878 # and Kind come from _api_version_and_kind: class-derived for a typed
1879 # object, instance data for IO::K8s::Unstructured. The group keeps the same
1880 # Kind name in two groups apart (Istio's and the Gateway API's Gateway);
1881 # the core group is ''. No version in the key: the same resource listed
1882 # through another version's class is still the same resource.
1883 39 ▶ my $key_of = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1884 39 my ($obj) = @_;
1885 39 my ($api_version, $kind) = $self->_api_version_and_kind($obj);
1886 39 my ($group) = $api_version =~ m{\A(.*)/[^/]*\z};
1887 39 my $metadata = $obj->metadata;
1888 39 ▶ return join("\0", $group // '', $kind, $metadata->namespace // '', $metadata->name);
Condition75%3/4
$group // ""
l!l
1920
$metadata->namespace // ""
l!l
390
MC/DC100%1/1
$group // ""
$group
MC/DC0%0/1
$metadata->namespace // ""
$metadata->namespace
Truth table100%2/2
A
A= $group
Aresult
11
00
Truth table50%1/2
A
A= $metadata->namespace
Aresult
11
00
1889 19 };
1890 19 my %expected = map { $key_of->($_) => 1 } @objects;
1891  
1892 # A failed list or delete leaves stale objects behind, so it is reported
1893 # rather than swallowed - but only a real failure: a 404 on the list means
1894 # the cluster does not serve the Kind, a 404 on the delete that the object
1895 # is already gone. The status comes from the response, never from the text
1896 # of an error. The caught croak already names the caller's line, which
1897 # carp adds again, so the reason drops it.
1898 8 ▶ my $where = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1899 8 my ($ns) = @_;
1900 8 ▶ return defined $ns ? "in namespace '$ns'" : 'at cluster scope';
Branch: 1 branch
BranchTrueFalseTotal
defined $ns ? : 7 1 8
1901 19 };
1902 8 ▶ my $reason_of = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1903 8 my ($error) = @_;
1904 8 $error =~ s/\s+\z//;
1905 8 $error =~ s/ at \S+ line \d+\.\z//;
1906 8 return $error;
1907 19 };
1908  
1909 19 for my $kind (@kinds) {
1910 22 for my $ns (@namespaces) {
1911 23 my %list_args = (labelSelector => $label);
1912 23 ▶ $list_args{namespace} = $ns if defined $ns;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ns 22 1 23
1913 23 my $list = eval {
1914 23 my ($class, $response) = $self->_list_request($kind, %list_args);
1915 19 ▶ return if $response->status == 404;
Branch: 1 branch
BranchTrueFalseTotal
if $response->status == 404 1 18 19
1916 18 $self->_check_response($response, "list $kind");
1917 15 $self->_inflate_list($class, $response);
1918 };
1919 23 ▶ unless ($list) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($list) 8 15 23
1920 8 ▶ carp "ensure_only: cannot list $kind " . $where->($ns)
Branch: 1 branch
BranchTrueFalseTotal
if $@ 7 1 8
1921 . ', nothing pruned there: ' . $reason_of->($@)
1922 if $@;
1923 7 next;
1924 }
1925 15 for my $item (@{$list->items}) {
1926 26 ▶ next if $expected{ $key_of->($item) };
Branch: 1 branch
BranchTrueFalseTotal
if $expected{&$key_of($item)} 10 16 26
1927 16 ▶ next if eval {
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { () = $self->_delete_request($item, "propagationPolicy", $propagation); $response->status == 404 or $self->_check_response($response, "delete $class") } } 15 1 16
1928 16 my ($class, $response) = $self->_delete_request($item,
1929 propagationPolicy => $propagation);
1930 16 ▶ $response->status == 404
Condition66%2/3
$response->status == 404 || $self->_check_response($response, "delete $class")
l!l&&r!l&&!r
1150
MC/DC0%0/2
$response->status == 404 || $self->_check_response($response, "delete $class")
$response->status == 404 $self->_check_response($response, "delete $class")
Truth table66%2/3
A || B
A= $response->status == 404B= $self->_check_response($response, "delete $class")
ABresult
1X1
011
000
1931 || $self->_check_response($response, "delete $class");
1932 };
1933 1 my (undef, $item_kind) = $self->_api_version_and_kind($item);
1934 1 carp "ensure_only: cannot delete $item_kind '" . $item->metadata->name
1935 . "' " . $where->($item->metadata->namespace)
1936 . ': ' . $reason_of->($@);
1937 }
1938 }
1939 }
1940  
1941 18 return @results;
1942 }
1943  
1944 12 ▶sub ensure_crd {
Subroutine ensure_crd: called CC=13 SCAR=25.7
Pod documented
1945 12 my $self = shift;
1946  
1947  
1948 12 my (@classes, %opts);
1949 12 ▶ if (@_ && ref $_[0] eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[0] eq 'ARRAY') { } 8 4 12
Condition100%3/3
@_ and ref $_[0] eq "ARRAY"
!ll&&!rl&&r
138
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
1950 8 @classes = @{ shift() };
1951 8 %opts = @_;
1952 } else {
1953 4 @classes = @_;
1954 }
1955 # A misspelt option is not ignored, before any class is asked for its CRD
1956 # (karr k61): tiemout => 5 waited the default 30 seconds.
1957 12 $self->_croak_unknown_args('ensure_crd', \%opts, qw(timeout poll_interval storage));
1958 8 ▶ croak "ensure_crd requires at least one CRD class" unless @classes;
Branch: 1 branch
BranchTrueFalseTotal
unless @classes 1 7 8
1959  
1960 7 my $storage = $opts{storage};
1961  
1962 # Group the classes by the CRD they name (metadata.name = "$plural.$group"),
1963 # preserving first-seen order so the applied order is predictable.
1964 7 my (@order, %group);
1965 7 for my $class (@classes) {
1966 9 my $single = $class->to_crd;
1967 9 my $crd_name = $single->metadata->name;
1968 9 ▶ push @order, $crd_name unless exists $group{$crd_name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $group{$crd_name} 7 2 9
1969 9 push @{ $group{$crd_name} }, { class => $class, single => $single };
1970 }
1971  
1972 7 my @crds;
1973 7 for my $crd_name (@order) {
1974 7 my $members = $group{$crd_name};
1975 7 ▶ if (@$members == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$members == 1) 5 2 7
1976 5 push @crds, $members->[0]{single};
1977 5 next;
1978 }
1979 # Two or more classes are versions of the SAME CRD: assemble one
1980 # multi-version CRD rather than apply competing single-version ones.
1981 2 my @version_classes = map { $_->{class} } @$members;
1982 2 my @versions = map { $_->{single}->spec->versions->[0]->name } @$members;
1983 my $storage_version =
1984 !defined $storage ? undef
1985 2 ▶ : ref $storage eq 'HASH' ? $storage->{$crd_name}
Branch: 2 branches
BranchTrueFalseTotal
!defined($storage) ? : 1 1 2
ref $storage eq 'HASH' ? : 0 1 1
1986 : $storage;
1987 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
1988 . join(', ', @version_classes) . ") naming versions ("
1989 . join(', ', @versions) . "); pass storage => '<version>' (or "
1990 . "storage => { '$crd_name' => '<version>' }) to name the storage version"
1991 unless defined $storage_version && length $storage_version;
1992 1 push @crds,
1993 IO::K8s::CRD->new(classes => \@version_classes, storage => $storage_version);
1994 }
1995  
1996 # Apply every CRD first, then wait for each to establish (so establishment
1997 # happens in parallel), then invalidate discovery exactly once.
1998 6 $self->ensure($_) for @crds;
1999 6 my @established = map { $self->_wait_crd_established($_, %opts) } @crds;
2000 3 $self->invalidate_discovery;
2001 3 return @established;
2002 }
2003  
2004 # Poll GET on a CustomResourceDefinition by name until its Established condition
2005 # is True, or croak on timeout. A 404 during polling means "not registered yet"
2006 # and is treated as not-established, not an error. That is read off the status
2007 # of the response, never out of the text of an error: any other failure - a
2008 # 500 whose message merely contains "404" too - ends the wait with that error
2009 # instead of being polled away into a timeout (karr k45).
2010 6 ▶sub _wait_crd_established {
Subroutine _wait_crd_established: called CC=7 SCAR=19.5
2011 6 my ($self, $crd, %opts) = @_;
2012  
2013 6 my $class = ref $crd;
2014 6 my $name = $crd->metadata->name;
2015 6 my $path = $self->_build_path($class, name => $name);
2016 6 ▶ my $timeout = defined $opts{timeout} ? $opts{timeout} : 30;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'timeout'} ? : 4 2 6
2017 6 ▶ my $interval = defined $opts{poll_interval} ? $opts{poll_interval} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'poll_interval'} ? : 2 4 6
2018 6 my $deadline = Time::HiRes::time() + $timeout;
2019  
2020 6 while (1) {
2021 8 my $response = $self->_request('GET', $path);
2022 8 ▶ unless ($response->status == 404) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->status == 404) 4 4 8
2023 4 $self->_check_response($response, "ensure_crd wait $name");
2024 3 my $current = $self->_inflate_object($class, $response);
2025 3 ▶ return $current if $current && $self->_crd_established($current);
Branch: 1 branch
BranchTrueFalseTotal
if $current and $self->_crd_established($current) 3 0 3
Condition33%1/3
$current and $self->_crd_established($current)
!ll&&!rl&&r
003
MC/DC0%0/2
$current and $self->_crd_established($current)
$current $self->_crd_established($current)
Truth table33%1/3
A and B
A= $currentB= $self->_crd_established($current)
ABresult
0X0
100
111
2026 }
2027 4 ▶ last if Time::HiRes::time() >= $deadline;
Branch: 1 branch
BranchTrueFalseTotal
if &Time::HiRes::time() >= $deadline 2 2 4
2028 2 Time::HiRes::sleep($interval);
2029 }
2030  
2031 2 croak "ensure_crd: CustomResourceDefinition '$name' did not reach the "
2032 . "Established condition within ${timeout}s";
2033 }
2034  
2035 # True when a CustomResourceDefinition object carries an Established=True
2036 # condition in status.conditions.
2037 5 ▶sub _crd_established {
Subroutine _crd_established: called CC=8 SCAR=25.5
2038 5 my ($self, $crd) = @_;
2039 5 ▶ my $status = $crd->status or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $status = $crd->status or return 0 5 0 5
2040 5 ▶ my $conditions = $status->conditions or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $conditions = $status->conditions or return 0 5 0 5
2041 5 for my $cond (@$conditions) {
2042 5 ▶ return 1
Branch: 1 branch
BranchTrueFalseTotal
if ($cond->type // "") eq "Established" and ($cond->status // "") eq "True" 5 0 5
Condition42%3/7
($cond->type // "") eq "Established" and ($cond->status // "") eq "True"
!ll&&!rl&&r
005
$cond->type // ""
l!l
50
$cond->status // ""
l!l
50
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
2043 if ($cond->type // '') eq 'Established'
2044 && ($cond->status // '') eq 'True';
2045 }
2046 0 return 0;
2047 }
2048  
2049 19 ▶sub watch {
Subroutine watch: called CC=7 SCAR=19.5
Pod documented
2050 19 my ($self, $short_class, %args) = @_;
2051  
2052  
2053 # A misspelt option is not ignored (karr k58): timeoutSeconds ran for the
2054 # default 300. name is out too: it made the request a GET of one object,
2055 # which the server answers with the object, not a watch.
2056 19 $self->_croak_unknown_args('watch', \%args, qw(on_event timeout
2057 resourceVersion labelSelector fieldSelector namespace));
2058 my $on_event = delete $args{on_event}
2059 13 ▶ 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") 12 1 13
2060 12 ▶ my $timeout = delete $args{timeout} // 300;
Condition100%2/2
delete $args{"timeout"} // 300
l!l
39
MC/DC100%1/1
delete $args{"timeout"} // 300
delete $args{"timeout"}
Truth table100%2/2
A
A= delete $args{"timeout"}
Aresult
11
00
2061 12 my $resource_version = delete $args{resourceVersion};
2062 12 my $label_selector = delete $args{labelSelector};
2063 12 my $field_selector = delete $args{fieldSelector};
2064  
2065 12 my $class = $self->_expand_class_or_croak($short_class);
2066 10 my $path = $self->_build_path($class, %args,
2067 $self->_unstructured_hint($class, $short_class));
2068  
2069 10 my %params = (
2070 watch => 'true',
2071 timeoutSeconds => $timeout,
2072 );
2073 10 ▶ $params{resourceVersion} = $resource_version if defined $resource_version;
Branch: 1 branch
BranchTrueFalseTotal
if defined $resource_version 2 8 10
2074 10 ▶ $params{labelSelector} = $label_selector if defined $label_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $label_selector 3 7 10
2075 10 ▶ $params{fieldSelector} = $field_selector if defined $field_selector;
Branch: 1 branch
BranchTrueFalseTotal
if defined $field_selector 3 7 10
2076  
2077 10 my $req = $self->_prepare_request('GET', $path, parameters => \%params);
2078  
2079 10 my $buffer = '';
2080 10 my $last_rv = $resource_version;
2081 10 my $got_410 = 0;
2082  
2083 12 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2084 12 my ($chunk) = @_;
2085 12 for my $result ($self->_process_watch_chunk($class, \$buffer, $chunk)) {
2086 12 ▶ $last_rv = $result->{resourceVersion} if $result->{resourceVersion};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"resourceVersion"} 9 3 12
2087 12 ▶ $got_410 = 1 if $result->{error_code} == 410;
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"error_code"} == 410 1 11 12
2088 12 $on_event->($result->{event});
2089 }
2090 10 };
2091  
2092 10 my $response = $self->io->call_streaming($req, $data_callback);
2093  
2094 10 $self->_check_response($response, "watch $short_class");
2095  
2096 8 ▶ croak "Watch expired (410 Gone): resourceVersion too old, re-list to get a fresh resourceVersion"
Branch: 1 branch
BranchTrueFalseTotal
if $got_410 1 7 8
2097 if $got_410;
2098  
2099 7 return $last_rv;
2100 }
2101  
2102 23 ▶sub log {
Subroutine log: called CC=17 SCAR=28.5
Pod documented
2103 23 my ($self, $short_class, @rest) = @_;
2104  
2105  
2106 # Support: log('Pod', 'name', ...) and log('Pod', name => 'name', ...)
2107 23 my %args;
2108 23 ▶ 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)$/) { } 20 3 23
elsif (@rest % 2 == 0) { } 3 0 3
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
0320
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
0023
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
2109 20 $args{name} = shift @rest;
2110 20 %args = (%args, @rest);
2111 } elsif (@rest % 2 == 0) {
2112 3 %args = @rest;
2113 } else {
2114 0 croak "Invalid arguments to log()";
2115 }
2116 # A misspelt option is not ignored (karr k53): tail_lines => 10 would
2117 # fetch the whole log.
2118 23 $self->_croak_unknown_args('log', \%args, qw(name namespace container
2119 follow tailLines sinceSeconds sinceTime timestamps previous limitBytes
2120 on_line));
2121  
2122 20 ▶ croak "name required for log" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 19 20
2123  
2124 19 my $on_line = delete $args{on_line};
2125 19 my $container = delete $args{container};
2126 19 my $follow = delete $args{follow};
2127 19 my $tail_lines = delete $args{tailLines};
2128 19 my $since_seconds = delete $args{sinceSeconds};
2129 19 my $since_time = delete $args{sinceTime};
2130 19 my $timestamps = delete $args{timestamps};
2131 19 my $previous = delete $args{previous};
2132 19 my $limit_bytes = delete $args{limitBytes};
2133  
2134 19 my $class = $self->_expand_class_or_croak($short_class);
2135 17 my $path = $self->_build_path($class, %args, subresource => 'log',
2136 $self->_unstructured_hint($class, $short_class));
2137  
2138 17 my %params;
2139 17 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 2 15 17
2140 17 ▶ $params{follow} = 'true' if $follow;
Branch: 1 branch
BranchTrueFalseTotal
if $follow 1 16 17
2141 17 ▶ $params{tailLines} = $tail_lines if defined $tail_lines;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tail_lines 2 15 17
2142 17 ▶ $params{sinceSeconds} = $since_seconds if defined $since_seconds;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since_seconds 2 15 17
2143 17 ▶ $params{sinceTime} = $since_time if defined $since_time;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since_time 1 16 17
2144 17 ▶ $params{timestamps} = 'true' if $timestamps;
Branch: 1 branch
BranchTrueFalseTotal
if $timestamps 2 15 17
2145 17 ▶ $params{previous} = 'true' if $previous;
Branch: 1 branch
BranchTrueFalseTotal
if $previous 2 15 17
2146 17 ▶ $params{limitBytes} = $limit_bytes if defined $limit_bytes;
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit_bytes 2 15 17
2147  
2148 17 ▶ if ($on_line) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_line) { } 4 13 17
2149 # Streaming mode
2150 4 my $req = $self->_prepare_request('GET', $path, parameters => \%params);
2151  
2152 4 my $buffer = '';
2153 5 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2154 5 my ($chunk) = @_;
2155 5 for my $event ($self->_process_log_chunk(\$buffer, $chunk)) {
2156 5 $on_line->($event);
2157 }
2158 4 };
2159  
2160 4 my $response = $self->io->call_streaming($req, $data_callback);
2161 4 $self->_check_response($response, "log $short_class");
2162  
2163 # Process any remaining data in buffer (last line without trailing newline)
2164 4 ▶ if (length $buffer) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $buffer) 0 4 4
2165 0 $on_line->(Kubernetes::REST::LogEvent->new(line => $buffer));
2166 }
2167  
2168 4 return;
2169 } else {
2170 # One-shot mode
2171 13 ▶ my $response = $self->_request('GET', $path, undef,
Branch: 1 branch
BranchTrueFalseTotal
%params ? : 7 6 13
2172 %params ? (parameters => \%params) : (),
2173 );
2174 13 $self->_check_response($response, "log $short_class");
2175  
2176 12 return $response->content;
2177 }
2178 }
2179  
2180 15 ▶sub port_forward {
Subroutine port_forward: called CC=16 SCAR=28.1
Pod documented
2181 15 my ($self, $short_class, @rest) = @_;
2182  
2183  
2184 15 my %args;
2185 15 ▶ 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)$/) { } 13 2 15
elsif (@rest % 2 == 0) { } 2 0 2
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
0213
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
0015
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
2186 13 $args{name} = shift @rest;
2187 13 %args = (%args, @rest);
2188 } elsif (@rest % 2 == 0) {
2189 2 %args = @rest;
2190 } else {
2191 0 croak "Invalid arguments to port_forward()";
2192 }
2193 # A misspelt option is not ignored (karr k61): whatever was not read went
2194 # on to build_path, which dropped it - on_message never saw a frame.
2195 15 $self->_croak_unknown_args('port_forward', \%args, qw(name namespace ports
2196 subprotocol on_open on_frame on_close on_error));
2197  
2198 10 ▶ croak "name required for port_forward" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 9 10
2199  
2200 9 my $ports = delete $args{ports};
2201 9 ▶ croak "ports required for port_forward" unless defined $ports;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ports 1 8 9
2202 8 ▶ $ports = [$ports] unless ref($ports) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ports eq "ARRAY" 0 8 8
2203 8 ▶ croak "ports required for port_forward" unless @$ports;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ports 1 7 8
2204 7 for my $p (@$ports) {
2205 9 ▶ croak "invalid port '$p' for port_forward"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535 2 7 9
Condition77%7/9
defined $p and $p =~ /^\d+$/ and $p > 0 and $p <= 65535
!ll&&!rl&&r
117
defined $p and $p =~ /^\d+$/ and $p > 0
!ll&&!rl&&r
108
defined $p and $p =~ /^\d+$/
!ll&&!rl&&r
018
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
2206 unless defined($p) && $p =~ /^\d+$/ && $p > 0 && $p <= 65535;
2207 }
2208  
2209 5 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
23
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
2210 5 my $on_open = delete $args{on_open};
2211 5 my $on_frame = delete $args{on_frame};
2212 5 my $on_close = delete $args{on_close};
2213 5 my $on_error = delete $args{on_error};
2214  
2215 5 my $class = $self->_expand_class_or_croak($short_class);
2216 3 my $path = $self->_build_path($class, %args, subresource => 'portforward',
2217 $self->_unstructured_hint($class, $short_class));
2218  
2219 3 my $req = $self->_prepare_request('GET', $path,
2220 parameters => { ports => $ports },
2221 headers => {
2222 Accept => '*/*',
2223 Connection => 'Upgrade',
2224 Upgrade => 'websocket',
2225 'Sec-WebSocket-Protocol' => $subprotocol,
2226 },
2227 );
2228  
2229 3 my $io = $self->io;
2230 3 ▶ unless ($io->can('call_duplex')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io->can("call_duplex")) 1 2 3
2231 1 croak "IO backend does not support port_forward(): missing call_duplex()";
2232 }
2233  
2234 2 return $io->call_duplex($req,
2235 on_open => $on_open,
2236 on_frame => $on_frame,
2237 on_close => $on_close,
2238 on_error => $on_error,
2239 );
2240 }
2241  
2242 16 ▶sub exec {
Subroutine exec: called CC=26 SCAR=32.7
Pod documented
2243 16 my ($self, $short_class, @rest) = @_;
2244  
2245  
2246 16 my %args;
2247 16 ▶ 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)$/) { } 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|command|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/
!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|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
2248 14 $args{name} = shift @rest;
2249 14 %args = (%args, @rest);
2250 } elsif (@rest % 2 == 0) {
2251 2 %args = @rest;
2252 } else {
2253 0 croak "Invalid arguments to exec()";
2254 }
2255 # A misspelt option is not ignored (karr k61): containr => 'app' ran the
2256 # command in the default container.
2257 16 $self->_croak_unknown_args('exec', \%args, qw(name namespace command
2258 container stdin stdout stderr tty subprotocol on_open on_frame on_close
2259 on_error));
2260  
2261 11 ▶ croak "name required for exec" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 10 11
2262  
2263 10 my $command = delete $args{command};
2264 10 ▶ croak "command required for exec" unless defined $command;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $command 1 9 10
2265 9 ▶ $command = [$command] unless ref($command) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $command eq "ARRAY" 1 8 9
2266 9 ▶ croak "command required for exec" unless @$command;
Branch: 1 branch
BranchTrueFalseTotal
unless @$command 1 8 9
2267 8 for my $part (@$command) {
2268 10 ▶ croak "invalid command element for exec"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part and not ref $part and length $part 2 8 10
Condition83%5/6
defined $part and not ref $part and length $part
!ll&&!rl&&r
208
defined $part and not ref $part
!ll&&!rl&&r
118
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
2269 unless defined($part) && !ref($part) && length $part;
2270 }
2271  
2272 6 my $container = delete $args{container};
2273 6 ▶ my $stdin = delete($args{stdin}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'stdin'} ? : 2 4 6
2274 6 ▶ my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stdout'} ? : 2 4 6
delete $args{'stdout'} ? : 1 1 2
2275 6 ▶ my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stderr'} ? : 2 4 6
delete $args{'stderr'} ? : 1 1 2
2276 6 ▶ my $tty = delete($args{tty}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'tty'} ? : 2 4 6
2277  
2278 6 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
24
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
2279 6 my $on_open = delete $args{on_open};
2280 6 my $on_frame = delete $args{on_frame};
2281 6 my $on_close = delete $args{on_close};
2282 6 my $on_error = delete $args{on_error};
2283  
2284 6 my $class = $self->_expand_class_or_croak($short_class);
2285 4 my $path = $self->_build_path($class, %args, subresource => 'exec',
2286 $self->_unstructured_hint($class, $short_class));
2287  
2288 4 ▶ my %params = (
Branch: 4 branches
BranchTrueFalseTotal
$stdin ? : 2 2 4
$stdout ? : 3 1 4
$stderr ? : 3 1 4
$tty ? : 2 2 4
2289 command => $command,
2290 stdin => $stdin ? 'true' : 'false',
2291 stdout => $stdout ? 'true' : 'false',
2292 stderr => $stderr ? 'true' : 'false',
2293 tty => $tty ? 'true' : 'false',
2294 );
2295 4 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 2 2 4
2296  
2297 4 my $req = $self->_prepare_request('GET', $path,
2298 parameters => \%params,
2299 headers => {
2300 Accept => '*/*',
2301 Connection => 'Upgrade',
2302 Upgrade => 'websocket',
2303 'Sec-WebSocket-Protocol' => $subprotocol,
2304 },
2305 );
2306  
2307 4 my $io = $self->io;
2308 4 ▶ unless ($io->can('call_duplex')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io->can("call_duplex")) 1 3 4
2309 1 croak "IO backend does not support exec(): missing call_duplex()";
2310 }
2311  
2312 3 return $io->call_duplex($req,
2313 on_open => $on_open,
2314 on_frame => $on_frame,
2315 on_close => $on_close,
2316 on_error => $on_error,
2317 );
2318 }
2319  
2320 12 ▶sub attach {
Subroutine attach: called CC=19 SCAR=29.5
Pod documented
2321 12 my ($self, $short_class, @rest) = @_;
2322  
2323  
2324 12 my %args;
2325 12 ▶ 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)$/) { } 9 3 12
elsif (@rest % 2 == 0) { } 3 0 3
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
039
@rest >= 1 and not ref $rest[0]
!ll&&!rl&&r
0012
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
2326 9 $args{name} = shift @rest;
2327 9 %args = (%args, @rest);
2328 } elsif (@rest % 2 == 0) {
2329 3 %args = @rest;
2330 } else {
2331 0 croak "Invalid arguments to attach()";
2332 }
2333 # A misspelt option is not ignored (karr k61): stdn => 1 attached without
2334 # stdin.
2335 12 $self->_croak_unknown_args('attach', \%args, qw(name namespace container
2336 stdin stdout stderr tty subprotocol on_open on_frame on_close on_error));
2337  
2338 7 ▶ croak "name required for attach" unless $args{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"name"} 1 6 7
2339  
2340 6 my $container = delete $args{container};
2341 6 ▶ my $stdin = delete($args{stdin}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'stdin'} ? : 2 4 6
2342 6 ▶ my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stdout'} ? : 2 4 6
delete $args{'stdout'} ? : 1 1 2
2343 6 ▶ my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $args{'stderr'} ? : 2 4 6
delete $args{'stderr'} ? : 1 1 2
2344 6 ▶ my $tty = delete($args{tty}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
delete $args{'tty'} ? : 2 4 6
2345  
2346 6 ▶ my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io';
Condition100%2/2
delete $args{"subprotocol"} // "v4.channel.k8s.io"
l!l
24
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
2347 6 my $on_open = delete $args{on_open};
2348 6 my $on_frame = delete $args{on_frame};
2349 6 my $on_close = delete $args{on_close};
2350 6 my $on_error = delete $args{on_error};
2351  
2352 6 my $class = $self->_expand_class_or_croak($short_class);
2353 4 my $path = $self->_build_path($class, %args, subresource => 'attach',
2354 $self->_unstructured_hint($class, $short_class));
2355  
2356 4 ▶ my %params = (
Branch: 4 branches
BranchTrueFalseTotal
$stdin ? : 2 2 4
$stdout ? : 3 1 4
$stderr ? : 3 1 4
$tty ? : 2 2 4
2357 stdin => $stdin ? 'true' : 'false',
2358 stdout => $stdout ? 'true' : 'false',
2359 stderr => $stderr ? 'true' : 'false',
2360 tty => $tty ? 'true' : 'false',
2361 );
2362 4 ▶ $params{container} = $container if defined $container;
Branch: 1 branch
BranchTrueFalseTotal
if defined $container 2 2 4
2363  
2364 4 my $req = $self->_prepare_request('GET', $path,
2365 parameters => \%params,
2366 headers => {
2367 Accept => '*/*',
2368 Connection => 'Upgrade',
2369 Upgrade => 'websocket',
2370 'Sec-WebSocket-Protocol' => $subprotocol,
2371 },
2372 );
2373  
2374 4 my $io = $self->io;
2375 4 ▶ unless ($io->can('call_duplex')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($io->can("call_duplex")) 1 3 4
2376 1 croak "IO backend does not support attach(): missing call_duplex()";
2377 }
2378  
2379 3 return $io->call_duplex($req,
2380 on_open => $on_open,
2381 on_frame => $on_frame,
2382 on_close => $on_close,
2383 on_error => $on_error,
2384 );
2385 }
2386  
2387 63 1;
2388  
2389 __END__
2390  
2391 =pod
2392  
2393 =encoding UTF-8
2394  
2395 =head1 NAME
2396  
2397 Kubernetes::REST - A Perl REST Client for the Kubernetes API
2398  
2399 =head1 VERSION
2400  
2401 version 1.109
2402  
2403 =head1 SYNOPSIS
2404  
2405 use Kubernetes::REST;
2406  
2407 my $api = Kubernetes::REST->new(
2408 server => {
2409 endpoint => 'https://kubernetes.local:6443',
2410 ssl_verify_server => 1,
2411 ssl_ca_file => '/path/to/ca.crt',
2412 },
2413 credentials => { token => $token },
2414 );
2415  
2416 # List all namespaces
2417 my $namespaces = $api->list('Namespace');
2418 for my $ns (@{ $namespaces->items }) {
2419 say $ns->metadata->name;
2420 }
2421  
2422 # List pods in a namespace
2423 my $pods = $api->list('Pod', namespace => 'default');
2424  
2425 # Get a specific pod
2426 my $pod = $api->get('Pod', name => 'my-pod', namespace => 'default');
2427  
2428 # Create a namespace
2429 my $ns = $api->new_object(Namespace => {
2430 metadata => { name => 'my-namespace' },
2431 });
2432 my $created = $api->create($ns);
2433  
2434 # Create multiple namespaces
2435 for my $i (1..10) {
2436 $api->create($api->new_object(Namespace =>
2437 metadata => { name => "test-ns-$i" },
2438 ));
2439 }
2440  
2441 # Update a resource (full replacement)
2442 $pod->metadata->labels({ app => 'updated' });
2443 my $updated = $api->update($pod);
2444  
2445 # Patch a resource (partial update)
2446 my $patched = $api->patch('Pod', 'my-pod',
2447 namespace => 'default',
2448 patch => { metadata => { labels => { env => 'staging' } } },
2449 );
2450  
2451 # Delete a resource
2452 $api->delete($pod);
2453 # or by name:
2454 $api->delete('Pod', name => 'my-pod', namespace => 'default');
2455  
2456 # Idempotent create-or-update (from a typed object or a manifest hashref)
2457 $api->ensure($pod);
2458 $api->ensure({
2459 apiVersion => 'v1',
2460 kind => 'Secret',
2461 metadata => { name => 'my-secret', namespace => 'default' },
2462 stringData => { password => 'hunter2' },
2463 });
2464  
2465 # Batch apply
2466 $api->ensure_all(@objects);
2467  
2468 # Apply a labeled set and prune anything with that label not in the set
2469 $api->ensure_only(
2470 label => 'app.kubernetes.io/component=queen',
2471 objects => \@rbac_objects,
2472 kinds => [qw(Role RoleBinding ClusterRoleBinding)],
2473 namespaces => ['default', undef],
2474 );
2475  
2476 =head1 DESCRIPTION
2477  
2478 This module provides a simple REST client for the Kubernetes API using IO::K8s
2479 resource classes. The IO::K8s classes know their own metadata (API version,
2480 kind, whether they're namespaced), so URL building is automatic.
2481  
2482 =head2 server
2483  
2484 Required. L<Kubernetes::REST::Server> instance or hashref with server connection configuration.
2485  
2486 server => { endpoint => 'https://kubernetes.local:6443' }
2487  
2488 Automatically coerces hashrefs to L<Kubernetes::REST::Server> objects.
2489  
2490 =head2 credentials
2491  
2492 Required. Authentication credentials. Can be a hashref, L<Kubernetes::REST::AuthToken>, or any object with a C<token()> method.
2493  
2494 credentials => { token => $bearer_token }
2495  
2496 Automatically coerces hashrefs to L<Kubernetes::REST::AuthToken> objects.
2497  
2498 =head2 io
2499  
2500 HTTP backend for making requests. Must consume L<Kubernetes::REST::Role::IO>. Defaults to L<Kubernetes::REST::LWPIO> (L<LWP::UserAgent>).
2501  
2502 To use L<HTTP::Tiny> instead:
2503  
2504 use Kubernetes::REST::HTTPTinyIO;
2505 my $api = Kubernetes::REST->new(
2506 ...,
2507 io => Kubernetes::REST::HTTPTinyIO->new(...),
2508 );
2509  
2510 See L</PLUGGABLE IO ARCHITECTURE> for custom backends.
2511  
2512 =head2 with
2513  
2514 Arrayref of external L<IO::K8s> resource-map providers (CRD bundles), passed
2515 straight through to the inner L<IO::K8s/with>. Each entry is a provider class
2516 name (or object, or plain hashref) whose typed classes are merged into the
2517 resource map, so the cluster's CRD Kinds resolve to real classes:
2518  
2519 my $api = Kubernetes::REST->new(
2520 server => { endpoint => 'https://k8s.local:6443' },
2521 credentials => { token => $token },
2522 with => ['IO::K8s::GatewayAPI'],
2523 );
2524  
2525 my $gw = $api->new_object(Gateway => { metadata => { name => 'gw' } });
2526 # => IO::K8s::GatewayAPI::V1::Gateway
2527  
2528 Defaults to C<[]>. See L<IO::K8s/with> for the accepted provider forms.
2529  
2530 =head2 k8s
2531  
2532 L<IO::K8s> instance configured with the same resource map. Automatically created when needed.
2533  
2534 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>.)
2535  
2536 Delegation is a convenience only, every one of them behaves exactly as it does on L<IO::K8s>, including its argument contract:
2537  
2538 =over
2539  
2540 =item *
2541  
2542 C<new_object> takes a short or full class name and either a hashref or a flat hash of attributes:
2543  
2544 my $ns = $api->new_object(Namespace => { metadata => { name => 'foo' } });
2545 my $ns = $api->new_object(Namespace => metadata => { name => 'foo' });
2546  
2547 =item *
2548  
2549 C<inflate> takes a hashref, or JSON as B<UTF-8 bytes> - its decoder is C<utf8 =E<gt> 1>.
2550  
2551 =item *
2552  
2553 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:
2554  
2555 my $pod = $api->json_to_object($json_with_kind);
2556 my $pod = $api->json_to_object('Pod', $json_string);
2557  
2558 C<object_to_json> and C<object_to_struct> are their inverses, serialising a typed object back to JSON or to a plain hashref.
2559  
2560 =item *
2561  
2562 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:
2563  
2564 for my $obj (@{ $api->load_yaml('deployment.yaml') }) {
2565 $api->create($obj);
2566 }
2567  
2568 =item *
2569  
2570 C<load> reads a C<.pk8s> manifest, which is Perl code and is C<eval>ed in-process:
2571  
2572 my $objects = $api->load('myapp.pk8s');
2573  
2574 Only load C<.pk8s> files you trust; for data-only manifests use C<load_yaml>.
2575  
2576 =back
2577  
2578 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.
2579  
2580 =head2 resource_map_from_cluster
2581  
2582 Boolean. If true, dynamically loads the resource map from the cluster's OpenAPI spec. Defaults to C<1>.
2583  
2584 Set to C<0> to use L<IO::K8s> built-in resource map instead (faster startup, but may not match your cluster version).
2585  
2586 =head2 cluster_version
2587  
2588 Read-only. The Kubernetes cluster version string (e.g., C<v1.31.0>). Fetched automatically from the C</version> endpoint when first accessed.
2589  
2590 =head2 resource_map
2591  
2592 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.
2593  
2594 When the cluster's discovery cannot be read, the built-in map is used
2595 instead, with a warning that names the reason - at the line of the call that
2596 first needed the map, whether that read C<resource_map> or resolved a name.
2597  
2598 Override for custom resources:
2599  
2600 resource_map => {
2601 %{ IO::K8s->default_resource_map },
2602 MyResource => '+My::K8s::V1::MyResource',
2603 }
2604  
2605 The C<+> prefix tells L<IO::K8s> that this is a custom class (not in the IO::K8s:: namespace).
2606  
2607 The client keeps a copy of the hashref it is given: the Kinds of the L</with>
2608 providers are merged into that copy, never into your hash, and a change you
2609 make to your hash after construction is not seen. Change
2610 C<< $api->resource_map >> itself instead:
2611  
2612 $api->resource_map->{StaticWebSite} = '+My::StaticWebSite';
2613  
2614 =head2 expand_class
2615  
2616 my $class = $api->expand_class('Pod');
2617 # => IO::K8s::Api::Core::V1::Pod
2618  
2619 Resolve a short resource name (C<'Pod'>), a domain-qualified name
2620 (C<'cilium.io/v2/NetworkPolicy'>), a C<+>-prefixed or an already
2621 fully-qualified class name to its L<IO::K8s> class - the same contract as
2622 L<IO::K8s/expand_class>, against this client's L</resource_map>.
2623  
2624 With L</resource_map_from_cluster> on (the default), a Kind no shipped class,
2625 L</with> provider or AutoGen class resolves becomes L<IO::K8s::Unstructured>
2626 when the cluster's discovery serves it. A bare Kind is looked up in whichever
2627 group serves it, at that group's preferred version. A qualified name
2628 (C<'example.org/v1/Widget'>, or C<('Widget', 'example.org/v1')>) counts only
2629 in exactly that group and version: when the cluster does not serve those, it
2630 stays unresolved (C<undef>), even if another group or another version serves
2631 a Kind of the same name - nothing is ever sent there instead.
2632  
2633 The methods that take a resource name - L</list>, L</get>, L</patch>,
2634 L</patch_status>, L</delete>, L</watch>, L</log>, L</port_forward>,
2635 L</exec>, L</attach> and L</compare_schema> - croak on a name that stays
2636 unresolved, before sending anything, and name it:
2637  
2638 unknown resource 'other.org/v1/Widget': no IO::K8s class for this
2639 apiVersion/kind (add it to resource_map if it is a CRD)
2640  
2641 A bare Kind nothing resolves (C<expand_class> answers with the class name
2642 C<IO::K8s::E<lt>KindE<gt>>, which does not exist) is reported the same way.
2643 When the cluster's discovery could not be read, the message goes on to say so
2644 and why - the cluster could not confirm the name, which is not the same as not
2645 serving it.
2646  
2647 Pure name resolution does not cost a cluster roundtrip: as long as the
2648 resource map has not been fetched yet (and none was passed to the
2649 constructor), a name the built-in L<IO::K8s> map resolves to a loadable
2650 class is answered from that map directly. Only a name the built-in map
2651 cannot answer falls through to the cluster-backed map, fetching it on first
2652 use exactly as before.
2653  
2654 The result is a plain class name, without a C<+>. Handed back to a method
2655 that resolves names again - L<IO::K8s/struct_to_object>,
2656 L<IO::K8s/json_to_object> - a single-segment class of your own (C<'+Gizmo'>
2657 in the resource map, returned as C<'Gizmo'>) reads as the Kind C<Gizmo>
2658 there. Prefix it with C<+> when you do that yourself; this client's own
2659 inflation already does.
2660  
2661 =head2 fetch_resource_map
2662  
2663 my $map = $api->fetch_resource_map;
2664  
2665 Build the resource map from the cluster's aggregated discovery documents
2666 (C<GET /api> and C<GET /apis>). Returns a hashref mapping short resource names
2667 (e.g., C<Pod>) to full L<IO::K8s> class paths.
2668  
2669 Called automatically if C<resource_map_from_cluster> is enabled.
2670  
2671 Discovery is fetched and cached once per instance (see L</invalidate_discovery>;
2672 an async client can supply it instead, see L</absorb_discovery>);
2673 calling this again rebuilds the map from the cached catalog rather than
2674 re-querying the cluster. It does B<not> download C</openapi/v2> - that spec is
2675 fetched lazily only when L</schema_for> or L</compare_schema> need it.
2676  
2677 When discovery cannot be read, it croaks C<Could not load resource map from
2678 cluster:> followed by the reason - for an HTTP error status the message of
2679 the L<Kubernetes::REST::APIError>,
2680 C<Kubernetes API error (discovery GET /api): 401 ...>.
2681  
2682 A cluster older than Kubernetes 1.27 answers with legacy discovery, which
2683 takes one more request per group and version. When one of those answers with
2684 an HTTP error status, that group/version's Kinds are missing from the map,
2685 and a warning names its apiVersion and the error - C<discovery: cannot read
2686 apiVersion 'metrics.k8s.io/v1beta1', its Kinds are missing from the resource
2687 map: Kubernetes API error (discovery GET /apis/metrics.k8s.io/v1beta1): 503
2688 ...>; the other groups are read on. A 404 there is silent: the group/version
2689 went away after the list of groups was read.
2690  
2691 B<Version selection (D17).> When a group serves a Kind in more than one
2692 version, the bare short name (C<Pod>, C<ServiceCIDR>) resolves to the version
2693 the B<cluster marks preferred> for that group - not to a fixed "stable beats
2694 alpha/beta" preference. A Kind served only outside the preferred version still
2695 maps, to its first served version.
2696  
2697 Only Kinds whose L<IO::K8s> class this distribution actually ships are recorded
2698 in the map. A CRD group with no bundled class (C<cilium.io>,
2699 C<cert-manager.io>, ...) is deliberately omitted here, so that its Kinds
2700 resolve through the inner L<IO::K8s> - a provider merged via L</with>, then
2701 AutoGen from the fetched C</openapi/v2>, and finally a fail-closed error -
2702 rather than being mapped to a class name that does not exist.
2703  
2704 =head2 invalidate_discovery
2705  
2706 $api->invalidate_discovery;
2707  
2708 Discard the cached discovery catalog and the resource map built from it, so the
2709 next resolution re-queries the cluster. Use it after a CustomResourceDefinition
2710 is installed or changed, to make the new Kind visible to this client instance.
2711  
2712 A resource map passed to the constructor is not built from the catalog and
2713 stays as it is, entries such as C<'+My::Class'> included.
2714  
2715 =head2 prepare_discovery_requests
2716  
2717 my %requests = $api->prepare_discovery_requests;
2718 # ('/api' => $request, '/apis' => $request)
2719  
2720 Build the two discovery requests - C<GET /api> and C<GET /apis>, with the
2721 C<Accept> header that asks for aggregated discovery (C<APIGroupDiscoveryList>,
2722 C<apidiscovery.k8s.io/v2>) - without sending them. Returns them as path/request
2723 pairs, C</api> first, each a L<Kubernetes::REST::HTTPRequest> as
2724 L</prepare_request> builds it: exactly what the client sends when it reads
2725 discovery through its own L</io>.
2726  
2727 This and L</absorb_discovery> are for async wrappers such as
2728 L<Net::Async::Kubernetes>. With L</resource_map_from_cluster> on, the first
2729 name resolution otherwise reads discovery through the synchronous L</io>,
2730 blocking the wrapper's event loop.
2731  
2732 =head2 absorb_discovery
2733  
2734 my $absorbed = $api->absorb_discovery(
2735 '/api' => $api_response,
2736 '/apis' => $apis_response,
2737 );
2738  
2739 Take the responses to the requests from L</prepare_discovery_requests> - any
2740 objects with C<status> and C<content> (the undecoded body), such as
2741 L<Kubernetes::REST::HTTPResponse>.
2742  
2743 When both are aggregated discovery documents they become this client's
2744 discovery catalog, replacing any it had cached, as if the client had read them
2745 itself, and the method returns true. From then on L</expand_class>,
2746 L</fetch_resource_map>, L</build_path> and the lazily built L</resource_map>
2747 answer from that catalog without sending a request. A resource map built from
2748 an earlier catalog is rebuilt from this one; a map passed to the constructor
2749 stays as it is.
2750  
2751 When either is a legacy discovery document - a cluster older than Kubernetes
2752 1.27 ignores the C<Accept> header - it returns false and caches nothing:
2753 reading legacy discovery takes a request per group and version, which only the
2754 synchronous path makes. The client then reads discovery itself when it first
2755 needs it, as it always did.
2756  
2757 An HTTP error status dies with a L<Kubernetes::REST::APIError>, as the
2758 client's own discovery read does, its C<context> naming the document:
2759 C<Kubernetes API error (discovery GET /apis): 503 ...>. A missing response,
2760 or any key other than C</api> and C</apis>, croaks.
2761  
2762 An async client hands the requests to its own transport and the responses
2763 back - here C<< $send->($request) >> stands for whatever runs a
2764 L<Kubernetes::REST::HTTPRequest> through the event loop and returns a
2765 L<Future> of the response:
2766  
2767 my %requests = $rest->prepare_discovery_requests;
2768 my @roots = sort keys %requests;
2769 my $ready = Future->needs_all(map { $send->($requests{$_}) } @roots)
2770 ->then(sub {
2771 my %responses;
2772 @responses{@roots} = @_;
2773 # false: legacy discovery, read synchronously on first use
2774 $rest->absorb_discovery(%responses);
2775 return Future->done;
2776 });
2777  
2778 =head2 schema_for
2779  
2780 my $schema = $api->schema_for('Pod');
2781  
2782 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>).
2783  
2784 A name resolves as in L</expand_class>, and the definition is looked up by
2785 the name its class maps onto (C<IO::K8s::Api::Core::V1::Pod> becomes
2786 C<io.k8s.api.core.v1.Pod>), which holds for the C<IO::K8s::Api::> classes.
2787 Where no definition has that name - apiextensions and apiregistration, whose
2788 definitions upstream names after their staging repositories, a CRD class of
2789 your own or from a L</with> provider, L<IO::K8s::Unstructured> - it is the
2790 definition whose C<x-kubernetes-group-version-kind> names the class's API
2791 group, version and Kind: its C<api_version> and C<kind>, or for
2792 L<IO::K8s::Unstructured> the Kind and the group/version the cluster's
2793 discovery confirmed for it.
2794  
2795 Returns a hashref with the OpenAPI v2 schema definition, or C<undef> when
2796 there is none - also for a name that resolves to no class at all.
2797  
2798 The spec is fetched from C</openapi/v2> on first use and kept. An HTTP error
2799 status there dies with a L<Kubernetes::REST::APIError> whose C<context> is
2800 C<fetch OpenAPI spec>, as does L</compare_schema>; nothing is kept, and the
2801 next call fetches again.
2802  
2803 =head2 compare_schema
2804  
2805 my $result = $api->compare_schema('Pod');
2806  
2807 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.
2808  
2809 Returns the comparison result from C<< $class->compare_to_schema >>, the method L<IO::K8s::Role::Resource> provides on every resource class.
2810  
2811 A name that resolves to L<IO::K8s::Unstructured> (see L</expand_class>)
2812 croaks, before the spec is fetched: that class declares only C<apiVersion>,
2813 C<kind> and C<metadata> and keeps every other field untyped, so it has no
2814 local schema to compare. L</schema_for> still answers the cluster's
2815 definition for such a name.
2816  
2817 =head2 build_path
2818  
2819 my $class = $api->expand_class('Pod');
2820 my $path = $api->build_path($class, name => 'my-pod', namespace => 'default');
2821 # => /api/v1/namespaces/default/pods/my-pod
2822  
2823 my $status = $api->build_path($class,
2824 name => 'my-pod',
2825 namespace => 'default',
2826 subresource => 'status',
2827 );
2828 # => /api/v1/namespaces/default/pods/my-pod/status
2829  
2830 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.
2831  
2832 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.
2833  
2834 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:
2835  
2836 my $path = $api->build_path('IO::K8s::Unstructured',
2837 kind => 'MyCRD',
2838 api_version => 'example.com/v1',
2839 resource => 'mycrds',
2840 namespaced => 1,
2841 name => 'my-instance',
2842 namespace => 'default',
2843 );
2844 # => /apis/example.com/v1/namespaces/default/mycrds/my-instance
2845  
2846 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 - then only that group/version counts, never another group or version that serves a Kind of the same name; C<build_path> croaks if discovery has no entry for the Kind (in the pinned group/version, which the message then names), 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.
2847  
2848 This is a public API for async wrappers like L<Net::Async::Kubernetes> that need to construct request paths independently.
2849  
2850 =head2 prepare_request
2851  
2852 my $req = $api->prepare_request('GET', $path,
2853 parameters => \%params,
2854 body => \%body,
2855 );
2856  
2857 Build a L<Kubernetes::REST::HTTPRequest> with method, full URL, authorization
2858 headers, and optional query parameters or JSON body.
2859  
2860 Query parameter values may be scalars or arrayrefs (arrayrefs are emitted as
2861 repeated C<key=value> pairs). Extra request headers can be provided via
2862 C<headers =E<gt> \%headers>.
2863  
2864 Keys and values are percent-encoded where they would otherwise split or
2865 change the query on its way to the API server: C<%>, C<&>, C<+>, C<#>, C<;>,
2866 space, control characters, and non-ASCII characters (as their UTF-8 bytes).
2867 Everything else is sent as written, so a selector such as
2868 C<app.kubernetes.io/name=web,tier!=db> appears in the URL exactly as it was
2869 passed. Pass characters, not bytes - a value that already holds UTF-8 bytes
2870 is encoded twice. A query string that is already part of C<$path> is left
2871 untouched.
2872  
2873 This is a public API for async wrappers that execute HTTP requests through their own event loop.
2874  
2875 =head2 check_response
2876  
2877 $api->check_response($response, "get Pod");
2878  
2879 Validate an HTTP response. Returns the response on success. On a status code
2880 >= 400 it dies with a L<Kubernetes::REST::APIError>, which carries the status
2881 (C<code>, C<is_not_found>, C<is_conflict>), the C<reason>, C<message> and
2882 C<details> of a Kubernetes C<Status> body, the decoded C<body>, the
2883 C<context> and the C<response>. It stringifies to the message this method
2884 croaked with as a plain string before, C<Kubernetes API error (get Pod): 404
2885 ...>, naming the line that called C<check_response>. See L</ERROR HANDLING>.
2886  
2887 =head2 inflate_object
2888  
2889 my $pod = $api->inflate_object($class, $response);
2890  
2891 Decode the JSON response body and inflate it into a typed L<IO::K8s> object.
2892  
2893 C<$class> is normally what L</expand_class> resolved and L</build_path>
2894 loaded. A loaded L<IO::K8s> class is inflated as exactly that class - also a
2895 single-segment class of your own, registered as C<'+Gizmo'>, which
2896 L<IO::K8s> would otherwise read as the Kind C<Gizmo>. Any other name, short
2897 or qualified, is resolved first. L</inflate_list> and
2898 L</process_watch_chunk> treat C<$class> the same way.
2899  
2900 =head2 inflate_list
2901  
2902 my $list = $api->inflate_list($class, $response);
2903  
2904 Decode the JSON response body and inflate the C<items> array into an L<IO::K8s::List> of typed objects.
2905  
2906 An item the object model rejects - typically because the installed L<IO::K8s>
2907 does not know a field the cluster version serves - is dropped from the list,
2908 and a warning names every dropped item (index, C<metadata.name>, the
2909 inflation error) so an incomplete list is never silent. Promote it to a fatal
2910 error with C<< local $SIG{__WARN__} = sub { die @_ } >> if partial results
2911 are unacceptable to you.
2912  
2913 =head2 process_watch_chunk
2914  
2915 my @results = $api->process_watch_chunk($class, \$buffer, $chunk);
2916  
2917 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>.
2918  
2919 This is a public API for async wrappers that handle streaming watch responses through their own event loop.
2920  
2921 =head2 process_log_chunk
2922  
2923 my @events = $api->process_log_chunk(\$buffer, $chunk);
2924  
2925 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.
2926  
2927 This is a public API for async wrappers that handle streaming log responses through their own event loop.
2928  
2929 =head2 list
2930  
2931 my $list = $api->list('Pod', namespace => 'default');
2932 my $list = $api->list('Namespace', labelSelector => 'app=web');
2933  
2934 List resources. Returns an L<IO::K8s::List> object.
2935  
2936 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.
2937  
2938 Supports C<labelSelector> and C<fieldSelector> query parameters for server-side filtering.
2939  
2940 Any other argument croaks before a request is sent, naming it: a misspelt
2941 option is not ignored. That includes C<name>: the list endpoint selects one
2942 object with C<< fieldSelector => 'metadata.name=NAME' >>, and L</get>
2943 fetches it.
2944  
2945 =head2 get
2946  
2947 my $pod = $api->get('Pod', name => 'my-pod', namespace => 'default');
2948 # or shorthand:
2949 my $pod = $api->get('Pod', 'my-pod', namespace => 'default');
2950  
2951 Get a single resource by name. Returns a typed L<IO::K8s> object.
2952  
2953 my $pod = $api->get('Pod', 'my-pod', namespace => 'default',
2954 subresource => 'status');
2955 # GET /api/v1/namespaces/default/pods/my-pod/status
2956  
2957 Takes C<name>, C<namespace> for namespaced resources, and C<subresource>,
2958 which reads the named subresource of the object instead of the object. The
2959 response is inflated as the resource's own class, which fits a subresource
2960 that answers with the object itself, as C<status> does. Any other argument
2961 croaks before a request is sent, naming it: a misspelt option is not
2962 ignored.
2963  
2964 =head2 create
2965  
2966 my $created = $api->create($pod);
2967  
2968 Create a resource from an L<IO::K8s> object. Returns the created object with server-assigned fields (UID, resourceVersion, etc.).
2969  
2970 =head2 update
2971  
2972 my $updated = $api->update($pod);
2973  
2974 Update an existing resource. Replaces the entire object server-side. Returns the updated object.
2975  
2976 For partial updates, use L</patch> instead.
2977  
2978 =head2 patch
2979  
2980 my $patched = $api->patch('Pod', 'my-pod',
2981 namespace => 'default',
2982 patch => { metadata => { labels => { env => 'staging' } } },
2983 );
2984  
2985 # Or with an object:
2986 my $patched = $api->patch($pod,
2987 patch => { metadata => { labels => { env => 'staging' } } },
2988 );
2989  
2990 # JSON Patch (RFC 6902) instead: an array of operations, not a hashref
2991 my $patched = $api->patch('Deployment', 'my-app',
2992 namespace => 'default',
2993 type => 'json',
2994 patch => [
2995 { op => 'replace', path => '/spec/replicas', value => 3 },
2996 { op => 'add', path => '/metadata/labels/env', value => 'prod' },
2997 ],
2998 );
2999  
3000 Partially update a resource. Unlike C<update()> which replaces the entire object, C<patch()> only modifies specified fields.
3001  
3002 Required: C<patch> (a hashref, or an arrayref of operations when C<type> is
3003 C<json>) and, when passing a class rather than an object, C<name>.
3004  
3005 Optional: C<namespace> (for namespaced resources) and C<type>, the patch
3006 strategy:
3007  
3008 =over 4
3009  
3010 =item C<strategic> (default)
3011  
3012 Strategic Merge Patch. The Kubernetes-native patch type, which understands
3013 array merge semantics (e.g. adding a container to a pod spec without removing
3014 the existing ones).
3015  
3016 =item C<merge>
3017  
3018 JSON Merge Patch (RFC 7396). Simple recursive merge where C<null> values
3019 delete keys; arrays are replaced entirely.
3020  
3021 =item C<json>
3022  
3023 JSON Patch (RFC 6902): an array of operations, as in the third example above.
3024  
3025 =back
3026  
3027 Returns the full updated object from the server.
3028  
3029 Any other argument croaks before a request is sent, naming it: a misspelt
3030 option is not ignored. With an object, which names the resource itself, only
3031 C<patch> and C<type> are taken - C<name> and C<namespace> croak too.
3032  
3033 =head2 patch_status
3034  
3035 my $node = $api->patch_status('OCPNode', 'cp-1',
3036 namespace => 'ocp',
3037 patch => { status => { phase => 'Ready', ip => '10.0.0.7' } },
3038 );
3039  
3040 # Or with an object:
3041 my $node = $api->patch_status($node,
3042 patch => { status => { phase => 'Ready' } },
3043 );
3044  
3045 Partially update a resource's B<status> through the C</status> subresource.
3046  
3047 Once a CustomResourceDefinition declares C<subresources: {status: {}}>, the API
3048 server strips the C<status> stanza from every write to the main endpoint -
3049 C<create>, C<update>, C<patch> and server-side apply alike - and still answers
3050 2xx. The write appears to succeed and nothing is stored. Status has to go to
3051 C</status>, which is what this method addresses.
3052  
3053 Takes the same arguments as L</patch> (object or class plus name, both call
3054 forms, the same C<type> values), croaks on any other as L</patch> does, and
3055 returns the full object from the server.
3056 The patch document is passed through unchanged, so it carries its own
3057 C<status> key.
3058  
3059 The default patch type is C<merge>, not C<strategic> as in L</patch>: custom
3060 resources do not support strategic merge patch and the API server rejects it
3061 with 415, and C<merge> works for built-in kinds as well. Pass
3062 C<type =E<gt> 'strategic'> explicitly when patching the status of a built-in
3063 resource and you need array merge semantics.
3064  
3065 =head2 update_status
3066  
3067 my $node = $api->update_status($node);
3068  
3069 Replace a resource's B<status> through the C</status> subresource. The whole
3070 object is sent, as with L</update>, but the server only takes its C<status>
3071 and leaves C<spec> and C<metadata> untouched. Returns the updated object.
3072  
3073 This is the read-modify-write counterpart to L</patch_status>: it needs a
3074 current C<resourceVersion> and fails with a 409 conflict when the object
3075 changed in the meantime. Prefer L</patch_status> when you are setting
3076 individual status fields.
3077  
3078 =head2 delete
3079  
3080 $api->delete($pod);
3081 # or by name:
3082 $api->delete('Pod', name => 'my-pod', namespace => 'default');
3083 # or shorthand:
3084 $api->delete('Pod', 'my-pod', namespace => 'default');
3085  
3086 # a Job, and the Pods it created with it:
3087 $api->delete($job, propagationPolicy => 'Background');
3088 $api->delete('Job', 'nightly', namespace => 'default',
3089 propagationPolicy => 'Foreground');
3090  
3091 Delete a resource. Returns true on success.
3092  
3093 The optional C<propagationPolicy> decides what happens to the objects the
3094 deleted one owns, and is sent as the C<propagationPolicy> query parameter
3095 (a C<DeleteOptions> field):
3096  
3097 =over 4
3098  
3099 =item C<Background>
3100  
3101 The object is deleted at once; the garbage collector deletes its dependents
3102 afterwards.
3103  
3104 =item C<Foreground>
3105  
3106 The object stays, with a C<deletionTimestamp>, until its dependents are
3107 deleted.
3108  
3109 =item C<Orphan>
3110  
3111 The dependents are kept and lose their owner reference.
3112  
3113 =back
3114  
3115 Without it the server applies the resource's default - for a C<batch/v1>
3116 C<Job> that is C<Orphan>, which leaves its Pods behind. Any other value
3117 croaks, listing the three.
3118  
3119 Any argument other than C<name>, C<namespace> and C<propagationPolicy> -
3120 with an object, other than C<propagationPolicy> - croaks before anything is
3121 sent, naming it: a misspelt option is not ignored.
3122  
3123 =head2 ensure
3124  
3125 my $obj = $api->ensure($pod);
3126 # or from a plain hashref (treated as a Kubernetes manifest):
3127 my $secret = $api->ensure({
3128 apiVersion => 'v1',
3129 kind => 'Secret',
3130 metadata => { name => 'foo', namespace => 'default' },
3131 stringData => { password => 'hunter2' },
3132 });
3133  
3134 Idempotent create-or-update. Fetches the resource by kind/name/namespace; if it
3135 exists, updates it (preserving C<resourceVersion>), otherwise creates it.
3136 Returns the resulting L<IO::K8s> object.
3137  
3138 Accepts either a typed L<IO::K8s> object or a plain hashref. A hashref must
3139 carry a C<kind> field and is inflated to a typed object via
3140 L<IO::K8s/struct_to_object>. Hashref keys follow the Kubernetes API convention
3141 (camelCase, e.g. C<stringData>, not C<string_data>).
3142  
3143 A hashref's C<apiVersion>, when present, selects the class: an
3144 C<autoscaling/v1> HorizontalPodAutoscaler stays C<autoscaling/v1> and goes to
3145 that endpoint, although the bare Kind resolves to C<autoscaling/v2>. An
3146 C<apiVersion> that resolves to no known class croaks, naming the Kind and the
3147 C<apiVersion>, instead of falling back to the Kind's default version. A
3148 hashref without C<apiVersion> resolves by its Kind alone, as L</expand_class>
3149 does; a Kind that resolves to nothing croaks naming it
3150 (C<unknown resource 'Kind'>, as described under L</expand_class>) before any
3151 request is sent.
3152  
3153 Handles common race conditions:
3154  
3155 =over 4
3156  
3157 =item * 404 on initial get is treated as "does not exist" and falls through to create.
3158  
3159 =item * 409 AlreadyExists on create (resource appeared between get and create) is
3160 re-fetched and handled like a resource that existed from the start: updated,
3161 or - for the special cases below - returned unchanged or recreated.
3162  
3163 =item * 409 Conflict on update (resourceVersion changed server-side, e.g. a
3164 controller wrote status) is retried by re-fetching and re-applying.
3165  
3166 =back
3167  
3168 Each case is recognised by the response status. Any other error status
3169 croaks with the API error, whatever its message happens to say.
3170  
3171 Special-cases for kinds with server-side mutation constraints:
3172  
3173 =over 4
3174  
3175 =item * C<PersistentVolumeClaim> (core C<v1>) - spec is immutable after
3176 creation, so an existing PVC is returned unchanged.
3177  
3178 =item * C<Job> (C<batch/v1>) - spec is immutable; an existing Job that is
3179 active or has succeeded is returned unchanged. A failed Job is deleted with
3180 C<propagationPolicy> C<Background>, so its Pods go with it, and recreated.
3181  
3182 =back
3183  
3184 Both are recognised by apiVersion and Kind together: a typed object's
3185 C<api_version> and C<kind>, or an L<IO::K8s::Unstructured> object's
3186 C<apiVersion> and C<kind> fields - never by the class name. A custom resource
3187 that reuses one of these Kind names in its own group is ensured like any other
3188 object, and so is a C<Job> under any apiVersion other than C<batch/v1>.
3189  
3190 It takes exactly one object or hashref. Anything after it croaks before a
3191 request is sent - an option is not ignored, and a second object is not
3192 applied silently or dropped; L</ensure_all> takes several.
3193  
3194 =head2 ensure_all
3195  
3196 my @results = $api->ensure_all(@objects);
3197  
3198 Batch version of L</ensure>. Applies create-or-update to each object in order
3199 and returns the list of resulting objects.
3200  
3201 =head2 ensure_only
3202  
3203 $api->ensure_only(
3204 label => 'app.kubernetes.io/component=queen',
3205 objects => \@objects,
3206 kinds => [qw(Role RoleBinding ClusterRoleBinding)],
3207 namespaces => ['default', 'kube-system', undef],
3208 );
3209  
3210 Like L</ensure_all>, but also B<deletes> any resources matching the label
3211 selector in the given kinds and namespaces that are not present in C<objects>.
3212 Use this for resources where stale objects must not survive (e.g. RBAC).
3213  
3214 Pass C<undef> inside C<namespaces> to scan cluster-scoped resources. If
3215 C<namespaces> is omitted, only cluster-scoped resources are scanned.
3216  
3217 C<objects> takes typed objects or hashrefs, resolved as in L</ensure>. A
3218 C<kinds> entry may be a bare Kind or a qualified C<group/version/Kind> (see
3219 L</expand_class>). A listed resource counts as present when its API group,
3220 Kind, namespace and name match an object in C<objects> - group and Kind come
3221 from a typed object's C<api_version> and C<kind>, or from an
3222 L<IO::K8s::Unstructured> object's C<apiVersion> and C<kind> fields. The
3223 same Kind name in another group is another resource: with Istio's
3224 C<networking.istio.io> Gateway in C<objects>, a labelled Gateway API
3225 C<gateway.networking.k8s.io> Gateway of the same name is deleted. The version
3226 is not compared, so an object applied as C<autoscaling/v1> is kept when the
3227 listing goes through C<autoscaling/v2>.
3228  
3229 Pruning goes on past a failure, and says so. When a C<kinds> entry cannot be
3230 listed in one namespace - an HTTP error, or an entry that resolves to no
3231 class - that combination is skipped with a warning naming the entry, the
3232 namespace (or cluster scope) and the reason; anything stale there survives
3233 this run. A 404 is silent: the cluster does not serve that Kind, so there is
3234 nothing to prune. A delete that fails warns with the Kind, name, namespace and
3235 reason, and the next object is tried; a 404 there means the object is already
3236 gone and is silent too. Promote the warnings to a fatal error with
3237 C<< local $SIG{__WARN__} = sub { die @_ } >> if a partial prune is
3238 unacceptable to you.
3239  
3240 Pruned objects are deleted with C<propagationPolicy> C<Background> (see
3241 L</delete>), as C<kubectl delete> does, so a pruned Job takes its Pods with
3242 it. Pass C<< propagationPolicy => 'Foreground' >> or C<'Orphan'> to change
3243 that; any other value croaks before anything is applied.
3244  
3245 Returns the list of applied objects (from L</ensure_all>), whether or not the
3246 pruning was complete.
3247  
3248 Any argument other than C<label>, C<objects>, C<kinds>, C<namespaces> and
3249 C<propagationPolicy> croaks before anything is applied, naming it: a
3250 misspelt option is not ignored.
3251  
3252 =head2 ensure_crd
3253  
3254 # one class == one single-version CRD
3255 $api->ensure_crd('My::K8s::StaticWebSite');
3256  
3257 # several distinct CRDs at once
3258 $api->ensure_crd(@crd_classes);
3259  
3260 # with options (pass the classes as an arrayref):
3261 $api->ensure_crd(\@crd_classes, timeout => 60, poll_interval => 2);
3262  
3263 # several classes that are versions of the SAME CRD -> one multi-version CRD
3264 $api->ensure_crd(
3265 [ 'My::K8s::V1beta1::Widget', 'My::K8s::V1::Widget' ],
3266 storage => 'v1',
3267 );
3268  
3269 Install (create-or-update) one or more CustomResourceDefinitions from typed
3270 L<IO::K8s> classes, wait for each to reach the C<Established> condition, then
3271 L</invalidate_discovery> so the new Kinds resolve on this client instance.
3272  
3273 Each class's CRD manifest comes from C<< $class->to_crd >> (L<IO::K8s::CRD>).
3274 The assembled CRD is applied with L</ensure>, so re-running is idempotent.
3275 After every CRD is applied, each is polled with L</get> by name until its
3276 C<status.conditions> carries C<< type => 'Established', status => 'True' >>,
3277 subject to a timeout. Only then is the discovery cache invalidated, so the
3278 next C<create>/C<list> of a custom resource does not race the apiserver
3279 registering the Kind (the reason plain C<ensure> of the CRD is not enough:
3280 the following call almost always creates a CR, which 404s until Established).
3281 A 404 while polling counts as not registered yet and is polled again; any
3282 other error status ends the wait at once and croaks with that API error.
3283  
3284 Returns the list of established CustomResourceDefinition objects (the objects
3285 read back from the final poll, carrying their C<Established> status).
3286  
3287 Arguments: the CRD classes, either as a plain list (C<ensure_crd(@classes)>)
3288 or, when options are needed, as an arrayref followed by named options
3289 (C<ensure_crd(\@classes, %opts)>).
3290  
3291 =over 4
3292  
3293 =item timeout
3294  
3295 Seconds to wait for the C<Established> condition per CRD (default 30). On
3296 expiry the call croaks, naming the CRD and that C<Established> was not
3297 reached.
3298  
3299 =item poll_interval
3300  
3301 Seconds between polls (default 1). The current state is always checked once
3302 before the timeout is consulted, so C<timeout =E<gt> 0> performs exactly one
3303 poll.
3304  
3305 =item storage
3306  
3307 Only consulted when two or more passed classes name the SAME CRD (same group,
3308 plural, kind and scope but different versions). Those are assembled into ONE
3309 multi-version CustomResourceDefinition via
3310 C<< IO::K8s::CRD->new(classes => [...], storage => ...) >> rather than applied
3311 as competing single-version CRDs. Because a class carries no marker for which
3312 version is authoritative, the storage version is not guessed: pass it as a
3313 bare version string (applies to the multi-version group) or as a hashref
3314 keyed by CRD name (C<< { 'widgets.example.com' => 'v1' } >>). A multi-version
3315 group with no storage version croaks, naming the CRD and the candidate
3316 versions.
3317  
3318 =back
3319  
3320 Any other option croaks before anything is applied, naming it: a misspelt
3321 option is not ignored.
3322  
3323 =head2 watch
3324  
3325 my $last_rv = $api->watch('Pod',
3326 namespace => 'default',
3327 on_event => sub {
3328 my ($event) = @_;
3329 say $event->type . ": " . $event->object->metadata->name;
3330 },
3331 timeout => 300,
3332 resourceVersion => '12345',
3333 labelSelector => 'app=web',
3334 fieldSelector => 'status.phase=Running',
3335 );
3336  
3337 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.
3338  
3339 Required: C<on_event>, a callback invoked with a L<Kubernetes::REST::WatchEvent> for each event.
3340  
3341 Optional:
3342  
3343 =over 4
3344  
3345 =item timeout
3346  
3347 Server-side timeout in seconds (default: 300). The API server closes the
3348 connection after this many seconds.
3349  
3350 =item resourceVersion
3351  
3352 Resume watching from a specific resource version - pass the return value of a
3353 previous C<watch()> call to avoid missing events.
3354  
3355 =item labelSelector
3356  
3357 Filter by label selector (e.g. C<'app=web,env=prod'>).
3358  
3359 =item fieldSelector
3360  
3361 Filter by field selector (e.g. C<'status.phase=Running'>).
3362  
3363 =item namespace
3364  
3365 For namespaced resources, the namespace to watch.
3366  
3367 =back
3368  
3369 Any other argument croaks before a request is sent, naming it: a misspelt
3370 option is not ignored. That includes C<name>: to watch one object, pass
3371 C<< fieldSelector => 'metadata.name=NAME' >>.
3372  
3373 Returns the last C<resourceVersion> seen. Croaks on 410 Gone once the given
3374 C<resourceVersion> has expired - re-list to get a fresh one and resume from
3375 there:
3376  
3377 my $rv;
3378 while (1) {
3379 $rv = eval {
3380 $api->watch('Pod',
3381 namespace => 'default',
3382 resourceVersion => $rv,
3383 on_event => \&handle_event,
3384 );
3385 };
3386 if ($@ && $@ =~ /410 Gone/) {
3387 # resourceVersion expired, re-list to get fresh version
3388 my $list = $api->list('Pod', namespace => 'default');
3389 $rv = undef; # start fresh
3390 }
3391 }
3392  
3393 That croak is a plain string, not a L<Kubernetes::REST::APIError>: the watch
3394 request itself was answered with C<200>, and the C<410> arrived inside the
3395 stream as an C<ERROR> event, which C<on_event> has already been given. It
3396 calls for a re-list, not error handling. An HTTP error status on the watch
3397 request itself dies with an L<Kubernetes::REST::APIError> as usual.
3398  
3399 =head2 log
3400  
3401 # One-shot: get full log as string
3402 my $text = $api->log('Pod', 'my-pod',
3403 namespace => 'default',
3404 tailLines => 100,
3405 );
3406  
3407 # Streaming: callback per log line
3408 $api->log('Pod', 'my-pod',
3409 namespace => 'default',
3410 follow => 1,
3411 on_line => sub {
3412 my ($event) = @_; # Kubernetes::REST::LogEvent
3413 say $event->line;
3414 },
3415 );
3416  
3417 Retrieve logs from a pod. Supports two modes:
3418  
3419 B<One-shot> (without C<on_line>): Returns the full log text as a string.
3420  
3421 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).
3422  
3423 Log output is returned as raw bytes in both modes - container output is not
3424 guaranteed to be UTF-8, or even text. Decode it yourself when you know it is:
3425 C<< Encode::decode('UTF-8', $text) >>. See L</ENCODING>.
3426  
3427 The streaming mode is designed for event-based systems like L<IO::Async> — see L<Net::Async::Kubernetes> for async integration.
3428  
3429 Also accepts, for namespaced resources, C<namespace>; and as further optional
3430 arguments: C<container> (name, for multi-container pods), C<sinceSeconds> /
3431 C<sinceTime> (show only recent output), C<timestamps> (prepend a timestamp to
3432 each line), C<previous> (logs from the container's previous run, after a
3433 restart), and C<limitBytes> (byte cap on the response). Any other argument
3434 croaks before the request is sent, naming it: a misspelt option is not
3435 ignored.
3436  
3437 =head2 port_forward
3438  
3439 my $session = $api->port_forward('Pod', 'my-pod',
3440 namespace => 'default',
3441 ports => [8080, 8443],
3442 on_frame => sub { my ($channel, $payload) = @_; ... },
3443 );
3444  
3445 Start a full-duplex pod port-forward session.
3446  
3447 Required: C<name> and C<ports> - one port number or an arrayref of them (e.g.
3448 C<[8080, 8443]>).
3449  
3450 Optional: C<namespace> (for namespaced resources), C<subprotocol> (WebSocket
3451 subprotocol, default C<v4.channel.k8s.io>), and the duplex transport callbacks
3452 C<on_open>, C<on_frame>, C<on_close>, C<on_error>, passed through to the IO
3453 backend. Any other argument croaks before a request is sent, naming it: a
3454 misspelt option is not ignored.
3455  
3456 This method requires an IO backend that implements C<call_duplex>. The default
3457 L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> backends do not
3458 currently provide duplex transport.
3459  
3460 Returns whatever the IO backend returns for C<call_duplex> (typically a
3461 session/handle object managed by that backend).
3462  
3463 =head2 exec
3464  
3465 my $session = $api->exec('Pod', 'my-pod',
3466 namespace => 'default',
3467 command => ['sh', '-c', 'echo hello'],
3468 stdin => 0,
3469 stdout => 1,
3470 stderr => 1,
3471 tty => 0,
3472 on_frame => sub { my ($channel, $payload) = @_; ... },
3473 );
3474  
3475 Start a full-duplex pod exec session via the C</exec> subresource.
3476  
3477 Required: C<name> and C<command> - a single string or an arrayref (e.g.
3478 C<['sh', '-c', 'id']>).
3479  
3480 Optional: C<namespace>, C<container> (for multi-container pods), the stream
3481 toggles C<stdin>/C<stdout>/C<stderr>/C<tty> shown above (defaults: stdin and
3482 tty off, stdout and stderr on), C<subprotocol> (WebSocket subprotocol, default
3483 C<v4.channel.k8s.io>), and the duplex transport callbacks C<on_open>,
3484 C<on_frame>, C<on_close>, C<on_error>, passed through to the IO backend. Any
3485 other argument croaks before a request is sent, naming it: a misspelt option
3486 is not ignored.
3487  
3488 This method requires an IO backend that implements C<call_duplex>. The default
3489 L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> backends do not
3490 currently provide duplex transport.
3491  
3492 Returns whatever the IO backend returns for C<call_duplex> (typically a
3493 session/handle object managed by that backend).
3494  
3495 =head2 attach
3496  
3497 my $session = $api->attach('Pod', 'my-pod',
3498 namespace => 'default',
3499 container => 'app',
3500 stdin => 1,
3501 stdout => 1,
3502 stderr => 1,
3503 tty => 0,
3504 on_frame => sub { my ($channel, $payload) = @_; ... },
3505 );
3506  
3507 Start a full-duplex pod attach session via the C</attach> subresource.
3508  
3509 Required: C<name>.
3510  
3511 Optional: C<namespace>, C<container> (for multi-container pods), the stream
3512 toggles C<stdin>/C<stdout>/C<stderr>/C<tty> shown above (defaults: stdin and
3513 tty off, stdout and stderr on), C<subprotocol> (WebSocket subprotocol, default
3514 C<v4.channel.k8s.io>), and the duplex transport callbacks C<on_open>,
3515 C<on_frame>, C<on_close>, C<on_error>, passed through to the IO backend. Any
3516 other argument croaks before a request is sent, naming it: a misspelt option
3517 is not ignored.
3518  
3519 This method requires an IO backend that implements C<call_duplex>. The default
3520 L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> backends do not
3521 currently provide duplex transport.
3522  
3523 Returns whatever the IO backend returns for C<call_duplex> (typically a
3524 session/handle object managed by that backend).
3525  
3526 =head1 ERROR HANDLING
3527  
3528 When the API server answers with an HTTP error status (400 and up), the call
3529 dies with a L<Kubernetes::REST::APIError>. It stringifies to the familiar
3530 message - C<Kubernetes API error (get Pod): 404 {...} at app.pl line 12.> -
3531 so printing C<$@> or matching it against a regex works as it always did, and
3532 it carries the status for code that has to tell cases apart:
3533  
3534 my $ok = eval { $api->delete('Pod', 'web', namespace => 'default'); 1 };
3535 unless ($ok) {
3536 my $err = $@;
3537 die $err unless ref $err && $err->isa('Kubernetes::REST::APIError')
3538 && $err->is_not_found; # already gone is fine
3539 }
3540  
3541 Besides C<code>, C<is_not_found> and C<is_conflict> it has the C<reason>,
3542 C<message> and C<details> of the Kubernetes C<Status> body, the decoded
3543 C<body>, the C<context> and the C<response>.
3544  
3545 That includes the C</openapi/v2> fetch behind C<schema_for> and
3546 C<compare_schema>, and the discovery documents (C<GET /api>, C<GET /apis>,
3547 context C<discovery GET /api>), which L</absorb_discovery> dies with
3548 directly. Where the client reads discovery for itself, a failure shows
3549 inside another message instead - the warning that the resource map falls
3550 back to the built-in one, the croak of L</fetch_resource_map>, the croak for
3551 a name discovery could not confirm, the warning for a legacy group/version
3552 it could not read (see L</fetch_resource_map>) - which embeds the error's
3553 text.
3554  
3555 Everything else croaks with a plain string: invalid arguments, a resource
3556 name nothing resolves, and an expired watch - its C<410> arrives as an
3557 C<ERROR> event in a stream the server answered with C<200>, not as an HTTP
3558 status (see L</watch>).
3559  
3560 =head1 UPGRADING FROM 0.02
3561  
3562 B<WARNING: Version 1.00 contains breaking changes!>
3563  
3564 This version has been completely rewritten. Key changes that may affect your code:
3565  
3566 =over 4
3567  
3568 =item * B<New simplified API>
3569  
3570 The old method-per-operation API (e.g., C<< $api->Core->ListNamespacedPod(...) >>)
3571 has been replaced with a simple API: C<list>, C<get>, C<create>, C<update>,
3572 C<patch>, C<patch_status>, C<update_status>, C<delete>, C<ensure>,
3573 C<ensure_all>, C<ensure_only>, C<watch>, C<log>, C<port_forward>, C<exec>,
3574 C<attach>.
3575  
3576 =item * B<Old API still works but deprecated>
3577  
3578 The old API is still available for backwards compatibility but will emit deprecation
3579 warnings. Set C<$ENV{HIDE_KUBERNETES_REST_V0_API_WARNING}> to suppress warnings.
3580  
3581 =item * B<Uses IO::K8s classes>
3582  
3583 Results are now returned as typed L<IO::K8s> objects instead of raw hashrefs.
3584 Lists are returned as L<IO::K8s::List> objects.
3585  
3586 B<Note:> L<IO::K8s> has also been completely rewritten (Moose to Moo, API
3587 objects updated to a current Kubernetes release). See
3588 L<IO::K8s/"UPGRADING FROM PREVIOUS VERSIONS"> for details.
3589  
3590 =item * B<Short resource names>
3591  
3592 You can now use short names like C<'Pod'> instead of full class paths. The
3593 C<resource_map> attribute controls this mapping.
3594  
3595 =item * B<Dynamic resource map>
3596  
3597 Use C<resource_map_from_cluster =E<gt> 1> to load the resource map from the
3598 cluster's OpenAPI spec, ensuring compatibility with any Kubernetes version.
3599  
3600 =back
3601  
3602 =head1 BUILDING BLOCKS FOR ASYNC WRAPPERS
3603  
3604 Async wrappers like L<Net::Async::Kubernetes> need access to the request/response
3605 pipeline without going through the synchronous convenience methods. The following
3606 public methods provide this:
3607  
3608 =over 4
3609  
3610 =item * C<expand_class($short)> - Resolve short name to full class
3611  
3612 =item * C<build_path($class, %args)> - Build REST API URL path
3613  
3614 =item * C<prepare_request($method, $path, %opts)> - Build HTTP request with auth
3615  
3616 =item * C<check_response($response, $context)> - Validate HTTP status (dies
3617 with a L<Kubernetes::REST::APIError> on 400 and up)
3618  
3619 =item * C<inflate_object($class, $response)> - JSON to typed object
3620  
3621 =item * C<inflate_list($class, $response)> - JSON to typed list (an item the
3622 object model rejects is dropped and carped about, not silently lost - see
3623 L</inflate_list>)
3624  
3625 =item * C<process_watch_chunk($class, \$buf, $chunk)> - Parse NDJSON watch stream
3626  
3627 =item * C<process_log_chunk(\$buf, $chunk)> - Parse plain-text log stream
3628  
3629 =item * C<prepare_discovery_requests> and C<absorb_discovery(%responses)> -
3630 Read the cluster's discovery through your own event loop, so that resolving
3631 names needs no request of the client's own (see L</absorb_discovery>)
3632  
3633 =back
3634  
3635 Example async integration:
3636  
3637 # Build request using Kubernetes::REST
3638 my $class = $rest->expand_class('Pod');
3639 my $path = $rest->build_path($class,
3640 name => $name,
3641 namespace => $ns,
3642 subresource => 'log',
3643 );
3644 my $req = $rest->prepare_request('GET', $path, parameters => { follow => 'true' });
3645  
3646 # Execute through your own event loop
3647 my $buffer = '';
3648 $async_http->request($req->url, sub {
3649 my ($chunk) = @_;
3650 for my $event ($rest->process_log_chunk(\$buffer, $chunk)) {
3651 $on_line->($event);
3652 }
3653 });
3654  
3655 =head1 PLUGGABLE IO ARCHITECTURE
3656  
3657 The HTTP transport is decoupled from request preparation and response
3658 processing. This makes it possible to swap the default L<LWP::UserAgent>
3659 backend for L<HTTP::Tiny> or an async backend (e.g. L<Net::Async::HTTP>)
3660 without changing any API logic.
3661  
3662 The pipeline for each API call:
3663  
3664 1. prepare_request() - builds HTTPRequest (method, url, headers, body)
3665 2. io->call() - executes request (pluggable backend)
3666 3. check_response() - validates HTTP status
3667 4. inflate_object/list - decodes JSON + inflates IO::K8s objects
3668  
3669 For watch, step 2 uses C<io-E<gt>call_streaming()> and step 4 uses
3670 C<process_watch_chunk()> which parses NDJSON and inflates each event.
3671  
3672 For log, step 2 uses C<io-E<gt>call_streaming()> and step 4 uses
3673 C<process_log_chunk()> which parses plain-text lines into L<Kubernetes::REST::LogEvent> objects.
3674  
3675 To implement a custom IO backend, consume L<Kubernetes::REST::Role::IO>
3676 and implement C<call($req)> and C<call_streaming($req, $callback)>.
3677 See L<Kubernetes::REST::LWPIO> and L<Kubernetes::REST::HTTPTinyIO> for
3678 reference implementations.
3679  
3680 =head1 ENCODING
3681  
3682 On the wire everything is bytes; in your program everything is characters.
3683 The boundary sits in this module, and you do not have to do anything for it:
3684  
3685 =over
3686  
3687 =item *
3688  
3689 Objects you pass to C<create>, C<update>, C<patch> and friends hold ordinary
3690 Perl character strings. They are UTF-8 encoded on the way into the request
3691 body, so C<< data => { note => "Caf\x{e9} \x{a7}" } >> is applied to the
3692 cluster unchanged.
3693  
3694 =item *
3695  
3696 Objects you get back from C<get>, C<list>, C<watch> and friends hold decoded
3697 characters, so C<length> counts characters and regexes match as expected.
3698  
3699 =item *
3700  
3701 Exception messages from failed API calls are decoded too.
3702  
3703 =back
3704  
3705 Two things stay bytes on purpose:
3706  
3707 =over
3708  
3709 =item *
3710  
3711 C<log> - container output is an arbitrary byte stream, not necessarily UTF-8,
3712 and decoding it would corrupt anything binary. Decode it yourself if you know
3713 it is text: C<< Encode::decode('UTF-8', $api->log('Pod', $name)) >>. The same
3714 applies to C<< $event->line >> in streaming mode.
3715  
3716 =item *
3717  
3718 The C<content> of L<Kubernetes::REST::HTTPRequest> and
3719 L<Kubernetes::REST::HTTPResponse> - these are the raw HTTP layer. Custom IO
3720 backends must honour that; see L<Kubernetes::REST::Role::IO/Encoding contract>.
3721  
3722 =back
3723  
3724 =head1 SEE ALSO
3725  
3726 =head2 Related Modules
3727  
3728 =over
3729  
3730 =item * L<IO::K8s> - Kubernetes resource classes (required dependency)
3731  
3732 =item * L<Net::Async::Kubernetes> - Async Kubernetes client for L<IO::Async>
3733  
3734 =back
3735  
3736 =head2 Configuration and Authentication
3737  
3738 =over
3739  
3740 =item * L<Kubernetes::REST::Kubeconfig> - Load settings from kubeconfig
3741  
3742 =item * L<Kubernetes::REST::Server> - Server connection configuration
3743  
3744 =item * L<Kubernetes::REST::AuthToken> - Authentication credentials
3745  
3746 =back
3747  
3748 =head2 HTTP Backends
3749  
3750 =over
3751  
3752 =item * L<Kubernetes::REST::Role::IO> - IO interface role
3753  
3754 =item * L<Kubernetes::REST::LWPIO> - LWP::UserAgent backend (default)
3755  
3756 =item * L<Kubernetes::REST::HTTPTinyIO> - HTTP::Tiny backend
3757  
3758 =item * L<LWP::ConsoleLogger> - HTTP debugging for LWPIO
3759  
3760 =back
3761  
3762 =head2 Data Objects
3763  
3764 =over
3765  
3766 =item * L<Kubernetes::REST::WatchEvent> - Watch event object
3767  
3768 =item * L<Kubernetes::REST::LogEvent> - Log event object
3769  
3770 =item * L<Kubernetes::REST::APIError> - Error thrown for an HTTP error status
3771  
3772 =item * L<Kubernetes::REST::HTTPRequest> - HTTP request object
3773  
3774 =item * L<Kubernetes::REST::HTTPResponse> - HTTP response object
3775  
3776 =back
3777  
3778 =head2 CLI Tools
3779  
3780 =over
3781  
3782 =item * L<Kubernetes::REST::CLI> - CLI base class
3783  
3784 =item * L<Kubernetes::REST::CLI::Watch> - kube_watch CLI tool
3785  
3786 =item * L<Kubernetes::REST::CLI::Role::Connection> - Shared CLI options
3787  
3788 =back
3789  
3790 =head2 Examples and Documentation
3791  
3792 =over
3793  
3794 =item * L<Kubernetes::REST::Example> - Comprehensive examples with Minikube/K3s
3795  
3796 =item * L<https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.36/> - Kubernetes API reference
3797  
3798 =back
3799  
3800 =head1 SUPPORT
3801  
3802 =head2 Issues
3803  
3804 Please report bugs and feature requests on GitHub at
3805 L<https://github.com/pplu/kubernetes-rest/issues>.
3806  
3807 =head2 IRC
3808  
3809 Join C<#kubernetes> on C<irc.perl.org> or message Getty directly.
3810  
3811 =head1 CONTRIBUTING
3812  
3813 Contributions are welcome! Please fork the repository and submit a pull request.
3814  
3815 =head1 AUTHORS
3816  
3817 =over 4
3818  
3819 =item *
3820  
3821 Torsten Raudssus <getty@cpan.org>
3822  
3823 =item *
3824  
3825 Jose Luis Martinez Torres <jlmartin@cpan.org>
3826  
3827 =back
3828  
3829 =head1 COPYRIGHT AND LICENSE
3830  
3831 This software is Copyright (c) 2019-2026 by Jose Luis Martinez Torres <jlmartin@cpan.org>.
3832  
3833 This is free software, licensed under:
3834  
3835 The Apache License, Version 2.0, January 2004
3836  
3837 =cut
« blib/lib/Kubernetes/REST/CLI/Crd2Class.pm ↑ Summary lib/Kubernetes/REST/CLI/Minikube.pm »