### Metrics Collection - SwiftMetrics Integration Source: https://github.com/swiftkube/client/blob/main/README.md Explains how Swiftkube client integrates with SwiftMetrics for collecting metrics and provides an example of bootstrapping a Prometheus client. ```APIDOC ## Metrics Collection ### Description The Swiftkube client utilizes SwiftMetrics to gather performance metrics, including request counts and latencies. This section outlines the available metrics and how to collect them. ### Available Metrics - **`sk_http_requests_total`** (counter): Total count of HTTP requests made by the client. - **`sk_http_request_errors_total`** (counter): Total count of HTTP requests that resulted in an error. - **`sk_request_errors_total`** (counter): Total count of requests that failed dispatch due to non-HTTP errors. - **`sk_http_request_duration_seconds`** (timer): Measures the duration of complete HTTP requests in seconds. ### Collecting Metrics with Prometheus To collect and expose these metrics, you need to bootstrap a metrics backend. The following example demonstrates how to use `SwiftPrometheus` to collect metrics and expose them via a `/metrics` endpoint, typically used in web frameworks like Vapor. ### Request Example ```swift import Metrics import Prometheus // Bootstrap Prometheus client let prom = PrometheusClient() MetricsSystem.bootstrap(prom) // Example of exposing metrics endpoint (e.g., in Vapor) // app.get("metrics") { request -> EventLoopFuture in // let promise = request.eventLoop.makePromise(of: String.self) // try MetricsSystem.prometheus().collect(into: promise) // return promise.futureResult // } ``` ### Response #### Success Response (This section is not applicable for metrics collection setup, as it's about configuring metric reporters.) ``` -------------------------------- ### Create Kubernetes Roles and RoleBindings with SwiftKube Source: https://context7.com/swiftkube/client/llms.txt Provides examples for creating Role objects to define permissions within a specific namespace and RoleBinding objects to grant those permissions to subjects (users, groups, or service accounts). Requires SwiftKube client setup. ```swift // Create a Role let role = rbac.v1.Role( metadata: meta.v1.ObjectMeta( name: "pod-reader", namespace: "default" ), rules: [ rbac.v1.PolicyRule( apiGroups: [""], resources: ["pods"], verbs: ["get", "watch", "list"] ), rbac.v1.PolicyRule( apiGroups: [""], resources: ["pods/log"], verbs: ["get"] ) ] ) try await client.rbacV1.roles.create(inNamespace: .default, role) // Create a RoleBinding let roleBinding = rbac.v1.RoleBinding( metadata: meta.v1.ObjectMeta( name: "read-pods-binding", namespace: "default" ), subjects: [ rbac.v1.Subject( kind: "ServiceAccount", name: "my-service-account", namespace: "default" ), rbac.v1.Subject( kind: "User", name: "jane@example.com", apiGroup: "rbac.authorization.k8s.io" ) ], roleRef: rbac.v1.RoleRef( apiGroup: "rbac.authorization.k8s.io", kind: "Role", name: "pod-reader" ) ) try await client.rbacV1.roleBindings.create(inNamespace: .default, roleBinding) ``` -------------------------------- ### Manually Configure Kubernetes Client in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Provides an example of completely manual configuration for the KubernetesClientConfig in Swift. This includes setting the master URL, namespace, authentication method (basic auth), trust roots, TLS verification settings, and timeouts. ```swift let caCert = try NIOSSLCertificate.fromPEMFile(caFile) let authentication = KubernetesClientAuthentication.basicAuth( username: "admin", password: "admin" ) let config = KubernetesClientConfig( masterURL: "https://kubernetesmaster", namespace: "default", authentication: authentication, trustRoots: NIOSSLTrustRoots.certificates(caCert), insecureSkipTLSVerify: false, timeout: HTTPClient.Configuration.Timeout.init(connect: .seconds(1), read: .seconds(10)), redirectConfiguration: HTTPClient.Configuration.RedirectConfiguration.follow(max: 5, allowCycles: false) ) let client = KubernetesClient(config: config) ``` -------------------------------- ### Get a Deployment in a Specific Namespace in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Illustrates fetching a specific Deployment resource from a given namespace using the SwiftKube client's DSL in Swift. It shows how to specify the namespace and the resource name. ```swift let deployment = try await client.appsV1.deployments.get(in: .namespace("ns"), name: "nginx") let roles = try await client.rbacV1.roles.get(in: .namespace("ns"), name: "role") ``` -------------------------------- ### Get Resources with Read Options in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Shows how to use `ReadOptions` when retrieving Kubernetes resources with the SwiftKube client in Swift. Options like `pretty`, `exact`, and `export` can be specified to customize the read operation. ```swift let deployments = try await client.appsV1.deployments.get(in: .allNamespaces, options: [ .pretty(true), .exact(false), .export(true) ]) ``` -------------------------------- ### Get and Update Resource Status Source: https://context7.com/swiftkube/client/llms.txt This code example shows how to retrieve and interpret the status of Kubernetes Deployments. It includes fetching details like available, ready, and updated replicas, as well as iterating through conditions to understand the deployment's health. It also demonstrates how a controller might update the status field, although direct status updates by users are generally discouraged. ```swift let deploymentStatus = try await client.appsV1.deployments.getStatus( in: .namespace("production"), name: "web-deployment" ) print("Available replicas: \(deploymentStatus.status?.availableReplicas ?? 0)") print("Ready replicas: \(deploymentStatus.status?.readyReplicas ?? 0)") print("Updated replicas: \(deploymentStatus.status?.updatedReplicas ?? 0)") if let conditions = deploymentStatus.status?.conditions { for condition in conditions { print("\ (condition.type ?? "unknown"): \(condition.status ?? "unknown")") if let message = condition.message { print(" Message: \(message)") } } } var deployment = try await client.appsV1.deployments.get( in: .default, name: "my-deployment" ) deployment.status?.replicas = 3 deployment.status?.readyReplicas = 3 let updatedStatus = try await client.appsV1.deployments.updateStatus( in: .default, name: "my-deployment", deployment ) ``` -------------------------------- ### Expose Metrics Endpoint with Vapor in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Provides an example of how to expose a '/metrics' endpoint using the Vapor web framework to allow Prometheus to scrape metrics collected by SwiftKubeClient. ```swift // if using vapor app.get("metrics") { request -> EventLoopFuture in let promise = request.eventLoop.makePromise(of: String.self) try MetricsSystem.prometheus().collect(into: promise) return promise.futureResult } ``` -------------------------------- ### GET /api/v1/namespaces/{namespace}/pods Source: https://context7.com/swiftkube/client/llms.txt Watches for changes to Pod resources in a specified namespace or all namespaces. ```APIDOC ## Watch Pods ### Description This endpoint provides a real-time stream of events for Pod resources, allowing monitoring of creation, modification, and deletion. ### Method GET ### Endpoint /api/v1/namespaces/{namespace}/pods ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace to watch Pods in. Use `.allNamespaces` for all namespaces. ### Request Example ```swift // Watch pods in all namespaces let task = try await client.pods.watch(in: .allNamespaces) let stream = await task.start() for try await event in stream { let pod = event.resource let name = pod.metadata?.name ?? "unknown" let namespace = pod.metadata?.namespace ?? "unknown" switch event.type { case .added: print("Pod created: \(namespace)/\(name)") print("Status: \(pod.status?.phase ?? "unknown")") case .modified: let ready = pod.status?.conditions?.first { $0.type == "Ready" }?.status == "True" print("Pod updated: \(namespace)/\(name) - Ready: \(ready)") case .deleted: print("Pod deleted: \(namespace)/\(name)") case .error: print("Watch error event") case .bookmark: print("Bookmark at resource version: \(pod.metadata?.resourceVersion ?? "")") } } // Cancel watching when done task.cancel() ``` ### Response #### Success Response (200) - **stream** - A stream of watch events, each containing the event type and the resource. #### Response Example ```json { "type": "ADDED", "resource": { "metadata": { "name": "my-pod", "namespace": "default", "creationTimestamp": "2023-10-27T10:30:00Z" }, "status": { "phase": "Running" } } } ``` ``` -------------------------------- ### Get Specific Resources by Name in Swift Source: https://context7.com/swiftkube/client/llms.txt Illustrates how to retrieve specific Kubernetes resources like namespaces, deployments, pods, and services by their names using the Swiftkube client. It also includes error handling for cases where a resource might not be found, specifically checking for a 404 status code. Requires the Swiftkube client library. ```swift // Get namespace let namespace = try await client.namespaces.get(name: "production") // Get deployment in specific namespace let deployment = try await client.appsV1.deployments.get( in: .namespace("production"), name: "web-server" ) print("Deployment replicas: (deployment.spec?.replicas ?? 0)") // Get pod with read options let pod = try await client.pods.get( in: .default, name: "nginx-pod", options: [ .pretty(true), .exact(false), .export(true) ] ) // Get service in system namespace let kubeProxy = try await client.services.get( in: .system, name: "kube-dns" ) // Error handling do { let pod = try await client.pods.get(in: .default, name: "nonexistent") } catch let SwiftkubeClientError.statusError(status) { if status.code == 404 { print("Pod not found") } else { print("Error: (status.message ?? "unknown error")") } } catch { print("Unexpected error: (error)") } ``` -------------------------------- ### Watch Kubernetes Resources in Real-Time with Swift Source: https://context7.com/swiftkube/client/llms.txt Demonstrates how to watch for real-time changes to Kubernetes Pods across all namespaces using the SwiftKube client. It initiates a watch stream, iterates over events (added, modified, deleted), and prints relevant information about the Pods. The example also shows how to cancel the watch task. This requires the SwiftKube client library and a configured Kubernetes client connection. ```swift // Watch pods in all namespaces let task = try await client.pods.watch(in: .allNamespaces) let stream = await task.start() for try await event in stream { let pod = event.resource let name = pod.metadata?.name ?? "unknown" let namespace = pod.metadata?.namespace ?? "unknown" switch event.type { case .added: print("Pod created: \(namespace)/\(name)") print("Status: \(pod.status?.phase ?? "unknown")") case .modified: let ready = pod.status?.conditions?.first { $0.type == "Ready" }?.status == "True" print("Pod updated: \(namespace)/\(name) - Ready: \(ready)") case .deleted: print("Pod deleted: \(namespace)/\(name)") case .error: print("Watch error event") case .bookmark: print("Bookmark at resource version: \(pod.metadata?.resourceVersion ?? "")") } } // Cancel watching when done task.cancel() ``` -------------------------------- ### Read Pod Logs (One-Shot) Source: https://context7.com/swiftkube/client/llms.txt This example shows how to retrieve all logs from a Kubernetes Pod's container in a single operation using the `logs` method. It supports various options, including specifying the container, retrieving logs from a previous instance of a container (after a crash or restart), enabling timestamps, and limiting the number of lines fetched (`tailLines`). ```swift let logs = try await client.pods.logs( in: .namespace("production"), name: "web-server-pod", container: "nginx" ) print(logs) let recentLogs = try await client.pods.logs( in: .default, name: "app-pod", container: "main", previous: false, timestamps: true, tailLines: 50 ) let crashLogs = try await client.pods.logs( in: .default, name: "crashed-pod", previous: true, timestamps: true ) print("Crash logs:\n\(crashLogs)") ``` -------------------------------- ### Type-Erased Resource Operations in SwiftKube Source: https://context7.com/swiftkube/client/llms.txt This Swift code demonstrates how to interact with Kubernetes resources when their types are not known at compile time. It shows how to create clients for unknown resource types using string names or `GroupVersionResource` objects, and how to perform GET and LIST operations returning `UnstructuredResource` objects. It also covers creating `GroupVersionResource` and `GroupVersionKind` from various sources. ```swift import KubernetesAPI // Assume 'client' is an authenticated Kubernetes client instance // Create client for unknown resource type using string name // guard let gvr = try? GroupVersionResource(for: "deployment") else { // throw NSError(domain: "Invalid resource type", code: 1) // } // Create unstructured client // let unstructuredClient = client.for(gvr: gvr) // Get resource as UnstructuredResource // let resource: UnstructuredResource = try await unstructuredClient.get( // in: .namespace("production"), // name: "web-deployment" // ) // print("Resource kind: (resource.kind ?? "unknown")") // print("API version: (resource.apiVersion ?? "unknown")") // print("Metadata: (resource.metadata ?? [:])") // print("Spec: (resource.spec ?? [:])") // List all resources // let resources: UnstructuredResourceList = try await unstructuredClient.list( // in: .allNamespaces // ) // for resource in resources.items { // let name = (resource.metadata?["name"] as? String) ?? "unknown" // let namespace = (resource.metadata?["namespace"] as? String) ?? "unknown" // print("\(namespace)/\(name)") // } // Create GroupVersionResource from various sources // let gvrFromType = GroupVersionResource(of: apps.v1.Deployment.self) // let gvrFromPlural = try GroupVersionResource(for: "configmaps") // let gvrFromSingular = try GroupVersionResource(for: "configmap") // let gvrFromShortName = try GroupVersionResource(for: "cm") // Create GroupVersionKind // let gvkFromType = GroupVersionKind(of: core.v1.Pod.self) // let gvkFromInstance = GroupVersionKind(of: resource) ``` -------------------------------- ### Create Kubernetes Deployment with Swift Source: https://context7.com/swiftkube/client/llms.txt Demonstrates how to create a new Kubernetes Deployment using the SwiftKube client. This includes defining the Deployment's metadata, specification, container details, resource requirements, and liveness probe. It requires the SwiftKube client library and a configured Kubernetes client connection. ```swift let deployment = apps.v1.Deployment( metadata: meta.v1.ObjectMeta( name: "web-deployment", namespace: "production", labels: ["app": "web"] ), spec: apps.v1.DeploymentSpec( replicas: 3, selector: meta.v1.LabelSelector( matchLabels: ["app": "web"] ), template: core.v1.PodTemplateSpec( metadata: meta.v1.ObjectMeta( labels: ["app": "web", "version": "v1"] ), spec: core.v1.PodSpec( containers: [ core.v1.Container( name: "web-server", image: "nginx:1.21", ports: [ core.v1.ContainerPort(containerPort: 80) ], resources: core.v1.ResourceRequirements( limits: ["cpu": "500m", "memory": "512Mi"], requests: ["cpu": "250m", "memory": "256Mi"] ), livenessProbe: core.v1.Probe( httpGet: core.v1.HTTPGetAction( path: "/health", port: 80 ), initialDelaySeconds: 10, periodSeconds: 5 ) ) ] ) ), strategy: apps.v1.DeploymentStrategy( type: "RollingUpdate", rollingUpdate: apps.v1.RollingUpdateDeployment( maxSurge: 1, maxUnavailable: 0 ) ) ) ) let created = try await client.appsV1.deployments.create( inNamespace: .namespace("production"), deployment ) print("Deployment created with \(created.spec?.replicas ?? 0) replicas") ``` -------------------------------- ### Initialize Kubernetes Client with Manual KubeConfig (Swift) Source: https://context7.com/swiftkube/client/llms.txt Demonstrates manual initialization of a KubernetesClient by loading KubeConfig from various sources such as YAML strings, file URLs, environment variables, default local config, or service accounts. It then creates a client configuration with an optional context name. Dependencies include SwiftkubeClient and KubeConfig. ```swift // Load kubeconfig from various sources let kubeConfig = try KubeConfig.from(config: "") let kubeConfig = try KubeConfig.from(url: URL(fileURLWithPath: "/path/to/config")) let kubeConfig = try KubeConfig.fromEnvironment(envVar: "KUBECONFIG") let kubeConfig = try KubeConfig.fromDefaultLocalConfig() let kubeConfig = try KubeConfig.fromServiceAccount() // Create client config from kubeconfig let config = try KubernetesClientConfig.from( kubeConfig: kubeConfig, contextName: "production-context" ) let client = KubernetesClient(config: config) ``` -------------------------------- ### Bootstrap Prometheus Metrics Backend in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Illustrates how to bootstrap a Prometheus metrics backend using SwiftMetrics and SwiftPrometheus. This is necessary for collecting and exposing metrics from the SwiftKubeClient. ```swift import Metrics import Prometheus let prom = PrometheusClient() MetricsSystem.bootstrap(prom) ``` -------------------------------- ### Swift Kubernetes Application: Init, Manage Deployments, Watch Pods Source: https://context7.com/swiftkube/client/llms.txt This Swift code demonstrates a full application workflow for interacting with Kubernetes using SwiftkubeClient. It initializes the client, sets up logging and metrics, retrieves cluster information, creates a deployment, watches for pod events related to that deployment, and finally cleans up the created deployment. It utilizes Swift's async/await for non-blocking operations and includes error handling and resource cleanup. ```swift import SwiftkubeClient import SwiftkubeModel import Logging import Metrics import Prometheus @main struct KubernetesApp { static func main() async throws { // Setup logging var logger = Logger(label: "com.example.k8s-app") logger.logLevel = .info // Setup metrics let prom = PrometheusClient() MetricsSystem.bootstrap(prom) // Create client guard let client = try? KubernetesClient(logger: logger) else { logger.error("Failed to initialize Kubernetes client") return } defer { try? client.syncShutdown() } // Get cluster information let version = try await client.discovery.serverVersion() logger.info("Connected to Kubernetes (version.gitVersion ?? "unknown")") // List all namespaces let namespaces = try await client.namespaces.list() logger.info("Found (namespaces.items.count) namespaces") // Create a deployment let deployment = apps.v1.Deployment( metadata: meta.v1.ObjectMeta( name: "app-deployment", labels: ["app": "myapp"] ), spec: apps.v1.DeploymentSpec( replicas: 3, selector: meta.v1.LabelSelector(matchLabels: ["app": "myapp"]), template: core.v1.PodTemplateSpec( metadata: meta.v1.ObjectMeta(labels: ["app": "myapp"]), spec: core.v1.PodSpec( containers: [ core.v1.Container( name: "app", image: "nginx:latest", ports: [core.v1.ContainerPort(containerPort: 80)] ) ] ) ) ) ) let created = try await client.appsV1.deployments.create( inNamespace: .default, deployment ) logger.info("Created deployment: (created.metadata?.name ?? "unknown")") // Watch pods let watchTask = try await client.pods.watch( in: .default, options: [.labelSelector(.eq(["app": "myapp"]))] ) Task { let stream = await watchTask.start() for try await event in stream { let pod = event.resource logger.info("Pod event: (event.type) - (pod.metadata?.name ?? "unknown")") } } // Wait and then cleanup try await Task.sleep(nanoseconds: 60_000_000_000) // 60 seconds watchTask.cancel() try await client.appsV1.deployments.delete( inNamespace: .default, name: "app-deployment" ) logger.info("Cleanup complete") } } ``` -------------------------------- ### Create Kubernetes Client Instance (Swift) Source: https://github.com/swiftkube/client/blob/main/README.md Initializes a Kubernetes client instance. Ensure to shut down the client when no longer needed to release resources. Supports synchronous, asynchronous, and callback-based shutdown. ```swift import SwiftkubeClient let client = try KubernetesClient()) ``` ```swift // when finished close the client try client.syncShutdown() // async/await try await client.shutdown() // DispatchQueue let queue: DispatchQueue = ... client.shutdown(queue: queue) { (error: Error?) in print(error) } ``` -------------------------------- ### Get and Update Resource Status Source: https://context7.com/swiftkube/client/llms.txt Provides methods to retrieve the current status of Kubernetes resources and, in some cases, update their status fields. ```APIDOC ## Get and Update Resource Status ### Description Retrieves the detailed status information for Kubernetes resources like Deployments, including replica counts and conditions. It also outlines how controllers typically update status. ### Method GET (to retrieve status), PUT (to update status, typically by controllers) ### Endpoint - `/apis/apps/v1/namespaces/{namespace}/deployments/{name}` (for getting full object including status) - `/apis/apps/v1/namespaces/{namespace}/deployments/{name}/status` (Conceptual - actual implementation is via client library methods) ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace of the resource. - **name** (string) - Required - The name of the Deployment. ### Request Example (Get Status) ```swift let deploymentStatus = try await client.appsV1.deployments.getStatus( in: .namespace("production"), name: "web-deployment" ) print("Available replicas: (deploymentStatus.status?.availableReplicas ?? 0)") print("Ready replicas: (deploymentStatus.status?.readyReplicas ?? 0)") if let conditions = deploymentStatus.status?.conditions { for condition in conditions { print("\(condition.type ?? "unknown"):\(condition.status ?? "unknown")") } } ``` ### Request Example (Update Status - Typically Controller Action) ```swift var deployment = try await client.appsV1.deployments.get( in: .default, name: "my-deployment" ) deployment.status?.replicas = 3 deployment.status?.readyReplicas = 3 let updatedStatus = try await client.appsV1.deployments.updateStatus( in: .default, name: "my-deployment", deployment ) ``` ### Response #### Success Response (200) - **status** (object) - Contains fields like `replicas`, `availableReplicas`, `readyReplicas`, and `conditions`. - **conditions** (array) - An array of status conditions, each with `type`, `status`, `lastTransitionTime`, `reason`, and `message`. #### Response Example ```json { "status": { "replicas": 3, "availableReplicas": 3, "readyReplicas": 3, "conditions": [ { "type": "Available", "status": "True", "lastTransitionTime": "...", "reason": "...", "message": "Deployment is available." } ] } } ``` ``` -------------------------------- ### List Namespaces using SwiftKube DSL in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Demonstrates how to list all available namespaces in a Kubernetes cluster using the SwiftKube client's DSL in Swift. This leverages asynchronous operations available through Swift concurrency. ```swift let namespaces = try await client.namespaces.list() ``` -------------------------------- ### Get a Specific Namespace in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Demonstrates how to retrieve a specific Kubernetes Namespace by its name using the SwiftKube client's DSL in Swift. This operation is asynchronous. ```swift let namespace = try await client.namespaces.get(name: "ns") ``` -------------------------------- ### Initialize GroupVersionKind and GroupVersionResource Source: https://github.com/swiftkube/client/blob/main/README.md Demonstrates various ways to initialize GroupVersionKind and GroupVersionResource. Initialization can be done from KubernetesAPIResource instances or types, full API group strings, singular/plural resource kinds, or short resource names. ```swift let deployment = .. let gvk = GroupVersionKind(of: deployment) let gvr = GroupVersionResource(of: deployment) let gvk = GroupVersionKind(of: apps.v1.Deployment.self) let gvr = GroupVersionResource(for: "configmaps") let gvk = GroupVersionKind(for: "cm") let gvr = GroupVersionResource(for: "cm") // etc. ``` -------------------------------- ### Create ConfigMap Resource in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Demonstrates creating a Kubernetes ConfigMap resource programmatically using the SwiftKube client and model definitions in Swift. It shows how to instantiate the ConfigMap object and post it to the cluster. ```swift // Create a resource instance and post it let configMap = core.v1.ConfigMap( metadata: meta.v1.ObjectMeta(name: "test"), data: ["foo": "bar"] ) try cm = try await client.configMaps.create(inNamespace: .default, configMap) ``` -------------------------------- ### Follow Kubernetes Pod Logs Source: https://github.com/swiftkube/client/blob/main/README.md Emits log lines from Kubernetes pods, similar to the watch API but for logs. The client does not automatically reconnect on errors in follow mode. The task must be explicitly started and can be cancelled to stop log streaming. ```swift let task = try await client.pods.follow(in: .default, name: "nginx", container: "app") for try await line in await task.start() { print(line) } // The task can be cancelled later to stop following logs task.cancel() ``` -------------------------------- ### Create Pod Resource using Builder in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Illustrates creating a Kubernetes Pod resource using a convenience builder pattern provided by SwiftKube in Swift. This allows for defining the Pod's metadata and spec in a more declarative and readable manner. ```swift // Or inline via a builder let pod = try await client.pods.create(inNamespace: .default) { sk.pod { $0.metadata = sk.metadata(name: "nginx") $0.spec = sk.podSpec { $0.containers = [ sk.container(name: "nginx") { $0.image = "nginx" } ] } } } ``` -------------------------------- ### Load Resources from Files Source: https://context7.com/swiftkube/client/llms.txt This section demonstrates how to load Kubernetes resources from local files (YAML/JSON) or remote URLs, and then create them using the client. ```APIDOC ## Load Resources from Files This section demonstrates how to load Kubernetes resources from local files (YAML/JSON) or remote URLs, and then create them using the client. ### Loading and Creating Resources #### Load deployment from file ```swift let fileURL = URL(fileURLWithPath: "/path/to/deployment.yaml") let deployment = try apps.v1.Deployment.load(contentsOf: fileURL) let created = try await client.appsV1.deployments.create( inNamespace: .namespace(deployment.metadata?.namespace ?? "default"), deployment ) ``` #### Load from URL ```swift let remoteURL = URL(string: "https://example.com/manifests/service.yaml")! let service = try core.v1.Service.load(contentsOf: remoteURL) try await client.services.create( inNamespace: .default, service ) ``` #### Load CRD from file ```swift let crdURL = URL(fileURLWithPath: "/path/to/custom-resource-definition.yaml") let crd = try apiextensions.v1.CustomResourceDefinition.load(contentsOf: crdURL) try await client.apiExtensionsV1.customResourceDefinitions.create(crd) ``` ``` -------------------------------- ### Watch Kubernetes Resources Source: https://github.com/swiftkube/client/blob/main/README.md Enables watching for Kubernetes events on specific objects. Opens a persistent connection represented by a SwiftkubeClientTask. The task must be started explicitly to receive events via an AsyncThrowingStream. Buffering is unbounded by default. Supports filtering with ListOptions and automatic reconnection with configurable RetryStrategy. ```swift let task: SwiftkubeClientTask = try await client.pods.watch(in: .allNamespaces) let stream = await task.start() for try await event in stream { print(event) } ``` ```swift let options = [ .labelSelector(.eq(["app": "nginx"])), .labelSelector(.exists(["env"])) ] let task = try await client.pods.watch(in: .default, options: options) ``` ```swift let strategy = RetryStrategy( policy: .maxAttemtps(20), backoff: .exponentiaBackoff(maxDelay: 60, multiplier: 2.0), initialDelay = 5.0, jitter = 0.2 ) let task = try await client.pods.watch(in: .default, retryStrategy: strategy) for try await event in await task.stream() { print(event) } ``` ```swift task.cancel() ``` -------------------------------- ### Define and Use Custom Kubernetes Resources in Swift Source: https://context7.com/swiftkube/client/llms.txt This Swift code defines custom resource types (CronTab, CronTabSpec, CronTabList) that conform to Kubernetes API resource protocols. It then demonstrates how to create a CustomResourceDefinition (CRD), install it, create a client for the custom resource, and perform create, list, update, and delete operations. ```swift import KubernetesAPI import KubernetesMeta // Step 1: Define the custom resource types struct CronTab: KubernetesAPIResource, NamespacedResource, MetadataHavingResource, ReadableResource, CreatableResource, ReplaceableResource, DeletableResource, ListableResource { typealias List = CronTabList var apiVersion = "example.com/v1" var kind = "CronTab" var metadata: meta.v1.ObjectMeta? var spec: CronTabSpec } struct CronTabSpec: Codable, Hashable, Sendable { var cronSpec: String var image: String var replicas: Int } struct CronTabList: KubernetesResourceList { var apiVersion = "example.com/v1" var kind = "CronTabList" var items: [CronTab] } // Step 2: Create the CRD definition let crd = apiextensions.v1.CustomResourceDefinition( metadata: meta.v1.ObjectMeta(name: "crontabs.example.com"), spec: apiextensions.v1.CustomResourceDefinitionSpec( group: "example.com", names: apiextensions.v1.CustomResourceDefinitionNames( plural: "crontabs", singular: "crontab", kind: "CronTab", shortNames: ["ct"] ), scope: "Namespaced", versions: [ apiextensions.v1.CustomResourceDefinitionVersion( name: "v1", served: true, storage: true, schema: apiextensions.v1.CustomResourceValidation( openAPIV3Schema: apiextensions.v1.JSONSchemaProps( type: "object", properties: [ "spec": apiextensions.v1.JSONSchemaProps( type: "object", properties: [ "cronSpec": apiextensions.v1.JSONSchemaProps(type: "string"), "image": apiextensions.v1.JSONSchemaProps(type: "string"), "replicas": apiextensions.v1.JSONSchemaProps(type: "integer") ] ) ] ) ) ) ] ) ) // Step 3: Install the CRD (assuming 'client' is an authenticated Kubernetes client) // try await client.apiExtensionsV1.customResourceDefinitions.create(crd) // Step 4: Create a client for the custom resource let gvr = GroupVersionResource( group: "example.com", version: "v1", resource: "crontabs" ) // let cronTabClient = client.for(CronTab.self, gvr: gvr) // Step 5: Use the custom resource like any other Kubernetes resource let cronTab = CronTab( metadata: meta.v1.ObjectMeta( name: "daily-report", namespace: "default" ), spec: CronTabSpec( cronSpec: "0 9 * * *", image: "report-generator:latest", replicas: 1 ) ) // let created = try await cronTabClient.create(in: .default, cronTab) // print("CronTab created: \(created.metadata?.name ?? "unknown")") // List all CronTabs // let allCronTabs: CronTabList = try await cronTabClient.list(in: .allNamespaces) // for cronTab in allCronTabs.items { // print("CronTab: \(cronTab.metadata?.name ?? "unknown")") // print(" Schedule: \(cronTab.spec.cronSpec)") // print(" Image: \(cronTab.spec.image)") // } // Update a CronTab // var updated = created // updated.spec.replicas = 2 // try await cronTabClient.update(in: .default, updated) // Delete a CronTab // try await cronTabClient.delete(in: .default, name: "daily-report") ``` -------------------------------- ### POST /apis/apps/v1/namespaces/{namespace}/deployments Source: https://context7.com/swiftkube/client/llms.txt Creates a new Kubernetes Deployment in the specified namespace. ```APIDOC ## Create a Deployment ### Description This endpoint allows for the creation of a new Deployment resource within a specified Kubernetes namespace. It accepts a Deployment object definition and returns the created Deployment upon success. ### Method POST ### Endpoint /apis/apps/v1/namespaces/{namespace}/deployments ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace in which to create the Deployment. #### Request Body - **deployment** (apps.v1.Deployment) - Required - The Deployment object to create. ### Request Example ```swift let deployment = apps.v1.Deployment( metadata: meta.v1.ObjectMeta( name: "web-deployment", namespace: "production", labels: ["app": "web"] ), spec: apps.v1.DeploymentSpec( replicas: 3, selector: meta.v1.LabelSelector( matchLabels: ["app": "web"] ), template: core.v1.PodTemplateSpec( metadata: meta.v1.ObjectMeta( labels: ["app": "web", "version": "v1"] ), spec: core.v1.PodSpec( containers: [ core.v1.Container( name: "web-server", image: "nginx:1.21", ports: [ core.v1.ContainerPort(containerPort: 80) ], resources: core.v1.ResourceRequirements( limits: ["cpu": "500m", "memory": "512Mi"], requests: ["cpu": "250m", "memory": "256Mi"] ), livenessProbe: core.v1.Probe( httpGet: core.v1.HTTPGetAction( path: "/health", port: 80 ), initialDelaySeconds: 10, periodSeconds: 5 ) ) ] ) ), strategy: apps.v1.DeploymentStrategy( type: "RollingUpdate", rollingUpdate: apps.v1.RollingUpdateDeployment( maxSurge: 1, maxUnavailable: 0 ) ) ) ) let created = try await client.appsV1.deployments.create( inNamespace: .namespace("production"), deployment ) print("Deployment created with \(created.spec?.replicas ?? 0) replicas") ``` ### Response #### Success Response (200) - **createdDeployment** (apps.v1.Deployment) - The Deployment object that was created. #### Response Example ```json { "metadata": { "name": "web-deployment", "namespace": "production", "creationTimestamp": "2023-10-27T10:00:00Z" }, "spec": { "replicas": 3 } } ``` ``` -------------------------------- ### List Deployments with Namespace Filtering in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Illustrates listing Deployments within a specific namespace or across all namespaces using the SwiftKube client's DSL in Swift. It shows how to target different API groups like 'appsV1'. ```swift let deployments = try await client.appsV1.deployments.list(in: .allNamespaces) let roles = try await client.rbacV1.roles.list(in: .namespace("ns")) ``` -------------------------------- ### Create, List, and Delete Kubernetes Jobs with SwiftKube Source: https://context7.com/swiftkube/client/llms.txt Demonstrates how to create a new Job, list existing Jobs across all namespaces, and delete a specific Job. This requires the SwiftKube client library and appropriate Kubernetes API access. ```swift let job = batch.v1.Job( metadata: meta.v1.ObjectMeta( name: "data-processing-job", namespace: "default" ), spec: batch.v1.JobSpec( parallelism: 3, completions: 10, backoffLimit: 3, template: core.v1.PodTemplateSpec( spec: core.v1.PodSpec( containers: [ core.v1.Container( name: "processor", image: "data-processor:latest", command: ["/bin/process"], args: ["--batch-size", "100"] ) ], restartPolicy: "OnFailure" ) ) ) ) let createdJob = try await client.batchV1.jobs.create( inNamespace: .default, job ) // List jobs let jobs = try await client.batchV1.jobs.list(in: .allNamespaces) for job in jobs.items { let name = job.metadata?.name ?? "unknown" let succeeded = job.status?.succeeded ?? 0 let failed = job.status?.failed ?? 0 print("Job: \(name) - Succeeded: \(succeeded), Failed: \(failed)") } // Delete completed job try await client.batchV1.jobs.delete( inNamespace: .default, name: "data-processing-job", options: meta.v1.DeleteOptions(propagationPolicy: "Background") ) ``` -------------------------------- ### Initialize Kubernetes Client with Auto-Discovery (Swift) Source: https://context7.com/swiftkube/client/llms.txt Initializes a KubernetesClient with automatic configuration discovery from kubeconfig files, service accounts, or environment variables. Demonstrates asynchronous shutdown and synchronous shutdown with completion callbacks. Dependencies include SwiftkubeClient. ```swift import SwiftkubeClient // Automatic configuration discovery from kubeconfig or service account let client = try KubernetesClient() // Shutdown when done try await client.shutdown() // Or synchronous shutdown try client.syncShutdown() // Or with completion callback let queue: DispatchQueue = DispatchQueue.global() client.shutdown(queue: queue) { error in if let error = error { print("Shutdown error: (error)") } } ``` -------------------------------- ### List Kubernetes Resources Across Namespaces (Swift) Source: https://context7.com/swiftkube/client/llms.txt Demonstrates listing Kubernetes resources such as namespaces, deployments, and pods across different scopes using the SwiftkubeClient. It shows how to list cluster-scoped resources, resources in all namespaces, a specific namespace, the default namespace, or the system namespace. Dependencies include SwiftkubeClient and SwiftkubeModel. ```swift import SwiftkubeClient import SwiftkubeModel let client = try KubernetesClient() // List all namespaces (cluster-scoped) let namespaces = try await client.namespaces.list() for namespace in namespaces.items { print("Namespace: (namespace.metadata?.name ?? "unknown")") } // List deployments in all namespaces let allDeployments = try await client.appsV1.deployments.list(in: .allNamespaces) print("Total deployments: (allDeployments.items.count)") // List pods in specific namespace let pods = try await client.pods.list(in: .namespace("production")) // List in default namespace (uses client config's namespace) let configMaps = try await client.configMaps.list(in: .default) // List in system namespace let systemPods = try await client.pods.list(in: .system) ``` -------------------------------- ### Initialize Kubernetes Client with KubeConfig in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Shows how to initialize the KubernetesClientConfig using a pre-loaded KubeConfig object in Swift. It also highlights the option to specify a context name, defaulting to 'current-context' if not provided. ```swift let kubeConfig = KubeConfig.fromDefaultLocalConfig() let config = KubernetesClientConfig.from( kubeConfig: kubeConfig, contextName: "some-context" // if not provided, then "current-context" is used ) ``` -------------------------------- ### Manage Custom CronTab Resources with SwiftKubeClient Source: https://github.com/swiftkube/client/blob/main/README.md Shows how to instantiate a client for a custom resource (CronTab) and perform create and list operations. This leverages the custom structs defined for CRDs and the SwiftKubeClient. ```swift let gvr = GroupVersionResource( group: "example.com", version: "v1", resource: "crontabs" ) let cronTabClient = client.for(CronTab.self, gvr: gvr) let cronTab = CronTab( metadata: meta.v1.ObjectMeta(name: "new-cron"), spec: CronTabSpec( cronSpec : "* * * * */5", image: "some-cron-image", replicas: 2 ) ) let new = try await cronTabClient.create(in: .default, cronTab) let cronTabs: CronTabList = try await cronTabClient.list(in: .allNamespaces) ``` -------------------------------- ### Load Kubernetes Resources from Files (Swift) Source: https://context7.com/swiftkube/client/llms.txt Demonstrates how to load Kubernetes resources such as Deployments, Services, and CustomResourceDefinitions from local files or remote URLs using the SwiftKube client. It covers loading YAML or JSON content and creating the resources on the cluster. ```swift // Load deployment from file let fileURL = URL(fileURLWithPath: "/path/to/deployment.yaml") let deployment = try apps.v1.Deployment.load(contentsOf: fileURL) // Create the loaded resource let created = try await client.appsV1.deployments.create( inNamespace: .namespace(deployment.metadata?.namespace ?? "default"), deployment ) // Load from URL let remoteURL = URL(string: "https://example.com/manifests/service.yaml")! let service = try core.v1.Service.load(contentsOf: remoteURL) try await client.services.create( inNamespace: .default, service ) // Load CRD from file let crdURL = URL(fileURLWithPath: "/path/to/custom-resource-definition.yaml") let crd = try apiextensions.v1.CustomResourceDefinition.load(contentsOf: crdURL) try await client.apiExtensionsV1.customResourceDefinitions.create(crd) ``` -------------------------------- ### Batch Operations - Jobs and CronJobs Source: https://context7.com/swiftkube/client/llms.txt Documentation for managing Kubernetes Jobs and CronJobs, covering creation, listing, and status checks. ```APIDOC ## Batch Operations - Jobs and CronJobs ### Description This section details how to manage batch workloads in Kubernetes using Jobs (for one-off tasks) and CronJobs (for scheduled tasks). Operations include creating, listing, getting, and observing the status of these resources. ### Method GET, POST, PUT, DELETE (for Jobs and CronJobs) ### Endpoint - `/apis/batch/v1/namespaces/{namespace}/jobs` - `/apis/batch/v1/namespaces/{namespace}/cronjobs` (Conceptual - actual implementation is via client library methods) ### Parameters (Specific parameters for creating/updating Jobs and CronJobs would be detailed here, including JobSpec and CronJobSpec fields like `template`, `schedule`, `concurrencyPolicy`, etc.) ### Request Example (Conceptual - Creating a Job) ```swift // Define a Job object with a container spec let job = Job( // ... metadata ... spec: JobSpec( template: PodTemplateSpec( spec: PodSpec( containers: [Container(name: "task-container", image: "my-batch-image")] ) ) ) ) try await client.batchV1.jobs.create(in: .default, job: job) ``` ### Response #### Success Response (200) - **items** (array) - A list of Job or CronJob objects. - **status** (object) - Status information for a specific Job or CronJob, including `succeeded`, `failed`, `active` counts, and `lastScheduleTime` for CronJobs. #### Response Example (Job Status) ```json { "status": { "succeeded": 1, "failed": 0, "active": 0 } } ``` ``` -------------------------------- ### List Resources with Options in Swift Source: https://github.com/swiftkube/client/blob/main/README.md Shows how to apply advanced filtering and limiting options when listing Kubernetes resources using the SwiftKube client's DSL in Swift. Supported options include label selectors, field selectors, resource version, and limiting the number of results. ```swift let deployments = try await client.appsV1.deployments.list(in: .allNamespaces, options: [ .labelSelector(.eq(["app": "nginx"])), .labelSelector(.notIn(["env": ["dev", "staging"]])), .labelSelector(.exists(["app", "env"])), .fieldSelector(.eq(["status.phase": "Running"])), .resourceVersion("9001"), .limit(20), .timeoutSeconds(10) ]) ```