| 1 | package Kubernetes::REST; | ||
| 2 | our $VERSION = '1.109'; | ||
| 3 | # ABSTRACT: A Perl REST Client for the Kubernetes API | ||
| 4 | use Moo; | ||
| 5 | use Carp qw(croak carp); | ||
| 6 | use Scalar::Util qw(blessed); | ||
| 7 | use Module::Runtime qw(require_module); | ||
| 8 | use JSON::MaybeXS (); | ||
| 9 | use Encode (); | ||
| 10 | use Kubernetes::REST::Server; | ||
| 11 | use Kubernetes::REST::AuthToken; | ||
| 12 | use Kubernetes::REST::LWPIO; | ||
| 13 | use Kubernetes::REST::HTTPRequest; | ||
| 14 | use IO::K8s; | ||
| 15 | use IO::K8s::List; | ||
| 16 | use IO::K8s::CRD; | ||
| 17 | use IO::K8s::Unstructured (); | ||
| 18 | use Time::HiRes (); | ||
| 19 | use Kubernetes::REST::WatchEvent; | ||
| 20 | use Kubernetes::REST::LogEvent; | ||
| 21 | use Kubernetes::REST::APIError; | ||
| 22 | use namespace::clean; | ||
| 23 | |||
| 24 | has server => ( | ||
| 25 | is => 'ro', | ||
| 26 | required => 1, | ||
| 27 | coerce => sub { | ||
| 28 | my $val = $_[0]; | ||
| 29 | return $val if blessed($val) && $val->isa('Kubernetes::REST::Server'); | ||
| 30 | Kubernetes::REST::Server->new($val); | ||
| 31 | }, | ||
| 32 | ); | ||
| 33 | |||
| 34 | |||
| 35 | has credentials => ( | ||
| 36 | is => 'ro', | ||
| 37 | required => 1, | ||
| 38 | coerce => sub { | ||
| 39 | my $val = $_[0]; | ||
| 40 | return $val if blessed($val) && $val->can('token'); | ||
| 41 | return Kubernetes::REST::AuthToken->new($val) if ref($val) eq 'HASH'; | ||
| 42 | return $val; | ||
| 43 | } | ||
| 44 | ); | ||
| 45 | |||
| 46 | |||
| 47 | has io => ( | ||
| 48 | is => 'ro', | ||
| 49 | lazy => 1, | ||
| 50 | default => sub { | ||
| 51 | my $self = shift; | ||
| 52 | my $s = $self->server; | ||
| 53 | Kubernetes::REST::LWPIO->new( | ||
| 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 | ); | ||
| 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 | default => sub { | ||
| 72 | JSON::MaybeXS->new(utf8 => 1, canonical => 1, convert_blessed => 1); | ||
| 73 | }, | ||
| 74 | ); | ||
| 75 | |||
| 76 | # External IO::K8s resource-map providers, mirrored onto the inner instance. | ||
| 77 | has with => ( | ||
| 78 | is => 'ro', | ||
| 79 | default => sub { [] }, | ||
| 80 | ); | ||
| 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 | default => sub { | ||
| 90 | my $self = shift; | ||
| 91 | return IO::K8s->new( | ||
| 92 | resource_map => $self->resource_map, | ||
| 93 | with => [ @{ $self->with } ], | ||
| 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 | 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 | has resource_map_from_cluster => (is => 'ro', default => sub { 1 }); | ||
| 117 | |||
| 118 | |||
| 119 | # Cluster version - fetched once per instance | ||
| 120 | has cluster_version => ( | ||
| 121 | is => 'ro', | ||
| 122 | lazy => 1, | ||
| 123 | default => sub { | ||
| 124 | my $self = shift; | ||
| 125 | my $response = $self->_request('GET', '/version'); | ||
| 126 | return 'unknown' if $response->status >= 400; | ||
| 127 | my $info = $self->_json->decode($response->content); | ||
| 128 | return $info->{gitVersion} // 'unknown'; | ||
| 129 | }, | ||
| 130 | ); | ||
| 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 | coerce => sub { ref $_[0] eq 'HASH' ? { %{ $_[0] } } : $_[0] }, | ||
| 147 | default => sub { | ||
| 148 | my $self = shift; | ||
| 149 | # Built here, not passed in: absorb_discovery may rebuild it. | ||
| 150 | $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 | return { %{ IO::K8s->default_resource_map } } unless $self->resource_map_from_cluster; | ||
| 156 | return $self->_load_resource_map_from_cluster; | ||
| 157 | }, | ||
| 158 | ); | ||
| 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 | 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 | sub expand_class { | ||
| 172 | my ($self, @args) = @_; | ||
| 173 | |||
| 174 | |||
| 175 | if ($self->resource_map_from_cluster && !$self->_has_resource_map | ||
| 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 | return substr($args[0], 1) if $args[0] =~ /^\+/; | ||
| 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 | my $class = IO::K8s->expand_class(@args); | ||
| 187 | return $class if defined $class | ||
| 188 | && ($class->can('new') || eval { require_module($class); 1 }); | ||
| 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 | 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 | my ($kind, $api_version) = $self->_kind_from_expand_args(@args); | ||
| 218 | return $class unless defined $kind && $self->_is_unresolved($class, $kind); | ||
| 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 | return 'IO::K8s::Unstructured' | ||
| 241 | if $self->_discovery_path_meta($kind, $api_version); | ||
| 242 | |||
| 243 | 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 | sub _is_unresolved { | ||
| 252 | my ($self, $class, $kind) = @_; | ||
| 253 | return 1 unless defined $class; | ||
| 254 | return defined $kind | ||
| 255 | && $class eq "IO::K8s::$kind" | ||
| 256 | && !($class->can('new') || eval { require_module($class); 1 }); | ||
| 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 | sub _expand_class_or_croak { | ||
| 274 | my ($self, $name) = @_; | ||
| 275 | my $class = $self->expand_class($name); | ||
| 276 | my ($kind) = $self->_kind_from_expand_args($name); | ||
| 277 | return $class unless $self->_is_unresolved($class, $kind); | ||
| 278 | my $discovery_error = defined $kind ? $self->_discovery_error : undef; | ||
| 279 | $discovery_error = $self->_error_reason($discovery_error) if defined $discovery_error; | ||
| 280 | croak "unknown resource '" . ($name // '(undef)') . "': no IO::K8s class" | ||
| 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 | sub _error_reason { | ||
| 293 | my ($self, $error) = @_; | ||
| 294 | my $reason = "$error"; | ||
| 295 | $reason =~ s/(?: at \S+ line \d+(?:, <[^>]*> (?:line|chunk) \d+)?\.)?\s*\z//; | ||
| 296 | 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 | sub _carp_past_builders { | ||
| 307 | my ($self, $message) = @_; | ||
| 308 | local our @CARP_NOT = ('Method::Generate::Accessor::_Generated'); | ||
| 309 | carp $message; | ||
| 310 | 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 | sub _kind_from_expand_args { | ||
| 320 | my ($self, $name, $api_version) = @_; | ||
| 321 | return () unless defined $name && !ref $name; | ||
| 322 | return () if $name =~ /^\+/; | ||
| 323 | return () if $name =~ /^IO::K8s::/; | ||
| 324 | if ($name =~ m{/}) { # 'group/version/Kind' -> ('Kind', 'group/version') | ||
| 325 | my ($av, $kind) = $name =~ m{\A(.*)/([^/]+)\z}; | ||
| 326 | return ($kind, $av); | ||
| 327 | } | ||
| 328 | return () if $name =~ /::/; # a multi-segment class name, not a Kind | ||
| 329 | 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 | sub _discovery_path_meta { | ||
| 355 | my ($self, $kind, $want_api_version) = @_; | ||
| 356 | return unless $self->resource_map_from_cluster; | ||
| 357 | my $catalog = eval { $self->_discovery }; | ||
| 358 | if (my $error = $@) { | ||
| 359 | $self->_discovery_error($error); | ||
| 360 | return; | ||
| 361 | } | ||
| 362 | $self->_clear_discovery_error; | ||
| 363 | return unless $catalog && $catalog->{groups}; | ||
| 364 | |||
| 365 | my $meta_for = sub { | ||
| 366 | my ($group, $version, $res) = @_; | ||
| 367 | return { | ||
| 368 | api_version => ($group eq '' ? $version : "$group/$version"), | ||
| 369 | resource => $res->{resource}, | ||
| 370 | namespaced => ($res->{scope} && $res->{scope} eq 'Namespaced' ? 1 : 0), | ||
| 371 | }; | ||
| 372 | }; | ||
| 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 | if (defined $want_api_version && length $want_api_version) { | ||
| 382 | my ($g, $v) = $want_api_version =~ m{/} | ||
| 383 | ? split(m{/}, $want_api_version, 2) | ||
| 384 | : ('', $want_api_version); | ||
| 385 | my $res = $catalog->{groups}{$g}{versions}{$v}{kinds}{$kind}; | ||
| 386 | return unless $res; | ||
| 387 | return $meta_for->($g, $v, $res); | ||
| 388 | } | ||
| 389 | |||
| 390 | # A bare Kind: the preferred version of whichever group serves it (D17). | ||
| 391 | for my $group (sort keys %{$catalog->{groups}}) { | ||
| 392 | my $gdata = $catalog->{groups}{$group}; | ||
| 393 | my @order = @{$gdata->{version_order} // []}; | ||
| 394 | my $pref = $gdata->{preferred}; | ||
| 395 | @order = ($pref, grep { $_ ne $pref } @order) | ||
| 396 | if defined $pref && grep { $_ eq $pref } @order; | ||
| 397 | for my $version (@order) { | ||
| 398 | my $res = $gdata->{versions}{$version}{kinds}{$kind}; | ||
| 399 | return $meta_for->($group, $version, $res) if $res; | ||
| 400 | } | ||
| 401 | } | ||
| 402 | 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 | sub _unstructured_hint { | ||
| 413 | my ($self, $class, $ident) = @_; | ||
| 414 | return () unless defined $class && $class eq 'IO::K8s::Unstructured'; | ||
| 415 | if (blessed($ident)) { | ||
| 416 | return ( | ||
| 417 | kind => $ident->kind, | ||
| 418 | (defined $ident->apiVersion ? (api_version => $ident->apiVersion) : ()), | ||
| 419 | ); | ||
| 420 | } | ||
| 421 | my ($kind, $api_version) = $self->_kind_from_expand_args($ident); | ||
| 422 | return ( | ||
| 423 | (defined $kind ? (kind => $kind) : ()), | ||
| 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 | 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 | 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 | sub _io_k8s_namespace_for_group { | ||
| 453 | my ($self, $group) = @_; | ||
| 454 | return $NON_API_NAMESPACE{$group} if exists $NON_API_NAMESPACE{$group}; | ||
| 455 | return 'Api::' . ($group eq '' ? 'Core' : ucfirst(lc((split /\./, $group)[0]))); | ||
| 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 | sub _io_k8s_namespace_for_group_path { | ||
| 463 | my ($self, $group_path) = @_; | ||
| 464 | return $NON_API_NAMESPACE_BY_GROUP_PATH{$group_path} // "Api::${group_path}"; | ||
| 465 | } | ||
| 466 | |||
| 467 | # Public method to build the resource map from the cluster's discovery catalog | ||
| 468 | sub fetch_resource_map { | ||
| 469 | 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 | my $catalog = eval { $self->_discovery }; | ||
| 479 | croak 'Could not load resource map from cluster: ' . $self->_error_reason($@) | ||
| 480 | unless $catalog; | ||
| 481 | |||
| 482 | 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 | sub _resource_map_from_catalog { | ||
| 504 | my ($self, $catalog) = @_; | ||
| 505 | |||
| 506 | my %map; | ||
| 507 | for my $group (keys %{$catalog->{groups} // {}}) { | ||
| 508 | 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 | my @order = @{$gdata->{version_order} // []}; | ||
| 516 | my $pref = $gdata->{preferred}; | ||
| 517 | @order = ($pref, grep { $_ ne $pref } @order) | ||
| 518 | if defined $pref && grep { $_ eq $pref } @order; | ||
| 519 | |||
| 520 | for my $version (@order) { | ||
| 521 | my $kinds = $gdata->{versions}{$version}{kinds}; | ||
| 522 | for my $kind (keys %$kinds) { | ||
| 523 | next if $kind =~ /List$/; | ||
| 524 | next if exists $map{$kind}; # a preferred/earlier version won it | ||
| 525 | |||
| 526 | my $version_path = ucfirst($version); | ||
| 527 | 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 | next unless $self->_io_k8s_class_ships($new_path); | ||
| 532 | |||
| 533 | $map{$kind} = $new_path; | ||
| 534 | } | ||
| 535 | } | ||
| 536 | } | ||
| 537 | |||
| 538 | 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 | 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 | sub _io_k8s_class_ships { | ||
| 553 | my ($self, $rel_path) = @_; | ||
| 554 | return $_CLASS_SHIPS{$rel_path} //= do { | ||
| 555 | my $full = "IO::K8s::$rel_path"; | ||
| 556 | ($full->can('new') || eval { require_module($full); 1 }) ? 1 : 0; | ||
| 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 | builder => sub { $_[0]->_fetch_discovery }, | ||
| 576 | ); | ||
| 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 | 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 | 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 | my @DISCOVERY_ROOTS = ('/api', '/apis'); | ||
| 600 | |||
| 601 | sub _fetch_discovery { | ||
| 602 | my ($self) = @_; | ||
| 603 | |||
| 604 | my $catalog = { groups => {} }; | ||
| 605 | |||
| 606 | for my $root (@DISCOVERY_ROOTS) { | ||
| 607 | my ($body, $aggregated) = $self->_discovery_document($root, | ||
| 608 | $self->io->call($self->_discovery_request($root))); | ||
| 609 | |||
| 610 | if ($aggregated) { | ||
| 611 | $self->_absorb_discovery_list($catalog, $body); | ||
| 612 | } elsif ($root eq '/api') { | ||
| 613 | $self->_fetch_discovery_legacy_core($catalog, $body); | ||
| 614 | } else { | ||
| 615 | $self->_fetch_discovery_legacy_groups($catalog, $body); | ||
| 616 | } | ||
| 617 | } | ||
| 618 | |||
| 619 | 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 | sub _discovery_request { | ||
| 625 | my ($self, $root) = @_; | ||
| 626 | 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 | sub _discovery_document { | ||
| 636 | my ($self, $root, $response) = @_; | ||
| 637 | $self->_check_response($response, "discovery GET $root"); | ||
| 638 | my $body = $self->_json->decode($response->content); | ||
| 639 | my $kind = ref $body eq 'HASH' ? ($body->{kind} // '') : ''; | ||
| 640 | 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 | sub _absorb_discovery_list { | ||
| 646 | my ($self, $catalog, $body) = @_; | ||
| 647 | |||
| 648 | for my $group_item (@{$body->{items} // []}) { | ||
| 649 | my $group = $group_item->{metadata}{name} // ''; | ||
| 650 | my @versions = @{$group_item->{versions} // []}; | ||
| 651 | for my $i (0 .. $#versions) { | ||
| 652 | my $vd = $versions[$i]; | ||
| 653 | my $version = $vd->{version}; | ||
| 654 | next unless defined $version && length $version; | ||
| 655 | for my $res (@{$vd->{resources} // []}) { | ||
| 656 | my $plural = $res->{resource}; | ||
| 657 | my $rkind = $res->{responseKind}{kind}; | ||
| 658 | next unless defined $plural && defined $rkind; | ||
| 659 | $self->_catalog_add($catalog, $group, $version, $rkind, | ||
| 660 | $plural, $res->{scope} // ''); | ||
| 661 | } | ||
| 662 | # First version served = preferred version for the group. | ||
| 663 | $catalog->{groups}{$group}{preferred} = $version | ||
| 664 | if $i == 0 && exists $catalog->{groups}{$group}; | ||
| 665 | } | ||
| 666 | } | ||
| 667 | } | ||
| 668 | |||
| 669 | # Legacy fallback for GET /api: an APIVersions document. Each version's | ||
| 670 | # APIResourceList is fetched from /api/<version>. | ||
| 671 | sub _fetch_discovery_legacy_core { | ||
| 672 | my ($self, $catalog, $body) = @_; | ||
| 673 | |||
| 674 | my @versions = @{$body->{versions} // []}; | ||
| 675 | for my $version (@versions) { | ||
| 676 | my $path = "/api/$version"; | ||
| 677 | my $response = $self->_request('GET', $path); | ||
| 678 | next unless $self->_legacy_resource_list_ok($response, $version, $path); | ||
| 679 | my $list = $self->_json->decode($response->content); | ||
| 680 | $self->_absorb_api_resource_list($catalog, '', $version, $list); | ||
| 681 | } | ||
| 682 | $catalog->{groups}{''}{preferred} = $versions[0] | ||
| 683 | if @versions && exists $catalog->{groups}{''}; | ||
| 684 | } | ||
| 685 | |||
| 686 | # Legacy fallback for GET /apis: an APIGroupList document. Each group/version's | ||
| 687 | # APIResourceList is fetched from /apis/<group>/<version>. | ||
| 688 | sub _fetch_discovery_legacy_groups { | ||
| 689 | my ($self, $catalog, $body) = @_; | ||
| 690 | |||
| 691 | for my $group (@{$body->{groups} // []}) { | ||
| 692 | my $gname = $group->{name}; | ||
| 693 | next unless defined $gname && length $gname; | ||
| 694 | for my $v (@{$group->{versions} // []}) { | ||
| 695 | my $version = $v->{version}; | ||
| 696 | next unless defined $version && length $version; | ||
| 697 | my $path = "/apis/$gname/$version"; | ||
| 698 | my $response = $self->_request('GET', $path); | ||
| 699 | next unless $self->_legacy_resource_list_ok($response, "$gname/$version", $path); | ||
| 700 | my $list = $self->_json->decode($response->content); | ||
| 701 | $self->_absorb_api_resource_list($catalog, $gname, $version, $list); | ||
| 702 | } | ||
| 703 | my $pref = $group->{preferredVersion}{version}; | ||
| 704 | $catalog->{groups}{$gname}{preferred} = $pref | ||
| 705 | if defined $pref && exists $catalog->{groups}{$gname}; | ||
| 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 | sub _legacy_resource_list_ok { | ||
| 717 | my ($self, $response, $api_version, $path) = @_; | ||
| 718 | return 1 if $response->status < 400; | ||
| 719 | return 0 if $response->status == 404; | ||
| 720 | eval { $self->_check_response($response, "discovery GET $path") }; | ||
| 721 | $self->_carp_past_builders("discovery: cannot read apiVersion '$api_version'," | ||
| 722 | . ' its Kinds are missing from the resource map: ' . $self->_error_reason($@)); | ||
| 723 | 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 | sub _absorb_api_resource_list { | ||
| 730 | my ($self, $catalog, $group, $version, $list) = @_; | ||
| 731 | |||
| 732 | for my $res (@{$list->{resources} // []}) { | ||
| 733 | my $name = $res->{name}; | ||
| 734 | next unless defined $name && length $name; | ||
| 735 | next if $name =~ m{/}; | ||
| 736 | my $kind = $res->{kind}; | ||
| 737 | next unless defined $kind; | ||
| 738 | my $scope = $res->{namespaced} ? 'Namespaced' : 'Cluster'; | ||
| 739 | $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 | sub _catalog_add { | ||
| 746 | my ($self, $catalog, $group, $version, $kind, $plural, $scope) = @_; | ||
| 747 | |||
| 748 | my $gdata = $catalog->{groups}{$group} ||= { | ||
| 749 | preferred => undef, version_order => [], versions => {}, | ||
| 750 | }; | ||
| 751 | unless (exists $gdata->{versions}{$version}) { | ||
| 752 | $gdata->{versions}{$version} = { kinds => {} }; | ||
| 753 | push @{$gdata->{version_order}}, $version; | ||
| 754 | } | ||
| 755 | $gdata->{versions}{$version}{kinds}{$kind} = { | ||
| 756 | resource => $plural, | ||
| 757 | scope => $scope, | ||
| 758 | }; | ||
| 759 | } | ||
| 760 | |||
| 761 | sub invalidate_discovery { | ||
| 762 | my ($self) = @_; | ||
| 763 | |||
| 764 | |||
| 765 | $self->_clear_discovery; | ||
| 766 | $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 | if ($self->_has_resource_map && $self->_resource_map_built) { | ||
| 772 | $self->_clear_resource_map; | ||
| 773 | $self->_clear_k8s if $self->_has_k8s; | ||
| 774 | } | ||
| 775 | return 1; | ||
| 776 | } | ||
| 777 | |||
| 778 | sub prepare_discovery_requests { | ||
| 779 | my ($self) = @_; | ||
| 780 | |||
| 781 | |||
| 782 | return map { ($_ => $self->_discovery_request($_)) } @DISCOVERY_ROOTS; | ||
| 783 | } | ||
| 784 | |||
| 785 | sub absorb_discovery { | ||
| 786 | my ($self, %responses) = @_; | ||
| 787 | |||
| 788 | |||
| 789 | $self->_croak_unknown_args('absorb_discovery', \%responses, @DISCOVERY_ROOTS); | ||
| 790 | my @lists; | ||
| 791 | for my $root (@DISCOVERY_ROOTS) { | ||
| 792 | my $response = $responses{$root} | ||
| 793 | or croak "absorb_discovery requires the response for $root"; | ||
| 794 | my ($body, $aggregated) = $self->_discovery_document($root, $response); | ||
| 795 | push @lists, $aggregated ? $body : undef; | ||
| 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 | return if grep { !defined } @lists; | ||
| 801 | |||
| 802 | my $catalog = { groups => {} }; | ||
| 803 | $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 | if ($self->_has_resource_map && $self->_resource_map_built) { | ||
| 809 | $self->_clear_resource_map; | ||
| 810 | $self->_clear_k8s if $self->_has_k8s; | ||
| 811 | } | ||
| 812 | $self->_clear_discovery_error; | ||
| 813 | $self->_set_discovery($catalog); | ||
| 814 | 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 | 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 | sub _fetch_openapi_spec { | ||
| 833 | my ($self) = @_; | ||
| 834 | my $response = $self->_request('GET', '/openapi/v2'); | ||
| 835 | $self->_check_response($response, 'fetch OpenAPI spec'); | ||
| 836 | my $spec = $self->_json->decode($response->content); | ||
| 837 | $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 | $self->_clear_k8s if $self->_has_k8s; | ||
| 843 | 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 | sub schema_for { | ||
| 849 | my ($self, $kind) = @_; | ||
| 850 | |||
| 851 | |||
| 852 | my $spec = $self->_has_openapi_spec ? $self->_openapi_spec : $self->_fetch_openapi_spec; | ||
| 853 | my $defs = $spec->{definitions} // {}; | ||
| 854 | |||
| 855 | # If it's already an OpenAPI definition name | ||
| 856 | if (exists $defs->{$kind}) { | ||
| 857 | 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 | my $class = $self->expand_class($kind); | ||
| 865 | return unless defined $class; | ||
| 866 | # IO::K8s::Api::Core::V1::Pod -> io.k8s.api.core.v1.Pod | ||
| 867 | my $def_name = $class; | ||
| 868 | $def_name =~ s/^IO::K8s:://; | ||
| 869 | $def_name =~ s/::/./g; | ||
| 870 | $def_name = 'io.k8s.' . $def_name; | ||
| 871 | # Lowercase all path components except the final type name | ||
| 872 | my @parts = split /\./, $def_name; | ||
| 873 | $parts[$_] = lc($parts[$_]) for 0 .. $#parts - 1; | ||
| 874 | $def_name = join '.', @parts; | ||
| 875 | return $defs->{$def_name} if exists $defs->{$def_name}; | ||
| 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 | my ($api_version, $gvk_kind) = $self->_schema_gvk($class, $kind); | ||
| 885 | return unless defined $api_version; | ||
| 886 | my ($group, $version) = $api_version =~ m{/} | ||
| 887 | ? split(m{/}, $api_version, 2) | ||
| 888 | : ('', $api_version); | ||
| 889 | for my $name (sort keys %$defs) { | ||
| 890 | my $gvks = ref $defs->{$name} eq 'HASH' | ||
| 891 | ? $defs->{$name}{'x-kubernetes-group-version-kind'} : undef; | ||
| 892 | next unless ref $gvks eq 'ARRAY'; | ||
| 893 | for my $gvk (grep { ref $_ eq 'HASH' } @$gvks) { | ||
| 894 | return $defs->{$name} | ||
| 895 | if ($gvk->{group} // '') eq $group | ||
| 896 | && ($gvk->{version} // '') eq $version | ||
| 897 | && ($gvk->{kind} // '') eq $gvk_kind; | ||
| 898 | } | ||
| 899 | } | ||
| 900 | 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 | sub _schema_gvk { | ||
| 909 | my ($self, $class, $name) = @_; | ||
| 910 | if ($class eq 'IO::K8s::Unstructured') { | ||
| 911 | my ($kind, $api_version) = $self->_kind_from_expand_args($name); | ||
| 912 | return unless defined $kind; | ||
| 913 | my $meta = $self->_discovery_path_meta($kind, $api_version) or return; | ||
| 914 | return ($meta->{api_version}, $kind); | ||
| 915 | } | ||
| 916 | return unless eval { require_module($class); 1 } && $class->can('api_version'); | ||
| 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 | my $api_version = eval { $class->api_version }; | ||
| 920 | return unless defined $api_version && length $api_version; | ||
| 921 | my $kind = $class->can('kind') ? eval { $class->kind } : undef; | ||
| 922 | ($kind = $class) =~ s/.*::// unless defined $kind && length $kind; | ||
| 923 | 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 | sub compare_schema { | ||
| 929 | my ($self, $kind) = @_; | ||
| 930 | |||
| 931 | |||
| 932 | 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 | croak "compare_schema: '$kind' resolves to IO::K8s::Unstructured, which has" | ||
| 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 | require_module($class); | ||
| 942 | |||
| 943 | my $schema = $self->schema_for($kind); | ||
| 944 | croak "Schema not found for $kind" unless $schema; | ||
| 945 | |||
| 946 | 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 | sub _load_resource_map_from_cluster { | ||
| 954 | my ($self) = @_; | ||
| 955 | my $map = eval { $self->fetch_resource_map }; | ||
| 956 | if ($@) { | ||
| 957 | $self->_carp_past_builders('Falling back to the built-in resource map: ' | ||
| 958 | . $self->_error_reason($@)); | ||
| 959 | return IO::K8s->default_resource_map; | ||
| 960 | } | ||
| 961 | 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 | sub _v0_group { | ||
| 973 | my ($group, $self) = @_; | ||
| 974 | my $class = "Kubernetes::REST::$group"; | ||
| 975 | require_module($class); | ||
| 976 | return $class unless defined $self; | ||
| 977 | return $class->new(api => $self); | ||
| 978 | } | ||
| 979 | |||
| 980 | sub Core { _v0_group('Core', @_) } | ||
| 981 | sub Apps { _v0_group('Apps', @_) } | ||
| 982 | sub Batch { _v0_group('Batch', @_) } | ||
| 983 | sub Networking { _v0_group('Networking', @_) } | ||
| 984 | sub Storage { _v0_group('Storage', @_) } | ||
| 985 | sub Policy { _v0_group('Policy', @_) } | ||
| 986 | sub Autoscaling { _v0_group('Autoscaling', @_) } | ||
| 987 | sub RbacAuthorization { _v0_group('RbacAuthorization', @_) } | ||
| 988 | sub Certificates { _v0_group('Certificates', @_) } | ||
| 989 | sub Coordination { _v0_group('Coordination', @_) } | ||
| 990 | sub Events { _v0_group('Events', @_) } | ||
| 991 | sub Scheduling { _v0_group('Scheduling', @_) } | ||
| 992 | sub Authentication { _v0_group('Authentication', @_) } | ||
| 993 | sub Authorization { _v0_group('Authorization', @_) } | ||
| 994 | sub Admissionregistration { _v0_group('Admissionregistration', @_) } | ||
| 995 | sub Apiextensions { _v0_group('Apiextensions', @_) } | ||
| 996 | sub Apiregistration { _v0_group('Apiregistration', @_) } | ||
| 997 | |||
| 998 | # Build URL path from class metadata | ||
| 999 | sub _build_path { | ||
| 1000 | my ($self, $class, %args) = @_; | ||
| 1001 | |||
| 1002 | 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 | my ($api_version, $resource, $is_namespaced); | ||
| 1012 | my ($kind_hint, $av_hint) = (delete $args{kind}, delete $args{api_version}); | ||
| 1013 | my $override_resource = delete $args{resource}; | ||
| 1014 | my $override_namespaced = delete $args{namespaced}; | ||
| 1015 | if ($class eq 'IO::K8s::Unstructured') { | ||
| 1016 | if (defined $override_resource && defined $override_namespaced | ||
| 1017 | && defined $av_hint) { | ||
| 1018 | ($api_version, $resource, $is_namespaced) = | ||
| 1019 | ($av_hint, $override_resource, $override_namespaced); | ||
| 1020 | } else { | ||
| 1021 | defined $kind_hint | ||
| 1022 | or croak "IO::K8s::Unstructured needs a Kind to build a path" | ||
| 1023 | . " (pass kind => 'Kind')"; | ||
| 1024 | my $meta = $self->_discovery_path_meta($kind_hint, $av_hint); | ||
| 1025 | unless ($meta) { | ||
| 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 | my $reason = $self->_discovery_error; | ||
| 1033 | $reason = $self->_error_reason($reason) if defined $reason; | ||
| 1034 | my $gvk = "Kind '$kind_hint'" | ||
| 1035 | . (defined $av_hint && length $av_hint | ||
| 1036 | ? " in apiVersion '$av_hint'" : ''); | ||
| 1037 | croak defined $reason | ||
| 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 | @{$meta}{qw(api_version resource namespaced)}; | ||
| 1046 | } | ||
| 1047 | } else { | ||
| 1048 | # Get metadata from class | ||
| 1049 | $api_version = $class->can('api_version') ? $class->api_version : undef; | ||
| 1050 | croak "Cannot determine api_version for $class - override api_version() in your CRD class" | ||
| 1051 | unless defined $api_version; | ||
| 1052 | my $kind = $class->can('kind') ? $class->kind : (split('::', $class))[-1]; | ||
| 1053 | $is_namespaced = $class->does('IO::K8s::Role::Namespaced'); | ||
| 1054 | |||
| 1055 | # Use explicit resource_plural if available, otherwise auto-pluralize | ||
| 1056 | if ($class->can('resource_plural') && $class->resource_plural) { | ||
| 1057 | $resource = $class->resource_plural; | ||
| 1058 | } else { | ||
| 1059 | $resource = lc($kind); | ||
| 1060 | if ($resource =~ /(?:ss|sh|ch|x|z)$/) { | ||
| 1061 | $resource .= 'es'; # class -> classes, ingress -> ingresses | ||
| 1062 | } elsif ($resource =~ /[^aeiou]y$/) { | ||
| 1063 | $resource =~ s/y$/ies/; # policy -> policies | ||
| 1064 | } elsif ($resource !~ /s$/) { | ||
| 1065 | $resource .= 's'; # pod -> pods | ||
| 1066 | } | ||
| 1067 | } | ||
| 1068 | } | ||
| 1069 | |||
| 1070 | # Build path based on API group | ||
| 1071 | my $path; | ||
| 1072 | if ($api_version =~ m{/}) { | ||
| 1073 | # Has group: apps/v1 -> /apis/apps/v1/... | ||
| 1074 | $path = "/apis/$api_version"; | ||
| 1075 | } else { | ||
| 1076 | # Core: v1 -> /api/v1/... | ||
| 1077 | $path = "/api/$api_version"; | ||
| 1078 | } | ||
| 1079 | |||
| 1080 | if ($is_namespaced && $args{namespace}) { | ||
| 1081 | $path .= "/namespaces/$args{namespace}"; | ||
| 1082 | } | ||
| 1083 | |||
| 1084 | $path .= "/$resource"; | ||
| 1085 | |||
| 1086 | if ($args{name}) { | ||
| 1087 | $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 | if (defined $args{subresource} && length $args{subresource}) { | ||
| 1094 | croak "subresource '$args{subresource}' requires a name for $class" | ||
| 1095 | unless $args{name}; | ||
| 1096 | $path .= "/$args{subresource}"; | ||
| 1097 | } | ||
| 1098 | |||
| 1099 | 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 | sub _prepare_request { | ||
| 1116 | my ($self, $method, $path, %opts) = @_; | ||
| 1117 | |||
| 1118 | my $url = $self->server->endpoint . $path; | ||
| 1119 | my $content_type = $opts{content_type} // 'application/json'; | ||
| 1120 | my $body = $opts{body}; | ||
| 1121 | my $parameters = $opts{parameters}; | ||
| 1122 | my $extra_headers = $opts{headers} // {}; | ||
| 1123 | |||
| 1124 | # Append query parameters to URL, keys and values through _query_escape | ||
| 1125 | if ($parameters && %$parameters) { | ||
| 1126 | my @pairs; | ||
| 1127 | for my $key (sort keys %$parameters) { | ||
| 1128 | my $val = $parameters->{$key}; | ||
| 1129 | next unless defined $val; | ||
| 1130 | my $k = $self->_query_escape($key); | ||
| 1131 | if (ref($val) eq 'ARRAY') { | ||
| 1132 | push @pairs, map { "$k=" . $self->_query_escape($_) } grep { defined } @$val; | ||
| 1133 | } else { | ||
| 1134 | push @pairs, "$k=" . $self->_query_escape($val); | ||
| 1135 | } | ||
| 1136 | } | ||
| 1137 | if (@pairs) { | ||
| 1138 | $url .= ($url =~ /\?/ ? '&' : '?') . join('&', @pairs); | ||
| 1139 | } | ||
| 1140 | } | ||
| 1141 | |||
| 1142 | 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 | my $token = $self->credentials->token; | ||
| 1150 | if (defined $token && length $token) { | ||
| 1151 | $headers{'Authorization'} = 'Bearer ' . $token; | ||
| 1152 | } | ||
| 1153 | if ($extra_headers && ref($extra_headers) eq 'HASH') { | ||
| 1154 | @headers{keys %$extra_headers} = values %$extra_headers; | ||
| 1155 | } | ||
| 1156 | |||
| 1157 | return Kubernetes::REST::HTTPRequest->new( | ||
| 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 | sub _query_escape { | ||
| 1180 | my ($self, $string) = @_; | ||
| 1181 | my $bytes = Encode::encode('UTF-8', "$string"); | ||
| 1182 | $bytes =~ s/([\x00-\x20\x7F-\xFF%&+#;])/sprintf('%%%02X', ord $1)/ge; | ||
| 1183 | return $bytes; | ||
| 1184 | } | ||
| 1185 | |||
| 1186 | sub _check_response { | ||
| 1187 | my ($self, $response, $context) = @_; | ||
| 1188 | if ($response->status >= 400) { | ||
| 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 | my $body = Encode::decode('UTF-8', $response->content // '', Encode::FB_DEFAULT); | ||
| 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 | Kubernetes::REST::APIError->throw( | ||
| 1197 | code => 0 + $response->status, | ||
| 1198 | body => $body, | ||
| 1199 | context => $context, | ||
| 1200 | response => $response, | ||
| 1201 | ); | ||
| 1202 | } | ||
| 1203 | 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 | sub _exact_class { | ||
| 1217 | my ($self, $class) = @_; | ||
| 1218 | return "+$class" | ||
| 1219 | if defined $class && !ref $class && length $class && $class !~ /\A\+/ | ||
| 1220 | && $class->can('does') && $class->does('IO::K8s::Role::Resource'); | ||
| 1221 | return $class; | ||
| 1222 | } | ||
| 1223 | |||
| 1224 | sub _inflate_object { | ||
| 1225 | my ($self, $class, $response) = @_; | ||
| 1226 | return $self->k8s->json_to_object($self->_exact_class($class), $response->content); | ||
| 1227 | } | ||
| 1228 | |||
| 1229 | sub _inflate_list { | ||
| 1230 | my ($self, $class, $response) = @_; | ||
| 1231 | my $struct = $self->_json->decode($response->content); | ||
| 1232 | my $items = $struct->{items} // []; | ||
| 1233 | my $exact_class = $self->_exact_class($class); | ||
| 1234 | my (@objects, @dropped); | ||
| 1235 | for my $i (0 .. $#$items) { | ||
| 1236 | my $item = $items->[$i]; | ||
| 1237 | my $obj = eval { $self->k8s->struct_to_object($exact_class, $item) }; | ||
| 1238 | if (defined $obj) { | ||
| 1239 | push @objects, $obj; | ||
| 1240 | 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 | my $err = $@ || 'inflated to undef'; | ||
| 1248 | $err =~ s/\s+\z//; | ||
| 1249 | my $name = ref $item eq 'HASH' && ref $item->{metadata} eq 'HASH' | ||
| 1250 | ? $item->{metadata}{name} | ||
| 1251 | : undef; | ||
| 1252 | push @dropped, | ||
| 1253 | "item $i" . (defined $name ? " (name '$name')" : '') . ": $err"; | ||
| 1254 | } | ||
| 1255 | if (@dropped) { | ||
| 1256 | 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 | return IO::K8s::List->new(items => \@objects, item_class => $class); | ||
| 1262 | } | ||
| 1263 | |||
| 1264 | sub _process_watch_chunk { | ||
| 1265 | my ($self, $class, $buffer_ref, $chunk) = @_; | ||
| 1266 | $$buffer_ref .= $chunk; | ||
| 1267 | |||
| 1268 | my $exact_class = $self->_exact_class($class); | ||
| 1269 | my @events; | ||
| 1270 | while ($$buffer_ref =~ s/^([^\n]*)\n//) { | ||
| 1271 | my $line = $1; | ||
| 1272 | next unless length $line; | ||
| 1273 | |||
| 1274 | my $data = eval { $self->_json->decode($line) }; | ||
| 1275 | next unless $data; | ||
| 1276 | |||
| 1277 | my $type = $data->{type} // ''; | ||
| 1278 | my $raw_object = $data->{object} // {}; | ||
| 1279 | |||
| 1280 | # Track resourceVersion for resumability | ||
| 1281 | my $rv; | ||
| 1282 | if ($raw_object->{metadata} && $raw_object->{metadata}{resourceVersion}) { | ||
| 1283 | $rv = $raw_object->{metadata}{resourceVersion}; | ||
| 1284 | } | ||
| 1285 | |||
| 1286 | # Inflate the object (ERROR events stay as hashrefs) | ||
| 1287 | my $object; | ||
| 1288 | if ($type eq 'ERROR') { | ||
| 1289 | $object = $raw_object; | ||
| 1290 | } else { | ||
| 1291 | $object = eval { $self->k8s->struct_to_object($exact_class, $raw_object) } | ||
| 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 | error_code => ($type eq 'ERROR' ? ($raw_object->{code} // 0) : 0), | ||
| 1304 | }; | ||
| 1305 | } | ||
| 1306 | |||
| 1307 | return @events; | ||
| 1308 | } | ||
| 1309 | |||
| 1310 | sub _process_log_chunk { | ||
| 1311 | my ($self, $buffer_ref, $chunk) = @_; | ||
| 1312 | $$buffer_ref .= $chunk; | ||
| 1313 | |||
| 1314 | my @events; | ||
| 1315 | while ($$buffer_ref =~ s/^([^\n]*)\n//) { | ||
| 1316 | my $line = $1; | ||
| 1317 | push @events, Kubernetes::REST::LogEvent->new(line => $line); | ||
| 1318 | } | ||
| 1319 | |||
| 1320 | 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 | sub build_path { | ||
| 1333 | my ($self, @args) = @_; | ||
| 1334 | |||
| 1335 | |||
| 1336 | return $self->_build_path(@args); | ||
| 1337 | } | ||
| 1338 | |||
| 1339 | sub prepare_request { | ||
| 1340 | my ($self, @args) = @_; | ||
| 1341 | |||
| 1342 | |||
| 1343 | return $self->_prepare_request(@args); | ||
| 1344 | } | ||
| 1345 | |||
| 1346 | sub check_response { | ||
| 1347 | my ($self, @args) = @_; | ||
| 1348 | |||
| 1349 | |||
| 1350 | return $self->_check_response(@args); | ||
| 1351 | } | ||
| 1352 | |||
| 1353 | sub inflate_object { | ||
| 1354 | my ($self, @args) = @_; | ||
| 1355 | |||
| 1356 | |||
| 1357 | return $self->_inflate_object(@args); | ||
| 1358 | } | ||
| 1359 | |||
| 1360 | sub inflate_list { | ||
| 1361 | my ($self, @args) = @_; | ||
| 1362 | |||
| 1363 | |||
| 1364 | return $self->_inflate_list(@args); | ||
| 1365 | } | ||
| 1366 | |||
| 1367 | sub process_watch_chunk { | ||
| 1368 | my ($self, @args) = @_; | ||
| 1369 | |||
| 1370 | |||
| 1371 | return $self->_process_watch_chunk(@args); | ||
| 1372 | } | ||
| 1373 | |||
| 1374 | sub process_log_chunk { | ||
| 1375 | my ($self, @args) = @_; | ||
| 1376 | |||
| 1377 | |||
| 1378 | return $self->_process_log_chunk(@args); | ||
| 1379 | } | ||
| 1380 | |||
| 1381 | # Convenience: prepare + call in one step (used by sync CRUD methods) | ||
| 1382 | sub _request { | ||
| 1383 | my ($self, $method, $path, $body, %opts) = @_; | ||
| 1384 | my $req = $self->_prepare_request($method, $path, | ||
| 1385 | body => $body, | ||
| 1386 | %opts, | ||
| 1387 | ); | ||
| 1388 | return $self->io->call($req); | ||
| 1389 | } | ||
| 1390 | |||
| 1391 | sub list { | ||
| 1392 | 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 | $self->_croak_unknown_args('list', \%args, qw(namespace labelSelector fieldSelector)); | ||
| 1399 | my ($class, $response) = $self->_list_request($short_class, %args); | ||
| 1400 | $self->_check_response($response, "list $short_class"); | ||
| 1401 | |||
| 1402 | 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 | sub _list_request { | ||
| 1410 | my ($self, $short_class, %args) = @_; | ||
| 1411 | |||
| 1412 | # Extract query parameters before building path | ||
| 1413 | my $label_selector = delete $args{labelSelector}; | ||
| 1414 | my $field_selector = delete $args{fieldSelector}; | ||
| 1415 | |||
| 1416 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 1417 | my $path = $self->_build_path($class, %args, | ||
| 1418 | $self->_unstructured_hint($class, $short_class)); | ||
| 1419 | |||
| 1420 | my %params; | ||
| 1421 | $params{labelSelector} = $label_selector if defined $label_selector; | ||
| 1422 | $params{fieldSelector} = $field_selector if defined $field_selector; | ||
| 1423 | |||
| 1424 | my $response = %params | ||
| 1425 | ? $self->_request('GET', $path, undef, parameters => \%params) | ||
| 1426 | : $self->_request('GET', $path); | ||
| 1427 | return ($class, $response); | ||
| 1428 | } | ||
| 1429 | |||
| 1430 | sub get { | ||
| 1431 | 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 | my %args; | ||
| 1438 | if (@rest == 1) { | ||
| 1439 | $args{name} = $rest[0]; | ||
| 1440 | } elsif (@rest >= 2 && $rest[0] !~ /^(name|namespace|subresource)$/) { | ||
| 1441 | # First arg is name, rest are key=value pairs | ||
| 1442 | $args{name} = shift @rest; | ||
| 1443 | %args = (%args, @rest); | ||
| 1444 | } elsif (@rest % 2 == 0) { | ||
| 1445 | %args = @rest; | ||
| 1446 | } else { | ||
| 1447 | 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 | $self->_croak_unknown_args('get', \%args, qw(name namespace subresource)); | ||
| 1452 | |||
| 1453 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 1454 | croak "name required for get" unless $args{name}; | ||
| 1455 | |||
| 1456 | my $path = $self->_build_path($class, %args, | ||
| 1457 | $self->_unstructured_hint($class, $short_class)); | ||
| 1458 | my $response = $self->_request('GET', $path); | ||
| 1459 | $self->_check_response($response, "get $short_class"); | ||
| 1460 | |||
| 1461 | return $self->_inflate_object($class, $response); | ||
| 1462 | } | ||
| 1463 | |||
| 1464 | sub create { | ||
| 1465 | my ($self, $object) = @_; | ||
| 1466 | |||
| 1467 | |||
| 1468 | my ($class, $response) = $self->_create_request($object); | ||
| 1469 | $self->_check_response($response, "create $class"); | ||
| 1470 | |||
| 1471 | 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 | sub _create_request { | ||
| 1479 | my ($self, $object) = @_; | ||
| 1480 | |||
| 1481 | my $class = ref($object); | ||
| 1482 | my $namespace = $object->can('metadata') && $object->metadata | ||
| 1483 | ? $object->metadata->namespace | ||
| 1484 | : undef; | ||
| 1485 | |||
| 1486 | my $path = $self->_build_path($class, namespace => $namespace, | ||
| 1487 | $self->_unstructured_hint($class, $object)); | ||
| 1488 | return ($class, $self->_request('POST', $path, $object->TO_JSON)); | ||
| 1489 | } | ||
| 1490 | |||
| 1491 | sub update { | ||
| 1492 | my ($self, $object) = @_; | ||
| 1493 | |||
| 1494 | |||
| 1495 | my ($class, $response) = $self->_update_request($object); | ||
| 1496 | $self->_check_response($response, "update $class"); | ||
| 1497 | |||
| 1498 | 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 | sub _update_request { | ||
| 1504 | my ($self, $object) = @_; | ||
| 1505 | |||
| 1506 | my $class = ref($object); | ||
| 1507 | my $metadata = $object->metadata or croak "object must have metadata"; | ||
| 1508 | my $name = $metadata->name or croak "object must have metadata.name"; | ||
| 1509 | my $namespace = $metadata->namespace; | ||
| 1510 | |||
| 1511 | my $path = $self->_build_path($class, name => $name, namespace => $namespace, | ||
| 1512 | $self->_unstructured_hint($class, $object)); | ||
| 1513 | return ($class, $self->_request('PUT', $path, $object->TO_JSON)); | ||
| 1514 | } | ||
| 1515 | |||
| 1516 | 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 | sub _unpack_patch_args { | ||
| 1533 | my ($self, $label, $default_type, $class_or_object, @rest) = @_; | ||
| 1534 | |||
| 1535 | my ($class, $name, $namespace, $patch, $patch_type); | ||
| 1536 | |||
| 1537 | if (ref($class_or_object) && blessed($class_or_object)) { | ||
| 1538 | # Object passed: patch($object, patch => {...}) | ||
| 1539 | my $object = $class_or_object; | ||
| 1540 | my %args = @rest; | ||
| 1541 | $self->_croak_unknown_args($label, \%args, qw(patch type)); | ||
| 1542 | $class = ref($object); | ||
| 1543 | my $metadata = $object->metadata or croak "object must have metadata"; | ||
| 1544 | $name = $metadata->name or croak "object must have metadata.name"; | ||
| 1545 | $namespace = $metadata->namespace; | ||
| 1546 | $patch = $args{patch} // croak "$label requires 'patch' parameter"; | ||
| 1547 | $patch_type = $args{type} // $default_type; | ||
| 1548 | } else { | ||
| 1549 | # Class + name: patch('Pod', 'name', namespace => 'ns', patch => {...}) | ||
| 1550 | my %args; | ||
| 1551 | if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|patch|type)$/) { | ||
| 1552 | $args{name} = shift @rest; | ||
| 1553 | %args = (%args, @rest); | ||
| 1554 | } elsif (@rest % 2 == 0) { | ||
| 1555 | %args = @rest; | ||
| 1556 | } else { | ||
| 1557 | croak "Invalid arguments to $label()"; | ||
| 1558 | } | ||
| 1559 | $self->_croak_unknown_args($label, \%args, qw(name namespace patch type)); | ||
| 1560 | |||
| 1561 | $class = $self->_expand_class_or_croak($class_or_object); | ||
| 1562 | $name = $args{name} or croak "name required for $label"; | ||
| 1563 | $namespace = $args{namespace}; | ||
| 1564 | $patch = $args{patch} // croak "$label requires 'patch' parameter"; | ||
| 1565 | $patch_type = $args{type} // $default_type; | ||
| 1566 | } | ||
| 1567 | |||
| 1568 | my $content_type = $PATCH_TYPES{$patch_type} | ||
| 1569 | // croak "Unknown patch type '$patch_type' (use: strategic, merge, json)"; | ||
| 1570 | |||
| 1571 | return ($class, $name, $namespace, $patch, $content_type); | ||
| 1572 | } | ||
| 1573 | |||
| 1574 | sub patch { | ||
| 1575 | my ($self, $class_or_object, @rest) = @_; | ||
| 1576 | |||
| 1577 | |||
| 1578 | my ($class, $name, $namespace, $patch, $content_type) | ||
| 1579 | = $self->_unpack_patch_args('patch', 'strategic', $class_or_object, @rest); | ||
| 1580 | |||
| 1581 | my $path = $self->_build_path($class, name => $name, namespace => $namespace, | ||
| 1582 | $self->_unstructured_hint($class, $class_or_object)); | ||
| 1583 | my $response = $self->_request('PATCH', $path, $patch, | ||
| 1584 | content_type => $content_type); | ||
| 1585 | $self->_check_response($response, "patch $class"); | ||
| 1586 | |||
| 1587 | return $self->_inflate_object($class, $response); | ||
| 1588 | } | ||
| 1589 | |||
| 1590 | sub patch_status { | ||
| 1591 | my ($self, $class_or_object, @rest) = @_; | ||
| 1592 | |||
| 1593 | |||
| 1594 | my ($class, $name, $namespace, $patch, $content_type) | ||
| 1595 | = $self->_unpack_patch_args('patch_status', 'merge', $class_or_object, @rest); | ||
| 1596 | |||
| 1597 | 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 | my $response = $self->_request('PATCH', $path, $patch, | ||
| 1604 | content_type => $content_type); | ||
| 1605 | $self->_check_response($response, "patch_status $class"); | ||
| 1606 | |||
| 1607 | return $self->_inflate_object($class, $response); | ||
| 1608 | } | ||
| 1609 | |||
| 1610 | sub update_status { | ||
| 1611 | my ($self, $object) = @_; | ||
| 1612 | |||
| 1613 | |||
| 1614 | my $class = ref($object); | ||
| 1615 | my $metadata = $object->metadata or croak "object must have metadata"; | ||
| 1616 | my $name = $metadata->name or croak "object must have metadata.name"; | ||
| 1617 | my $namespace = $metadata->namespace; | ||
| 1618 | |||
| 1619 | my $path = $self->_build_path($class, | ||
| 1620 | name => $name, | ||
| 1621 | namespace => $namespace, | ||
| 1622 | subresource => 'status', | ||
| 1623 | $self->_unstructured_hint($class, $object), | ||
| 1624 | ); | ||
| 1625 | my $response = $self->_request('PUT', $path, $object->TO_JSON); | ||
| 1626 | $self->_check_response($response, "update_status " . ref($object)); | ||
| 1627 | |||
| 1628 | return $self->_inflate_object($class, $response); | ||
| 1629 | } | ||
| 1630 | |||
| 1631 | sub delete { | ||
| 1632 | my ($self, $class_or_object, @rest) = @_; | ||
| 1633 | |||
| 1634 | |||
| 1635 | my ($class, $response) = $self->_delete_request($class_or_object, @rest); | ||
| 1636 | $self->_check_response($response, "delete $class"); | ||
| 1637 | |||
| 1638 | 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 | sub _delete_request { | ||
| 1650 | my ($self, $class_or_object, @rest) = @_; | ||
| 1651 | |||
| 1652 | my ($class, $name, $namespace, %args); | ||
| 1653 | |||
| 1654 | if (ref($class_or_object)) { | ||
| 1655 | # Object passed: delete($object), delete($object, propagationPolicy => ...) | ||
| 1656 | my $object = $class_or_object; | ||
| 1657 | croak "Invalid arguments to delete()" if @rest % 2; | ||
| 1658 | %args = @rest; | ||
| 1659 | $self->_croak_unknown_args('delete', \%args, 'propagationPolicy'); | ||
| 1660 | $self->_propagation_policy_or_croak('delete', $args{propagationPolicy}); | ||
| 1661 | $class = ref($object); | ||
| 1662 | my $metadata = $object->metadata or croak "object must have metadata"; | ||
| 1663 | $name = $metadata->name or croak "object must have metadata.name"; | ||
| 1664 | $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 | if (@rest == 1) { | ||
| 1670 | $args{name} = $rest[0]; | ||
| 1671 | } elsif (@rest >= 2 && $rest[0] !~ /^(name|namespace|propagationPolicy)$/) { | ||
| 1672 | # First arg is name, rest are key=value pairs | ||
| 1673 | $args{name} = shift @rest; | ||
| 1674 | %args = (%args, @rest); | ||
| 1675 | } elsif (@rest % 2 == 0) { | ||
| 1676 | %args = @rest; | ||
| 1677 | } else { | ||
| 1678 | croak "Invalid arguments to delete()"; | ||
| 1679 | } | ||
| 1680 | $self->_croak_unknown_args('delete', \%args, | ||
| 1681 | qw(name namespace propagationPolicy)); | ||
| 1682 | $self->_propagation_policy_or_croak('delete', $args{propagationPolicy}); | ||
| 1683 | |||
| 1684 | $class = $self->_expand_class_or_croak($class_or_object); | ||
| 1685 | $name = $args{name} or croak "name required for delete"; | ||
| 1686 | $namespace = $args{namespace}; | ||
| 1687 | } | ||
| 1688 | |||
| 1689 | my $path = $self->_build_path($class, name => $name, namespace => $namespace, | ||
| 1690 | $self->_unstructured_hint($class, $class_or_object)); | ||
| 1691 | my $policy = $args{propagationPolicy}; | ||
| 1692 | return ($class, defined $policy | ||
| 1693 | ? $self->_request('DELETE', $path, undef, | ||
| 1694 | parameters => { propagationPolicy => $policy }) | ||
| 1695 | : $self->_request('DELETE', $path)); | ||
| 1696 | } | ||
| 1697 | |||
| 1698 | # The propagationPolicy values DeleteOptions takes. | ||
| 1699 | 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 | sub _propagation_policy_or_croak { | ||
| 1704 | my ($self, $label, $policy) = @_; | ||
| 1705 | return $policy if !defined $policy || grep { $_ eq $policy } @PROPAGATION_POLICIES; | ||
| 1706 | 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 | sub _croak_unknown_args { | ||
| 1713 | my ($self, $label, $args, @allowed) = @_; | ||
| 1714 | my %allowed = map { $_ => 1 } @allowed; | ||
| 1715 | my ($unknown) = sort grep { !$allowed{$_} } keys %$args; | ||
| 1716 | return unless defined $unknown; | ||
| 1717 | 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 | sub _manifest_to_object { | ||
| 1735 | my ($self, $label, $manifest) = @_; | ||
| 1736 | my $kind = $manifest->{kind} or croak "$label: hashref must have 'kind'"; | ||
| 1737 | my $api_version = $manifest->{apiVersion}; | ||
| 1738 | |||
| 1739 | return $self->k8s->struct_to_object('+' . $self->_expand_class_or_croak($kind), $manifest) | ||
| 1740 | unless defined $api_version && length $api_version; | ||
| 1741 | |||
| 1742 | my $class = $self->expand_class($kind, $api_version) | ||
| 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 | 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 | sub _api_version_and_kind { | ||
| 1755 | my ($self, $object) = @_; | ||
| 1756 | my $api_version = ref($object) eq 'IO::K8s::Unstructured' ? $object->apiVersion | ||
| 1757 | : $object->can('api_version') ? $object->api_version | ||
| 1758 | : undef; | ||
| 1759 | my $kind = $object->can('kind') ? $object->kind : undef; | ||
| 1760 | ($kind = ref $object) =~ s/.*::// unless defined $kind; | ||
| 1761 | return ($api_version // '', $kind); | ||
| 1762 | } | ||
| 1763 | |||
| 1764 | sub ensure { | ||
| 1765 | 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 | croak 'Invalid arguments to ensure(): it takes one object or hashref' | ||
| 1771 | . ' (ensure_all takes several)' | ||
| 1772 | if @extra; | ||
| 1773 | $object = $self->_manifest_to_object('ensure', $object) if ref($object) eq 'HASH'; | ||
| 1774 | |||
| 1775 | my $class = ref($object); | ||
| 1776 | croak "ensure requires an IO::K8s object or hashref" unless blessed($object); | ||
| 1777 | 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 | my $is_pvc = $api_version eq 'v1' && $kind eq 'PersistentVolumeClaim'; | ||
| 1784 | my $is_job = $api_version eq 'batch/v1' && $kind eq 'Job'; | ||
| 1785 | my $metadata = $object->metadata or croak "object must have metadata"; | ||
| 1786 | my $name = $metadata->name or croak "object must have metadata.name"; | ||
| 1787 | my $namespace = $metadata->namespace; | ||
| 1788 | |||
| 1789 | my @unstructured_hint = $self->_unstructured_hint($class, $object); | ||
| 1790 | 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 | my $existing; | ||
| 1797 | my $response = $self->_request('GET', $path); | ||
| 1798 | unless ($response->status == 404) { | ||
| 1799 | $self->_check_response($response, "ensure get $kind/$name"); | ||
| 1800 | $existing = $self->_inflate_object($class, $response); | ||
| 1801 | } | ||
| 1802 | |||
| 1803 | unless ($existing) { | ||
| 1804 | (undef, $response) = $self->_create_request($object); | ||
| 1805 | unless ($response->status == 409) { | ||
| 1806 | $self->_check_response($response, "create $class"); | ||
| 1807 | 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 | $response = $self->_request('GET', $path); | ||
| 1813 | $self->_check_response($response, "ensure post-409 get $kind/$name"); | ||
| 1814 | $existing = $self->_inflate_object($class, $response); | ||
| 1815 | } | ||
| 1816 | |||
| 1817 | return $existing if $is_pvc; | ||
| 1818 | if ($is_job) { | ||
| 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 | my $status = $existing->TO_JSON->{status} || {}; | ||
| 1822 | return $existing if $status->{succeeded} || $status->{active}; | ||
| 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 | eval { $self->delete($existing, propagationPolicy => 'Background') }; | ||
| 1827 | return $self->create($object); | ||
| 1828 | } | ||
| 1829 | $object->metadata->resourceVersion($existing->metadata->resourceVersion); | ||
| 1830 | (undef, $response) = $self->_update_request($object); | ||
| 1831 | unless ($response->status == 409) { | ||
| 1832 | $self->_check_response($response, "update $class"); | ||
| 1833 | 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 | $response = $self->_request('GET', $path); | ||
| 1838 | $self->_check_response($response, "ensure refetch $kind/$name"); | ||
| 1839 | $existing = $self->_inflate_object($class, $response); | ||
| 1840 | $object->metadata->resourceVersion($existing->metadata->resourceVersion); | ||
| 1841 | return $self->update($object); | ||
| 1842 | } | ||
| 1843 | |||
| 1844 | sub ensure_all { | ||
| 1845 | my ($self, @objects) = @_; | ||
| 1846 | |||
| 1847 | |||
| 1848 | return map { $self->ensure($_) } @objects; | ||
| 1849 | } | ||
| 1850 | |||
| 1851 | sub ensure_only { | ||
| 1852 | 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 | $self->_croak_unknown_args('ensure_only', \%args, | ||
| 1859 | qw(label objects kinds namespaces propagationPolicy)); | ||
| 1860 | my $label = $args{label} or croak "ensure_only requires 'label'"; | ||
| 1861 | my @objects = @{$args{objects} || []}; | ||
| 1862 | my @kinds = @{$args{kinds} || []}; | ||
| 1863 | my @namespaces = @{$args{namespaces} || [undef]}; | ||
| 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 | $args{propagationPolicy} // 'Background'); | ||
| 1868 | |||
| 1869 | for my $obj (@objects) { | ||
| 1870 | $obj = $self->_manifest_to_object('ensure_only', $obj) if ref($obj) eq 'HASH'; | ||
| 1871 | } | ||
| 1872 | |||
| 1873 | 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 | my $key_of = sub { | ||
| 1884 | my ($obj) = @_; | ||
| 1885 | my ($api_version, $kind) = $self->_api_version_and_kind($obj); | ||
| 1886 | my ($group) = $api_version =~ m{\A(.*)/[^/]*\z}; | ||
| 1887 | my $metadata = $obj->metadata; | ||
| 1888 | return join("\0", $group // '', $kind, $metadata->namespace // '', $metadata->name); | ||
| 1889 | }; | ||
| 1890 | 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 | my $where = sub { | ||
| 1899 | my ($ns) = @_; | ||
| 1900 | return defined $ns ? "in namespace '$ns'" : 'at cluster scope'; | ||
| 1901 | }; | ||
| 1902 | my $reason_of = sub { | ||
| 1903 | my ($error) = @_; | ||
| 1904 | $error =~ s/\s+\z//; | ||
| 1905 | $error =~ s/ at \S+ line \d+\.\z//; | ||
| 1906 | return $error; | ||
| 1907 | }; | ||
| 1908 | |||
| 1909 | for my $kind (@kinds) { | ||
| 1910 | for my $ns (@namespaces) { | ||
| 1911 | my %list_args = (labelSelector => $label); | ||
| 1912 | $list_args{namespace} = $ns if defined $ns; | ||
| 1913 | my $list = eval { | ||
| 1914 | my ($class, $response) = $self->_list_request($kind, %list_args); | ||
| 1915 | return if $response->status == 404; | ||
| 1916 | $self->_check_response($response, "list $kind"); | ||
| 1917 | $self->_inflate_list($class, $response); | ||
| 1918 | }; | ||
| 1919 | unless ($list) { | ||
| 1920 | carp "ensure_only: cannot list $kind " . $where->($ns) | ||
| 1921 | . ', nothing pruned there: ' . $reason_of->($@) | ||
| 1922 | if $@; | ||
| 1923 | next; | ||
| 1924 | } | ||
| 1925 | for my $item (@{$list->items}) { | ||
| 1926 | next if $expected{ $key_of->($item) }; | ||
| 1927 | next if eval { | ||
| 1928 | my ($class, $response) = $self->_delete_request($item, | ||
| 1929 | propagationPolicy => $propagation); | ||
| 1930 | $response->status == 404 | ||
| 1931 | || $self->_check_response($response, "delete $class"); | ||
| 1932 | }; | ||
| 1933 | my (undef, $item_kind) = $self->_api_version_and_kind($item); | ||
| 1934 | carp "ensure_only: cannot delete $item_kind '" . $item->metadata->name | ||
| 1935 | . "' " . $where->($item->metadata->namespace) | ||
| 1936 | . ': ' . $reason_of->($@); | ||
| 1937 | } | ||
| 1938 | } | ||
| 1939 | } | ||
| 1940 | |||
| 1941 | return @results; | ||
| 1942 | } | ||
| 1943 | |||
| 1944 | sub ensure_crd { | ||
| 1945 | my $self = shift; | ||
| 1946 | |||
| 1947 | |||
| 1948 | my (@classes, %opts); | ||
| 1949 | if (@_ && ref $_[0] eq 'ARRAY') { | ||
| 1950 | @classes = @{ shift() }; | ||
| 1951 | %opts = @_; | ||
| 1952 | } else { | ||
| 1953 | @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 | $self->_croak_unknown_args('ensure_crd', \%opts, qw(timeout poll_interval storage)); | ||
| 1958 | croak "ensure_crd requires at least one CRD class" unless @classes; | ||
| 1959 | |||
| 1960 | 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 | my (@order, %group); | ||
| 1965 | for my $class (@classes) { | ||
| 1966 | my $single = $class->to_crd; | ||
| 1967 | my $crd_name = $single->metadata->name; | ||
| 1968 | push @order, $crd_name unless exists $group{$crd_name}; | ||
| 1969 | push @{ $group{$crd_name} }, { class => $class, single => $single }; | ||
| 1970 | } | ||
| 1971 | |||
| 1972 | my @crds; | ||
| 1973 | for my $crd_name (@order) { | ||
| 1974 | my $members = $group{$crd_name}; | ||
| 1975 | if (@$members == 1) { | ||
| 1976 | push @crds, $members->[0]{single}; | ||
| 1977 | 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 | my @version_classes = map { $_->{class} } @$members; | ||
| 1982 | my @versions = map { $_->{single}->spec->versions->[0]->name } @$members; | ||
| 1983 | my $storage_version = | ||
| 1984 | !defined $storage ? undef | ||
| 1985 | : ref $storage eq 'HASH' ? $storage->{$crd_name} | ||
| 1986 | : $storage; | ||
| 1987 | croak "ensure_crd: '$crd_name' is defined by multiple classes (" | ||
| 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 | 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 | $self->ensure($_) for @crds; | ||
| 1999 | my @established = map { $self->_wait_crd_established($_, %opts) } @crds; | ||
| 2000 | $self->invalidate_discovery; | ||
| 2001 | 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 | sub _wait_crd_established { | ||
| 2011 | my ($self, $crd, %opts) = @_; | ||
| 2012 | |||
| 2013 | my $class = ref $crd; | ||
| 2014 | my $name = $crd->metadata->name; | ||
| 2015 | my $path = $self->_build_path($class, name => $name); | ||
| 2016 | my $timeout = defined $opts{timeout} ? $opts{timeout} : 30; | ||
| 2017 | my $interval = defined $opts{poll_interval} ? $opts{poll_interval} : 1; | ||
| 2018 | my $deadline = Time::HiRes::time() + $timeout; | ||
| 2019 | |||
| 2020 | while (1) { | ||
| 2021 | my $response = $self->_request('GET', $path); | ||
| 2022 | unless ($response->status == 404) { | ||
| 2023 | $self->_check_response($response, "ensure_crd wait $name"); | ||
| 2024 | my $current = $self->_inflate_object($class, $response); | ||
| 2025 | return $current if $current && $self->_crd_established($current); | ||
| 2026 | } | ||
| 2027 | last if Time::HiRes::time() >= $deadline; | ||
| 2028 | Time::HiRes::sleep($interval); | ||
| 2029 | } | ||
| 2030 | |||
| 2031 | 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 | sub _crd_established { | ||
| 2038 | my ($self, $crd) = @_; | ||
| 2039 | my $status = $crd->status or return 0; | ||
| 2040 | my $conditions = $status->conditions or return 0; | ||
| 2041 | for my $cond (@$conditions) { | ||
| 2042 | return 1 | ||
| 2043 | if ($cond->type // '') eq 'Established' | ||
| 2044 | && ($cond->status // '') eq 'True'; | ||
| 2045 | } | ||
| 2046 | return 0; | ||
| 2047 | } | ||
| 2048 | |||
| 2049 | sub watch { | ||
| 2050 | 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 | $self->_croak_unknown_args('watch', \%args, qw(on_event timeout | ||
| 2057 | resourceVersion labelSelector fieldSelector namespace)); | ||
| 2058 | my $on_event = delete $args{on_event} | ||
| 2059 | or croak "watch requires 'on_event' callback"; | ||
| 2060 | my $timeout = delete $args{timeout} // 300; | ||
| 2061 | my $resource_version = delete $args{resourceVersion}; | ||
| 2062 | my $label_selector = delete $args{labelSelector}; | ||
| 2063 | my $field_selector = delete $args{fieldSelector}; | ||
| 2064 | |||
| 2065 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 2066 | my $path = $self->_build_path($class, %args, | ||
| 2067 | $self->_unstructured_hint($class, $short_class)); | ||
| 2068 | |||
| 2069 | my %params = ( | ||
| 2070 | watch => 'true', | ||
| 2071 | timeoutSeconds => $timeout, | ||
| 2072 | ); | ||
| 2073 | $params{resourceVersion} = $resource_version if defined $resource_version; | ||
| 2074 | $params{labelSelector} = $label_selector if defined $label_selector; | ||
| 2075 | $params{fieldSelector} = $field_selector if defined $field_selector; | ||
| 2076 | |||
| 2077 | my $req = $self->_prepare_request('GET', $path, parameters => \%params); | ||
| 2078 | |||
| 2079 | my $buffer = ''; | ||
| 2080 | my $last_rv = $resource_version; | ||
| 2081 | my $got_410 = 0; | ||
| 2082 | |||
| 2083 | my $data_callback = sub { | ||
| 2084 | my ($chunk) = @_; | ||
| 2085 | for my $result ($self->_process_watch_chunk($class, \$buffer, $chunk)) { | ||
| 2086 | $last_rv = $result->{resourceVersion} if $result->{resourceVersion}; | ||
| 2087 | $got_410 = 1 if $result->{error_code} == 410; | ||
| 2088 | $on_event->($result->{event}); | ||
| 2089 | } | ||
| 2090 | }; | ||
| 2091 | |||
| 2092 | my $response = $self->io->call_streaming($req, $data_callback); | ||
| 2093 | |||
| 2094 | $self->_check_response($response, "watch $short_class"); | ||
| 2095 | |||
| 2096 | croak "Watch expired (410 Gone): resourceVersion too old, re-list to get a fresh resourceVersion" | ||
| 2097 | if $got_410; | ||
| 2098 | |||
| 2099 | return $last_rv; | ||
| 2100 | } | ||
| 2101 | |||
| 2102 | sub log { | ||
| 2103 | my ($self, $short_class, @rest) = @_; | ||
| 2104 | |||
| 2105 | |||
| 2106 | # Support: log('Pod', 'name', ...) and log('Pod', name => 'name', ...) | ||
| 2107 | my %args; | ||
| 2108 | if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|container|follow|tailLines|sinceSeconds|sinceTime|timestamps|previous|limitBytes|on_line)$/) { | ||
| 2109 | $args{name} = shift @rest; | ||
| 2110 | %args = (%args, @rest); | ||
| 2111 | } elsif (@rest % 2 == 0) { | ||
| 2112 | %args = @rest; | ||
| 2113 | } else { | ||
| 2114 | 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 | $self->_croak_unknown_args('log', \%args, qw(name namespace container | ||
| 2119 | follow tailLines sinceSeconds sinceTime timestamps previous limitBytes | ||
| 2120 | on_line)); | ||
| 2121 | |||
| 2122 | croak "name required for log" unless $args{name}; | ||
| 2123 | |||
| 2124 | my $on_line = delete $args{on_line}; | ||
| 2125 | my $container = delete $args{container}; | ||
| 2126 | my $follow = delete $args{follow}; | ||
| 2127 | my $tail_lines = delete $args{tailLines}; | ||
| 2128 | my $since_seconds = delete $args{sinceSeconds}; | ||
| 2129 | my $since_time = delete $args{sinceTime}; | ||
| 2130 | my $timestamps = delete $args{timestamps}; | ||
| 2131 | my $previous = delete $args{previous}; | ||
| 2132 | my $limit_bytes = delete $args{limitBytes}; | ||
| 2133 | |||
| 2134 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 2135 | my $path = $self->_build_path($class, %args, subresource => 'log', | ||
| 2136 | $self->_unstructured_hint($class, $short_class)); | ||
| 2137 | |||
| 2138 | my %params; | ||
| 2139 | $params{container} = $container if defined $container; | ||
| 2140 | $params{follow} = 'true' if $follow; | ||
| 2141 | $params{tailLines} = $tail_lines if defined $tail_lines; | ||
| 2142 | $params{sinceSeconds} = $since_seconds if defined $since_seconds; | ||
| 2143 | $params{sinceTime} = $since_time if defined $since_time; | ||
| 2144 | $params{timestamps} = 'true' if $timestamps; | ||
| 2145 | $params{previous} = 'true' if $previous; | ||
| 2146 | $params{limitBytes} = $limit_bytes if defined $limit_bytes; | ||
| 2147 | |||
| 2148 | if ($on_line) { | ||
| 2149 | # Streaming mode | ||
| 2150 | my $req = $self->_prepare_request('GET', $path, parameters => \%params); | ||
| 2151 | |||
| 2152 | my $buffer = ''; | ||
| 2153 | my $data_callback = sub { | ||
| 2154 | my ($chunk) = @_; | ||
| 2155 | for my $event ($self->_process_log_chunk(\$buffer, $chunk)) { | ||
| 2156 | $on_line->($event); | ||
| 2157 | } | ||
| 2158 | }; | ||
| 2159 | |||
| 2160 | my $response = $self->io->call_streaming($req, $data_callback); | ||
| 2161 | $self->_check_response($response, "log $short_class"); | ||
| 2162 | |||
| 2163 | # Process any remaining data in buffer (last line without trailing newline) | ||
| 2164 | if (length $buffer) { | ||
| 2165 | $on_line->(Kubernetes::REST::LogEvent->new(line => $buffer)); | ||
| 2166 | } | ||
| 2167 | |||
| 2168 | return; | ||
| 2169 | } else { | ||
| 2170 | # One-shot mode | ||
| 2171 | my $response = $self->_request('GET', $path, undef, | ||
| 2172 | %params ? (parameters => \%params) : (), | ||
| 2173 | ); | ||
| 2174 | $self->_check_response($response, "log $short_class"); | ||
| 2175 | |||
| 2176 | return $response->content; | ||
| 2177 | } | ||
| 2178 | } | ||
| 2179 | |||
| 2180 | sub port_forward { | ||
| 2181 | my ($self, $short_class, @rest) = @_; | ||
| 2182 | |||
| 2183 | |||
| 2184 | my %args; | ||
| 2185 | if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|ports|subprotocol|on_open|on_frame|on_close|on_error)$/) { | ||
| 2186 | $args{name} = shift @rest; | ||
| 2187 | %args = (%args, @rest); | ||
| 2188 | } elsif (@rest % 2 == 0) { | ||
| 2189 | %args = @rest; | ||
| 2190 | } else { | ||
| 2191 | 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 | $self->_croak_unknown_args('port_forward', \%args, qw(name namespace ports | ||
| 2196 | subprotocol on_open on_frame on_close on_error)); | ||
| 2197 | |||
| 2198 | croak "name required for port_forward" unless $args{name}; | ||
| 2199 | |||
| 2200 | my $ports = delete $args{ports}; | ||
| 2201 | croak "ports required for port_forward" unless defined $ports; | ||
| 2202 | $ports = [$ports] unless ref($ports) eq 'ARRAY'; | ||
| 2203 | croak "ports required for port_forward" unless @$ports; | ||
| 2204 | for my $p (@$ports) { | ||
| 2205 | croak "invalid port '$p' for port_forward" | ||
| 2206 | unless defined($p) && $p =~ /^\d+$/ && $p > 0 && $p <= 65535; | ||
| 2207 | } | ||
| 2208 | |||
| 2209 | my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io'; | ||
| 2210 | my $on_open = delete $args{on_open}; | ||
| 2211 | my $on_frame = delete $args{on_frame}; | ||
| 2212 | my $on_close = delete $args{on_close}; | ||
| 2213 | my $on_error = delete $args{on_error}; | ||
| 2214 | |||
| 2215 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 2216 | my $path = $self->_build_path($class, %args, subresource => 'portforward', | ||
| 2217 | $self->_unstructured_hint($class, $short_class)); | ||
| 2218 | |||
| 2219 | 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 | my $io = $self->io; | ||
| 2230 | unless ($io->can('call_duplex')) { | ||
| 2231 | croak "IO backend does not support port_forward(): missing call_duplex()"; | ||
| 2232 | } | ||
| 2233 | |||
| 2234 | 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 | sub exec { | ||
| 2243 | my ($self, $short_class, @rest) = @_; | ||
| 2244 | |||
| 2245 | |||
| 2246 | my %args; | ||
| 2247 | 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)$/) { | ||
| 2248 | $args{name} = shift @rest; | ||
| 2249 | %args = (%args, @rest); | ||
| 2250 | } elsif (@rest % 2 == 0) { | ||
| 2251 | %args = @rest; | ||
| 2252 | } else { | ||
| 2253 | 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 | $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 | croak "name required for exec" unless $args{name}; | ||
| 2262 | |||
| 2263 | my $command = delete $args{command}; | ||
| 2264 | croak "command required for exec" unless defined $command; | ||
| 2265 | $command = [$command] unless ref($command) eq 'ARRAY'; | ||
| 2266 | croak "command required for exec" unless @$command; | ||
| 2267 | for my $part (@$command) { | ||
| 2268 | croak "invalid command element for exec" | ||
| 2269 | unless defined($part) && !ref($part) && length $part; | ||
| 2270 | } | ||
| 2271 | |||
| 2272 | my $container = delete $args{container}; | ||
| 2273 | my $stdin = delete($args{stdin}) ? 1 : 0; | ||
| 2274 | my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1; | ||
| 2275 | my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1; | ||
| 2276 | my $tty = delete($args{tty}) ? 1 : 0; | ||
| 2277 | |||
| 2278 | my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io'; | ||
| 2279 | my $on_open = delete $args{on_open}; | ||
| 2280 | my $on_frame = delete $args{on_frame}; | ||
| 2281 | my $on_close = delete $args{on_close}; | ||
| 2282 | my $on_error = delete $args{on_error}; | ||
| 2283 | |||
| 2284 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 2285 | my $path = $self->_build_path($class, %args, subresource => 'exec', | ||
| 2286 | $self->_unstructured_hint($class, $short_class)); | ||
| 2287 | |||
| 2288 | my %params = ( | ||
| 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 | $params{container} = $container if defined $container; | ||
| 2296 | |||
| 2297 | 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 | my $io = $self->io; | ||
| 2308 | unless ($io->can('call_duplex')) { | ||
| 2309 | croak "IO backend does not support exec(): missing call_duplex()"; | ||
| 2310 | } | ||
| 2311 | |||
| 2312 | 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 | sub attach { | ||
| 2321 | my ($self, $short_class, @rest) = @_; | ||
| 2322 | |||
| 2323 | |||
| 2324 | my %args; | ||
| 2325 | if (@rest >= 1 && !ref($rest[0]) && $rest[0] !~ /^(name|namespace|container|stdin|stdout|stderr|tty|subprotocol|on_open|on_frame|on_close|on_error)$/) { | ||
| 2326 | $args{name} = shift @rest; | ||
| 2327 | %args = (%args, @rest); | ||
| 2328 | } elsif (@rest % 2 == 0) { | ||
| 2329 | %args = @rest; | ||
| 2330 | } else { | ||
| 2331 | croak "Invalid arguments to attach()"; | ||
| 2332 | } | ||
| 2333 | # A misspelt option is not ignored (karr k61): stdn => 1 attached without | ||
| 2334 | # stdin. | ||
| 2335 | $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 | croak "name required for attach" unless $args{name}; | ||
| 2339 | |||
| 2340 | my $container = delete $args{container}; | ||
| 2341 | my $stdin = delete($args{stdin}) ? 1 : 0; | ||
| 2342 | my $stdout = exists($args{stdout}) ? (delete($args{stdout}) ? 1 : 0) : 1; | ||
| 2343 | my $stderr = exists($args{stderr}) ? (delete($args{stderr}) ? 1 : 0) : 1; | ||
| 2344 | my $tty = delete($args{tty}) ? 1 : 0; | ||
| 2345 | |||
| 2346 | my $subprotocol = delete $args{subprotocol} // 'v4.channel.k8s.io'; | ||
| 2347 | my $on_open = delete $args{on_open}; | ||
| 2348 | my $on_frame = delete $args{on_frame}; | ||
| 2349 | my $on_close = delete $args{on_close}; | ||
| 2350 | my $on_error = delete $args{on_error}; | ||
| 2351 | |||
| 2352 | my $class = $self->_expand_class_or_croak($short_class); | ||
| 2353 | my $path = $self->_build_path($class, %args, subresource => 'attach', | ||
| 2354 | $self->_unstructured_hint($class, $short_class)); | ||
| 2355 | |||
| 2356 | my %params = ( | ||
| 2357 | stdin => $stdin ? 'true' : 'false', | ||
| 2358 | stdout => $stdout ? 'true' : 'false', | ||
| 2359 | stderr => $stderr ? 'true' : 'false', | ||
| 2360 | tty => $tty ? 'true' : 'false', | ||
| 2361 | ); | ||
| 2362 | $params{container} = $container if defined $container; | ||
| 2363 | |||
| 2364 | 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 | my $io = $self->io; | ||
| 2375 | unless ($io->can('call_duplex')) { | ||
| 2376 | croak "IO backend does not support attach(): missing call_duplex()"; | ||
| 2377 | } | ||
| 2378 | |||
| 2379 | 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 | 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 |