### GET /api Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves the API discovery information from the Kubernetes cluster. ```APIDOC ## GET /api ### Description Retrieves the API discovery information from the Kubernetes cluster. ### Method GET ### Endpoint /api ### Response #### Success Response (200) - **response** (Hash) - The parsed JSON response containing API versions and groups. ``` -------------------------------- ### Get SSL Options Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the SSL options configured for the client. This is a read-only attribute. ```Ruby def ssl_options @ssl_options end ``` -------------------------------- ### Get Authentication Options Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the authentication options configured for the client. This is a read-only attribute. ```Ruby def auth_options @auth_options end ``` -------------------------------- ### GET /all_entities Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves all entities available in the current API context. ```APIDOC ## GET /all_entities ### Description Retrieves all entities available in the current API context by iterating through discovered resources. ### Method GET ### Parameters #### Query Parameters - **options** (hash) - Optional - Options to pass to the underlying get requests. ### Response #### Success Response (200) - **result_hash** (hash) - A mapping of entity names to arrays of entity objects. ``` -------------------------------- ### Get REST Client Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns or initializes the REST client instance using the API endpoint and version. ```ruby def rest_client @rest_client ||= begin create_rest_client("#{@api_endpoint.path}/#{@api_version}") end end ``` -------------------------------- ### GET Watch Stream Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/WatchStream Establishes a streaming connection to watch for entity changes. ```APIDOC ## GET /watch ### Description Initiates an HTTP stream to monitor changes on Kubernetes entities. The stream processes incoming data chunks and yields formatted results. ### Method GET ### Parameters #### Path Parameters - **uri** (String) - Required - The URI of the Kubernetes resource to watch. ### Response #### Success Response (200) - **yield** (Object) - Yields formatted entity change events as they arrive in the stream. #### Error Handling - **HttpError** - Raised if the response code is 300 or greater. ``` -------------------------------- ### Get Current Context Details Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config Retrieves and constructs the details for a specific context, including server details, authentication options, and SSL options. It handles 'exec' credential plugins and certificate loading. ```ruby def context(context_name = nil) cluster, user, namespace = fetch_context(context_name || @kcfg['current-context']) if user.key?('exec') exec_opts = expand_command_option(user['exec'], 'command') user['exec_result'] = ExecCredentials.run(exec_opts) end client_cert_data = fetch_user_cert_data(user) client_key_data = fetch_user_key_data(user) auth_options = fetch_user_auth_options(user) ssl_options = {} ssl_options[:verify_ssl] = if cluster['insecure-skip-tls-verify'] == true OpenSSL::SSL::VERIFY_NONE else OpenSSL::SSL::VERIFY_PEER end if cluster_ca_data?(cluster) cert_store = OpenSSL::X509::Store.new populate_cert_store_from_cluster_ca_data(cluster, cert_store) ssl_options[:cert_store] = cert_store end unless client_cert_data.nil? ssl_options[:client_cert] = OpenSSL::X509::Certificate.new(client_cert_data) end unless client_key_data.nil? ssl_options[:client_key] = OpenSSL::PKey.read(client_key_data) end Context.new(cluster['server'], @kcfg['apiVersion'], ssl_options, auth_options, namespace) end ``` -------------------------------- ### Get All Entities Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves all entities of a given type, making a GET request for each. It handles potential HTTP errors for resources that might not support GET operations. ```ruby def all_entities(options = {}) discover unless @discovered @entities.values.each_with_object({}) do |entity, result_hash| # method call for get each entities # build hash of entity name to array of the entities method_name = "get_#{entity.method_names[1]}" begin result_hash[entity.method_names[0]] = send(method_name, options) rescue Kubeclient::HttpError next # do not fail due to resources not supporting get end end end ``` -------------------------------- ### GET /:resource_name/:name Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves a specific entity by its name and resource type. ```APIDOC ## GET /:resource_name/:name ### Description Retrieves a specific entity by its name and resource type. Allows specifying the response format. ### Method GET ### Endpoint /:resource_name/:name ### Parameters #### Path Parameters - **resource_name** (string) - Required - The type of resource. - **name** (string) - Required - The name of the entity. #### Query Parameters - **namespace** (string) - Optional - The namespace of the entity. - **as** (:raw|:ros) - Optional - Specifies the format of the returned object. Defaults to `:ros` (RecursiveOpenStruct object). `:raw` returns the raw response body as a string. ### Request Example ```json { "namespace": "default", "as": "ros" } ``` ### Response #### Success Response (200) - **body** (object|string) - The requested entity object or the raw response body. #### Response Example ```json { "metadata": {"name": "my-pod"}, "spec": {} } ``` ``` -------------------------------- ### GET /:resource_name Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves a list of entities of a specified type. Supports filtering and pagination. ```APIDOC ## GET /:resource_name ### Description Retrieves a list of entities of a specified type. Supports filtering by namespace, labels, and fields, as well as pagination. ### Method GET ### Endpoint /:resource_name ### Parameters #### Path Parameters - **entity_type** (string) - Required - The type of entity to retrieve (e.g., 'pods', 'services'). - **resource_name** (string) - Required - The name of the resource collection. #### Query Parameters - **namespace** (string) - Optional - The namespace of the entities. - **label_selector** (string) - Optional - A selector to restrict the list of returned objects by labels. - **field_selector** (string) - Optional - A selector to restrict the list of returned objects by fields. - **limit** (integer) - Optional - A maximum number of items to return in each response. - **continue** (string) - Optional - A token used to retrieve the next chunk of entities. - **as** (:raw|:ros) - Optional - Specifies the format of the returned objects. Defaults to `:ros` (RecursiveOpenStruct objects). `:raw` returns the raw response body as a string. ### Request Example ```json { "namespace": "default", "label_selector": "app=my-app", "limit": 100, "as": "raw" } ``` ### Response #### Success Response (200) - **body** (object|string) - A collection of entities or the raw response body, depending on the `as` option. #### Response Example ```json [ { "metadata": {"name": "pod-1"}, "spec": {} } ] ``` ``` -------------------------------- ### Get a single entity Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Fetches a specific entity by name and namespace. Returns the formatted response based on the :as option. ```ruby def get_entity(resource_name, name, namespace = nil, options = {}) ns_prefix = build_namespace_prefix(namespace) response = handle_exception do rest_client[ns_prefix + resource_name + "/#{name}"] .get(get_headers) end format_response(options[:as] || @as, response.body) end ``` -------------------------------- ### Get Proxy URL Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Constructs a proxy URL for a specific resource kind, name, and port. Triggers discovery if it has not been performed yet. ```ruby def proxy_url(kind, name, port, namespace = '') discover unless @discovered entity_name_plural = if %w[services pods nodes].include?(kind.to_s) kind.to_s else @entities[kind.to_s].resource_name end ns_prefix = build_namespace_prefix(namespace) rest_client["#{ns_prefix}#{entity_name_plural}/#{name}:#{port}/proxy"].url end ``` -------------------------------- ### Get Context Names Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config Returns an array of names for all available contexts defined in the kubeconfig data. ```ruby def contexts @kcfg['contexts'].map { |x| x['name'] } end ``` -------------------------------- ### Get HTTP Proxy URI Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the HTTP proxy URI configured for the client. This is a read-only attribute. ```Ruby def http_proxy_uri @http_proxy_uri end ``` -------------------------------- ### Get Continue Token from EntityList Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/EntityList Returns the value of the 'continue' attribute, which is used for pagination in Kubernetes API responses. ```ruby def continue @continue end ``` -------------------------------- ### Get API Information Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Fetches and parses the API information from the Kubernetes server. This is typically used to understand the available API groups and versions. ```ruby def api response = handle_exception { create_rest_client.get(get_headers) } JSON.parse(response) end ``` -------------------------------- ### Get multiple entities Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves a list of entities based on provided search parameters and namespace. Supports filtering via label and field selectors. ```ruby def get_entities(entity_type, resource_name, options = {}) params = {} SEARCH_ARGUMENTS.each { |k, v| params[k] = options[v] if options[v] } ns_prefix = build_namespace_prefix(options[:namespace]) response = handle_exception do rest_client[ns_prefix + resource_name] .get({ 'params' => params }.merge(get_headers)) end format_response(options[:as] || @as, response.body, entity_type) end ``` -------------------------------- ### Get pod logs Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves logs for a specific pod. Supports various log parameters like container selection, timestamps, and tail lines. ```ruby def get_pod_log(pod_name, namespace, container: nil, previous: false, timestamps: false, since_time: nil, tail_lines: nil, limit_bytes: nil) params = {} params[:previous] = true if previous params[:container] = container if container params[:timestamps] = timestamps if timestamps params[:sinceTime] = format_datetime(since_time) if since_time params[:tailLines] = tail_lines if tail_lines params[:limitBytes] = limit_bytes if limit_bytes ns = build_namespace_prefix(namespace) handle_exception do rest_client[ns + "pods/#{pod_name}/log"] .get({ 'params' => params }.merge(get_headers)) end end ``` -------------------------------- ### Initialize Kubeclient Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Sets up the client with authentication, SSL, and connection options. It validates auth options and handles URI parsing during initialization. ```ruby def initialize_client( uri, path, version, ssl_options: DEFAULT_SSL_OPTIONS, auth_options: DEFAULT_AUTH_OPTIONS, socket_options: DEFAULT_SOCKET_OPTIONS, timeouts: DEFAULT_TIMEOUTS, http_proxy_uri: DEFAULT_HTTP_PROXY_URI, http_max_redirects: DEFAULT_HTTP_MAX_REDIRECTS, as: :ros ) validate_auth_options(auth_options) handle_uri(uri, path) @entities = {} @discovered = false @api_version = version @headers = {} @ssl_options = ssl_options @auth_options = auth_options.dup @socket_options = socket_options # Allow passing partial timeouts hash, without unspecified # @timeouts[:foo] == nil resulting in infinite timeout. @timeouts = DEFAULT_TIMEOUTS.merge(timeouts) @http_proxy_uri = http_proxy_uri ? http_proxy_uri.to_s : nil @http_max_redirects = http_max_redirects @as = as if auth_options[:bearer_token_file] validate_bearer_token_file bearer_token(File.read(@auth_options[:bearer_token_file])) elsif auth_options[:bearer_token] bearer_token(@auth_options[:bearer_token]) end end ``` -------------------------------- ### Kubeclient::Config Instance Methods Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config Details instance methods for managing configuration contexts and initialization. ```APIDOC ## GET /api/users/{id} ### Description Retrieves details for a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": 1, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Constructor: Kubeclient::Config::Context.new Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config/Context Initializes a new configuration context for the Kubernetes client. ```APIDOC ## Constructor: Kubeclient::Config::Context.new ### Description Creates a new instance of the Context class to hold configuration details for a Kubernetes client connection. ### Parameters #### Request Body - **api_endpoint** (Object) - Required - The URL of the Kubernetes API server. - **api_version** (Object) - Required - The version of the Kubernetes API to use. - **ssl_options** (Object) - Required - SSL configuration options for the connection. - **auth_options** (Object) - Required - Authentication credentials or options. - **namespace** (Object) - Required - The default Kubernetes namespace. ``` -------------------------------- ### Get KubeException Response Source: https://www.rubydoc.info/gems/kubeclient/KubeException Returns the response object associated with the KubeException. ```ruby def response @response end ``` -------------------------------- ### Initialize Kubeclient::Config::Context Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config/Context Constructor for creating a new configuration context instance. ```ruby # File 'lib/kubeclient/config.rb', line 14 def initialize(api_endpoint, api_version, ssl_options, auth_options, namespace) @api_endpoint = api_endpoint @api_version = api_version @ssl_options = ssl_options @auth_options = auth_options @namespace = namespace end ``` -------------------------------- ### Client Initialization Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Initializes the Kubernetes client with specified URI, API version, and various configuration options for SSL, authentication, sockets, timeouts, and proxy settings. ```APIDOC ## initialize_client ### Description Initializes the Kubernetes client with specified URI, API version, and various configuration options for SSL, authentication, sockets, timeouts, and proxy settings. ### Method `initialize_client` ### Parameters - **uri** (String or URI) - The base URI for the Kubernetes API. - **path** (String) - The API path segment. - **version** (String) - The API version to use. - **ssl_options** (Hash, optional) - SSL configuration options. Defaults to `DEFAULT_SSL_OPTIONS`. - **auth_options** (Hash, optional) - Authentication options (e.g., bearer token). Defaults to `DEFAULT_AUTH_OPTIONS`. - **socket_options** (Hash, optional) - Socket configuration options. Defaults to `DEFAULT_SOCKET_OPTIONS`. - **timeouts** (Hash, optional) - Timeout settings for requests. Defaults to `DEFAULT_TIMEOUTS`. - **http_proxy_uri** (String, optional) - URI for an HTTP proxy. Defaults to `DEFAULT_HTTP_PROXY_URI`. - **http_max_redirects** (Integer, optional) - Maximum number of HTTP redirects. Defaults to `DEFAULT_HTTP_MAX_REDIRECTS`. - **as** (Symbol, optional) - Alias for the client type. Defaults to `:ros`. ### Request Example ```ruby client = Kubeclient::Client.new('http://localhost:8080', 'v1') ``` ### Response Returns an initialized client object. ``` -------------------------------- ### Get KubeException Message Source: https://www.rubydoc.info/gems/kubeclient/KubeException Returns the error message associated with the KubeException. ```ruby def message @message end ``` -------------------------------- ### Instance Method Summary Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Provides a summary of instance methods available in the Kubeclient gem for managing Kubernetes resources. ```APIDOC ## Instance Method Summary * #**all_entities**(options = {}) ⇒ Object * #**api** ⇒ Object * #**api_valid?** ⇒ Boolean * #**apply_entity**(resource_name, resource, field_manager:, force: true) ⇒ Object * #**build_namespace_prefix**(namespace) ⇒ Object * #**create_entity**(entity_type, resource_name, entity_config) ⇒ Object * #**create_rest_client**(path = nil) ⇒ Object * #**define_entity_methods** ⇒ Object * #**delete_entity**(resource_name, name, namespace = nil, delete_options: {}) ⇒ Object * delete_options are passed as a JSON payload in the delete request. * #**discover** ⇒ Object * #**discovery_needed?**(method_sym) ⇒ Boolean * #**get_entities**(entity_type, resource_name, options = {}) ⇒ Object * Accepts the following options: :namespace (string) - the namespace of the entity. * #**get_entity**(resource_name, name, namespace = nil, options = {}) ⇒ Object * Accepts the following options: :as (:raw|:ros) - defaults to :ros :raw - return the raw response body as a string :ros - return a collection of RecursiveOpenStruct objects. * #**get_headers** ⇒ Object * #**get_pod_log**(pod_name, namespace, container: nil, previous: false, timestamps: false, since_time: nil, tail_lines: nil, limit_bytes: nil) ⇒ Object * #**handle_exception** ⇒ Object * #**handle_uri**(uri, path) ⇒ Object * #**initialize_client**(uri, path, version, ssl_options: DEFAULT_SSL_OPTIONS, auth_options: DEFAULT_AUTH_OPTIONS, socket_options: DEFAULT_SOCKET_OPTIONS, timeouts: DEFAULT_TIMEOUTS, http_proxy_uri: DEFAULT_HTTP_PROXY_URI, http_max_redirects: DEFAULT_HTTP_MAX_REDIRECTS, as: :ros) ⇒ Object * #**method_missing**(method_sym, *args, &block) ⇒ Object * #**patch_entity**(resource_name, name, patch, strategy, namespace) ⇒ Object * #**process_template**(template) ⇒ Object * #**proxy_url**(kind, name, port, namespace = '') ⇒ Object * #**respond_to_missing?**(method_sym, include_private = false) ⇒ Boolean * #**rest_client** ⇒ Object * #**update_entity**(resource_name, entity_config) ⇒ Object * #**watch_entities**(resource_name, options = {}, &block) ⇒ Object * Accepts the following options: :namespace (string) - the namespace of the entity. * #**watch_pod_log**(pod_name, namespace, container: nil, &block) ⇒ Object ``` -------------------------------- ### Get Headers Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the headers used for API requests. This is a read-only attribute. ```Ruby def headers @headers end ``` -------------------------------- ### Constructor: Kubeclient::Resource#initialize Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Resource Initializes a new instance of the Resource class with optional hash data and configuration arguments. ```APIDOC ## Constructor: Kubeclient::Resource#initialize ### Description Creates a new instance of Resource. This class inherits from RecursiveOpenStruct and is used to represent objects returned by Kubeclient. ### Parameters #### Request Body - **hash** (Hash) - Optional - Initial data for the resource. - **args** (Hash) - Optional - Configuration arguments. Defaults to setting :recurse_over_arrays to true. ### Request Example ```ruby resource = Kubeclient::Resource.new({ name: 'my-pod' }, { recurse_over_arrays: true }) ``` ### Response #### Success Response (200) - **Resource** (Object) - A new instance of Kubeclient::Resource. ``` -------------------------------- ### Create REST Client Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Initializes a RestClient::Resource with SSL, proxy, and timeout configurations. ```ruby def create_rest_client(path = nil) path ||= @api_endpoint.path options = { ssl_ca_file: @ssl_options[:ca_file], ssl_cert_store: @ssl_options[:cert_store], verify_ssl: @ssl_options[:verify_ssl], ssl_client_cert: @ssl_options[:client_cert], ssl_client_key: @ssl_options[:client_key], proxy: @http_proxy_uri, max_redirects: @http_max_redirects, user: @auth_options[:username], password: @auth_options[:password], open_timeout: @timeouts[:open], read_timeout: @timeouts[:read] } RestClient::Resource.new(@api_endpoint.merge(path).to_s, options) end ``` -------------------------------- ### Initialize WatchStream Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/WatchStream Constructor for the WatchStream class, setting up the URI, HTTP options, and formatter. ```ruby def initialize(uri, http_options, formatter:) @uri = uri @http_client = nil @http_options = http_options @http_options[:http_max_redirects] ||= Kubeclient::Client::DEFAULT_HTTP_MAX_REDIRECTS @formatter = formatter end ``` -------------------------------- ### Initialize Kubeclient::Client Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Client Constructor for creating a new instance of the Kubernetes client. ```APIDOC ## POST /initialize ### Description Initializes a new Kubeclient::Client instance to connect to a Kubernetes API endpoint. ### Method Constructor ### Parameters #### Request Body - **uri** (String) - Required - The base URI of the Kubernetes API server. - **version** (String) - Optional - The API version to use (defaults to 'v1'). - **options** (Hash) - Optional - Additional configuration options including authentication, SSL, and proxy settings. ``` -------------------------------- ### POST .run Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ExecCredentials Executes the configured command to retrieve authentication credentials for Kubernetes. ```APIDOC ## .run(opts) ### Description Executes an external command to retrieve exec-based authentication credentials. It validates the provided options, runs the command, and parses the resulting JSON output. ### Parameters #### Request Body - **opts** (Hash) - Required - A hash containing 'command', 'args', and 'env' keys required for the execution. ### Response #### Success Response (200) - **status** (Object) - The status object containing the authentication credentials parsed from the command output. ### Errors - **ArgumentError** - Raised if the opts parameter is nil. - **RuntimeError** - Raised if the execution command fails (non-zero exit status). ``` -------------------------------- ### Initialize Kubeclient Config Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config Initializes a Config instance with parsed kubeconfig data and a path for resolving relative references. Raises an error for unknown kubeconfig versions. ```ruby def initialize(data, kcfg_path) @kcfg = data @kcfg_path = kcfg_path raise 'Unknown kubeconfig version' if @kcfg['apiVersion'] != 'v1' end ``` -------------------------------- ### Get API Endpoint Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the configured API endpoint for the client. This is a read-only attribute. ```Ruby def api_endpoint @api_endpoint end ``` -------------------------------- ### Get KubeException Error Code Source: https://www.rubydoc.info/gems/kubeclient/KubeException Returns the HTTP error code associated with the KubeException. ```ruby def error_code @error_code end ``` -------------------------------- ### Initialize Kubeclient::Client Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Client Constructor for creating a new client instance, which delegates configuration to initialize_client. ```ruby # File 'lib/kubeclient.rb', line 24 def initialize( uri, version = 'v1', **options ) initialize_client( uri, '/api', version, **options ) end ``` -------------------------------- ### Execute authentication command with Kubeclient::ExecCredentials Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ExecCredentials The run method executes a command to retrieve credentials, requiring specific options and validating the output. ```ruby def run(opts) require 'open3' require 'json' raise ArgumentError, 'exec options are required' if opts.nil? cmd = opts['command'] args = opts['args'] env = map_env(opts['env']) # Validate exec options validate_opts(opts) out, err, st = Open3.capture3(env, cmd, *args) raise "exec command failed: #{err}" unless st.success? creds = JSON.parse(out) validate_credentials(opts, creds) creds['status'] end ``` -------------------------------- ### Kubeclient::Common::EntityList Constructor Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/EntityList Initializes a new instance of Kubeclient::Common::EntityList. ```APIDOC ## #initialize(kind, resource_version, list, continue = nil) ### Description Initializes a new instance of EntityList. ### Method constructor ### Parameters - **kind** (Object) - Required - The kind of the entities in the list. - **resource_version** (Object) - Required - The resource version of the list. - **list** (Object) - Required - The list of entities. - **continue** (Object) - Optional - A token for pagination, if available. ### Request Example ```ruby EntityList.new('Pod', '12345', [{ 'metadata' => { 'name' => 'my-pod' } }], 'next-token') ``` ### Response #### Success Response (200) - **EntityList** (Object) - A new instance of EntityList. ``` -------------------------------- ### Initialize Kubeclient::Common::EntityList Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/EntityList Initializes a new instance of EntityList with kind, resource version, the list of entities, and an optional continue token. ```ruby def initialize(kind, resource_version, list, continue = nil) @kind = kind # rubocop:disable Style/VariableName @resourceVersion = resource_version @continue = continue super(list) end ``` -------------------------------- ### Get HTTP Max Redirects Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the maximum number of HTTP redirects allowed. This is a read-only attribute. ```Ruby def http_max_redirects @http_max_redirects end ``` -------------------------------- ### WatchStream Initialization Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/WatchStream Constructor for the WatchStream instance. ```APIDOC ## Constructor: initialize ### Description Creates a new instance of WatchStream with the specified URI, HTTP options, and formatter. ### Parameters - **uri** (String) - Required - The target URI. - **http_options** (Hash) - Required - Configuration for the HTTP client. - **formatter** (Object) - Required - The object responsible for formatting the stream data. ``` -------------------------------- ### Get Kind from EntityList Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/EntityList Returns the value of the 'kind' attribute, indicating the type of Kubernetes resource in the list. ```ruby def kind @kind end ``` -------------------------------- ### Get request headers Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves request headers, including bearer token authentication if a token file is configured. ```ruby def get_headers bearer_token(File.read(@auth_options[:bearer_token_file])) if @auth_options[:bearer_token_file] @headers end ``` -------------------------------- ### Build Namespace Prefix Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Generates a URL path prefix based on the provided namespace. ```ruby def build_namespace_prefix(namespace) namespace.to_s.empty? ? '' : "namespaces/#{namespace}/" end ``` -------------------------------- ### Create REST Client Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Initializes and returns a RestClient::Resource object configured for interacting with the Kubernetes API endpoint. ```APIDOC ## Initialize Kubernetes API Client ### Description Sets up a REST client to communicate with the Kubernetes API server, including SSL/TLS and authentication options. ### Method Initialization/Configuration ### Endpoint Configured via `@api_endpoint` which typically points to the Kubernetes API server URL. ### Parameters None directly exposed in this method, configuration is typically set during client initialization. ### Request Example N/A (This is a client initialization method) ### Response - **RestClient::Resource** - A configured resource object for making API calls. ``` -------------------------------- ### Get Resource Version from EntityList Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/EntityList Returns the value of the 'resourceVersion' attribute, which is an opaque identifier representing the state of the list. ```ruby def resourceVersion @resourceVersion end ``` -------------------------------- ### Kubeclient::Common::EntityList Instance Methods Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/EntityList Details of the instance methods for Kubeclient::Common::EntityList. ```APIDOC ## Instance Method Summary ### #last? ⇒ Boolean #### Description Checks if this is the last page of results. #### Returns - **Boolean** - True if there are no more pages, false otherwise. ``` -------------------------------- ### discover Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Initiates the discovery process for Kubernetes entities and defines corresponding methods. ```APIDOC ## discover ### Description Initiates the discovery process for Kubernetes entities and defines corresponding methods. This method should be called to ensure all entity methods are available. ### Method N/A (Instance Method) ### Endpoint N/A ### Parameters None ### Request Example ```ruby client.discover ``` ### Response #### Success Response This method does not return a value but modifies the client's internal state by loading entities and defining methods. ``` -------------------------------- ### Initialize KubeException Source: https://www.rubydoc.info/gems/kubeclient/KubeException Constructor for KubeException. Initializes the exception with an error code, message, and response object. ```ruby def initialize(error_code, message, response) @error_code = error_code @message = message @response = response end ``` -------------------------------- ### Get Discovered Status Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Returns the discovery status of the client. This is a read-only attribute, indicating whether API resources have been discovered. ```Ruby def discovered @discovered end ``` -------------------------------- ### GET /namespaces/:namespace/pods/:pod_name/log Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Retrieves logs for a specific pod, with options for container, previous logs, timestamps, and log filtering. ```APIDOC ## GET /namespaces/:namespace/pods/:pod_name/log ### Description Retrieves logs for a specific pod. Allows specifying the container, requesting logs from a previous instance of the pod, and applying various filtering options. ### Method GET ### Endpoint /namespaces/:namespace/pods/:pod_name/log ### Parameters #### Path Parameters - **pod_name** (string) - Required - The name of the pod. - **namespace** (string) - Required - The namespace of the pod. #### Query Parameters - **container** (string) - Optional - The name of the container within the pod to retrieve logs from. - **previous** (boolean) - Optional - If true, return logs from a previous instance of the container. - **timestamps** (boolean) - Optional - If true, include timestamps in the logs. - **since_time** (string) - Optional - RFC3339 date/time format. Only return logs created after this time. - **tail_lines** (integer) - Optional - Only return the last N lines of the logs. - **limit_bytes** (integer) - Optional - Maximum number of bytes of returned log in the stream. These bytes of log are stored as a byte stream. ### Request Example ```json { "container": "main-app", "previous": false, "timestamps": true, "since_time": "2023-10-27T10:00:00Z", "tail_lines": 100, "limit_bytes": 1024 } ``` ### Response #### Success Response (200) - **body** (string) - The log output as a string. ``` -------------------------------- ### Kubeclient::Config Class Methods Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config Provides methods for interacting with the Kubeclient configuration, such as reading configuration files. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": 1, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Kubeclient::AmazonEksCredentials.token Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/AmazonEksCredentials This class method retrieves a bearer token for AWS EKS authentication. It requires AWS SDK gems to be installed. ```APIDOC ## Class Method: Kubeclient::AmazonEksCredentials.token ### Description Retrieves a bearer token for authenticating against AWS EKS. This method requires the `aws-sigv4`, `base64`, and `cgi` gems to be installed. ### Method Class Method ### Endpoint N/A (This is a class method for credential generation) ### Parameters - **credentials** (Object) - Required - AWS credentials object or hash. - **eks_cluster** (String) - Required - The name of the EKS cluster. - **region** (String) - Optional - The AWS region of the EKS cluster. Defaults to 'us-east-1'. ### Request Example ```ruby # Assuming 'credentials' and 'eks_cluster_name' are defined # token = Kubeclient::AmazonEksCredentials.token(credentials, eks_cluster_name, region: 'us-west-2') ``` ### Response #### Success Response (String) - **token** (String) - A bearer token for EKS authentication. #### Response Example ```json { "token": "k8s-aws-v1.aHR0cHM6Ly9zdHMu..." } ``` ### Error Handling - **Kubeclient::AmazonEksDependencyError** - Raised if the required AWS gems are not installed. ``` -------------------------------- ### Define DEFAULT_SSL_OPTIONS constant Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Sets the default SSL configuration for client connections. ```ruby { client_cert: nil, client_key: nil, ca_file: nil, cert_store: nil, verify_ssl: OpenSSL::SSL::VERIFY_PEER }.freeze ``` -------------------------------- ### Define Entity Methods Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Dynamically defines singleton methods for interacting with various Kubernetes entity types (e.g., get_pods, watch_nodes, create_secrets). ```APIDOC ## Dynamic Entity Method Definition ### Description This method automatically generates CRUD (Create, Read, Update, Delete) and watch methods for each supported Kubernetes entity type based on the `@entities` configuration. ### Method Initialization/Configuration ### Endpoint N/A (Internal configuration method) ### Parameters None ### Request Example N/A (This method configures the client object itself) ### Response - **Object** - Returns the client object after defining the entity methods. ``` -------------------------------- ### Kubeclient::GoogleApplicationDefaultCredentials.token Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/GoogleApplicationDefaultCredentials Retrieves a bearer token from Google's Application Default Credentials. This method requires the 'googleauth' gem to be installed in the calling application. ```APIDOC ## Class: Kubeclient::GoogleApplicationDefaultCredentials ### Description Get a bearer token from the Google’s application default credentials. ### Method Class Method ### Endpoint N/A (This is a class method for credential retrieval) ### Parameters None ### Request Body None ### Response #### Success Response (200) - **access_token** (string) - The bearer token obtained from Google. #### Response Example ```json { "access_token": "your_google_bearer_token" } ``` ### Error Handling - **GoogleDependencyError**: Raised if the 'googleauth' gem is not found. The calling application must include this gem. ``` -------------------------------- ### Initialize Kubeclient::Resource Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Resource Initializes a new instance of Resource, setting recurse_over_arrays to true. This is used for representing objects returned by Kubeclient. ```ruby def initialize(hash = nil, args = {}) args[:recurse_over_arrays] = true super(hash, args) end ``` -------------------------------- ### Client Configuration Options Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Default configuration constants used by the Kubeclient for connection management. ```APIDOC ## Configuration Constants ### DEFAULT_SSL_OPTIONS - client_cert (nil) - client_key (nil) - ca_file (nil) - cert_store (nil) - verify_ssl (OpenSSL::SSL::VERIFY_PEER) ### DEFAULT_AUTH_OPTIONS - username (nil) - password (nil) - bearer_token (nil) - bearer_token_file (nil) ### DEFAULT_TIMEOUTS - open (Net::HTTP open_timeout) - read (Net::HTTP read_timeout) ``` -------------------------------- ### Instance Attribute Details Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Details on instance attributes available in the Kubeclient gem. ```APIDOC ## Instance Attribute Details ### #**api_endpoint** ⇒ `Object` (readonly) Returns the value of attribute api_endpoint. ```ruby # File 'lib/kubeclient/common.rb', line 55 def api_endpoint @api_endpoint end ``` ### #**auth_options** ⇒ `Object` (readonly) Returns the value of attribute auth_options. ```ruby # File 'lib/kubeclient/common.rb', line 57 def auth_options @auth_options end ``` ### #**discovered** ⇒ `Object` (readonly) Returns the value of attribute discovered. ```ruby # File 'lib/kubeclient/common.rb', line 61 def discovered @discovered end ``` ### #**headers** ⇒ `Object` (readonly) Returns the value of attribute headers. ```ruby # File 'lib/kubeclient/common.rb', line 60 def headers @headers end ``` ### #**http_max_redirects** ⇒ `Object` (readonly) Returns the value of attribute http_max_redirects. ```ruby # File 'lib/kubeclient/common.rb', line 59 def http_max_redirects @http_max_redirects end ``` ### #**http_proxy_uri** ⇒ `Object` (readonly) Returns the value of attribute http_proxy_uri. ```ruby # File 'lib/kubeclient/common.rb', line 58 def http_proxy_uri @http_proxy_uri end ``` ### #**ssl_options** ⇒ `Object` (readonly) Returns the value of attribute ssl_options. ```ruby # File 'lib/kubeclient/common.rb', line 56 def ssl_options @ssl_options end ``` ``` -------------------------------- ### Respond to Missing Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Handles method calls that are not directly defined, often used for dynamic resource discovery. ```APIDOC ## respond_to_missing? ### Description Handles method calls that are not directly defined, often used for dynamic resource discovery. ### Method `respond_to_missing?` ### Parameters - **method_sym** (Symbol) - The symbol representing the method being called. - **include_private** (Boolean, optional) - Whether to include private methods in the check. Defaults to `false`. ### Response Returns `true` if the method can be handled (potentially after discovery), `false` otherwise. ``` -------------------------------- ### Read Kubeconfig File Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Config Builds a Config instance by parsing a given kubeconfig file. It handles YAML parsing with permitted classes and determines lookups relative to the file's directory. Supports different YAML loading methods based on Ruby version. ```ruby def self.read(filename) parsed = if RUBY_VERSION >= '2.6' YAML.safe_load(File.read(filename), permitted_classes: [Date, Time]) else YAML.safe_load(File.read(filename), [Date, Time]) end Config.new(parsed, File.dirname(filename)) end ``` -------------------------------- ### Dynamic Method Handling Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Explains how the Kubeclient gem handles dynamic method calls using `method_missing`. ```APIDOC ## Dynamic Method Handling This class handles dynamic methods through the `method_missing` method ### #**method_missing**(method_sym, *args, &block) ⇒ `Object` ```ruby # File 'lib/kubeclient/common.rb', line 100 def method_missing(method_sym, *args, &block) if discovery_needed?(method_sym) discover send(method_sym, *args, &block) else super end end ``` ``` -------------------------------- ### Class Method Details Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Details on class methods available in the Kubeclient gem. ```APIDOC ## Class Method Details ### .**parse_definition**(kind, name) ⇒ `Object` ``` -------------------------------- ### Rest Client Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Provides access to the underlying REST client instance, creating it if it doesn't exist. ```APIDOC ## rest_client ### Description Provides access to the underlying REST client instance, creating it if it doesn't exist. ### Method `rest_client` ### Response Returns the REST client object. ``` -------------------------------- ### Kubeclient Entity Methods Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin The ClientMixin module defines a set of standard entity operations available for Kubernetes resources. ```APIDOC ## Entity Operations ### Description The following methods are available for interacting with Kubernetes entities via the client: - get - watch - delete - create - update - patch - json_patch - merge_patch - apply ``` -------------------------------- ### Build Namespace Prefix Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Constructs the namespace prefix for API requests. If a namespace is provided, it appends it to the base path; otherwise, it returns an empty string. ```ruby def build_namespace_prefix(namespace) namespace.nil? || namespace.empty? ? '' : "/namespaces/#{namespace}" end ``` -------------------------------- ### Create Entity Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Sends a POST request to create a new Kubernetes entity. It handles namespace prefixing and ensures the original configuration object is not mutated. ```ruby def create_entity(entity_type, resource_name, entity_config) # Duplicate the entity_config to a hash so that when we assign # kind and apiVersion, this does not mutate original entity_config obj. hash = entity_config.to_hash ns_prefix = build_namespace_prefix(hash[:metadata][:namespace]) # TODO: temporary solution to add "kind" and apiVersion to request # until this issue is solved # https://github.com/GoogleCloudPlatform/kubernetes/issues/6439 hash[:kind] = entity_type hash[:apiVersion] = @api_group + @api_version response = handle_exception do rest_client[ns_prefix + resource_name] .post(hash.to_json, { 'Content-Type' => 'application/json' }.merge(get_headers)) end format_response(@as, response.body) end ``` -------------------------------- ### Implement resource_kind lookup method Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/Common/MissingKindCompatibility Retrieves the kind string for a given resource name from the MAPPING constant. ```ruby # File 'lib/kubeclient/missing_kind_compatibility.rb', line 65 def self.resource_kind(name) MAPPING[name] end ``` -------------------------------- ### Define ENTITY_METHODS constant Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Defines the list of supported HTTP methods for Kubernetes resources. ```ruby %w[get watch delete create update patch json_patch merge_patch apply].freeze ``` -------------------------------- ### Create Entity Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Creates a new entity (resource) within the Kubernetes cluster. It constructs the necessary API path and sends a POST request with the entity configuration. ```APIDOC ## POST /api/v1/{resource_name} ### Description Creates a new entity of a specified type with the given configuration. ### Method POST ### Endpoint `/api/v1/{resource_name}` (or similar, depending on API group and version) ### Parameters #### Path Parameters - **resource_name** (string) - Required - The name of the resource type (e.g., 'pods', 'nodes'). #### Request Body - **entity_config** (object) - Required - The configuration of the entity to be created, including metadata like namespace, name, labels, etc. ### Request Example ```json { "metadata": { "namespace": "default", "name": "my-pod" }, "spec": { "containers": [ { "name": "nginx", "image": "nginx:latest" } ] } } ``` ### Response #### Success Response (200 or 201) - **entity** (object) - The created entity object, including its status and metadata. ``` -------------------------------- ### Parse Kubernetes Resource Definition Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Parses Kubernetes resource definitions to derive singular and plural method names. Handles irregular names and infers underscores based on CamelCase boundaries. ```ruby def self.parse_definition(kind, name) # Kubernetes gives us 3 inputs: # kind: "ComponentStatus", "NetworkPolicy", "Endpoints" # name: "componentstatuses", "networkpolicies", "endpoints" # singularName: "componentstatus" etc (usually omitted, defaults to kind.downcase) # and want to derive singular and plural method names, with underscores: # "network_policy" # "network_policies" # kind's CamelCase word boundaries determine our placement of underscores. if IRREGULAR_NAMES[kind] # In a few cases, the given kind / singularName itself is still plural. # We require a distinct singular method name, so force it. method_names = IRREGULAR_NAMES[kind] else # TODO: respect singularName from discovery? # But how? If it differs from kind.downcase, kind's word boundaries don't apply. singular_name = kind.downcase if !(/[A-Z]/ =~ kind) # Some custom resources have a fully lowercase kind - can't infer underscores. method_names = [singular_name, name] else # Some plurals are not exact suffixes, e.g. NetworkPolicy -> networkpolicies. # So don't expect full last word to match. /^(?(.*[A-Z]))(?[^A-Z]*)$/ =~ kind # "NetworkP", "olicy" if name.start_with?(prefix.downcase) plural_suffix = name[prefix.length..-1] # "olicies" prefix_underscores = ClientMixin.underscore_entity(prefix) # "network_p" method_names = [prefix_underscores + singular_suffix, # "network_policy" prefix_underscores + plural_suffix] # "network_policies" else method_names = resolve_unconventional_method_names(name, kind, singular_name) end end end OpenStruct.new( entity_type: kind, resource_name: name, method_names: method_names ) end ``` -------------------------------- ### Define DEFAULT_AUTH_OPTIONS constant Source: https://www.rubydoc.info/gems/kubeclient/Kubeclient/ClientMixin Sets the default authentication options for client requests. ```ruby { username: nil, password: nil, bearer_token: nil, bearer_token_file: nil }.freeze ```