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