### Register Kuberesolver and Expose Prometheus Metrics in Go Source: https://context7.com/sercand/kuberesolver/llms.txt Register kuberesolver to automatically expose Prometheus metrics for monitoring endpoint discovery. This example also shows how to create a gRPC connection and expose metrics via HTTP. ```go package main import ( "net/http" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { // Register kuberesolver (automatically registers Prometheus metrics) kuberesolver.RegisterInCluster() // Create gRPC connection conn, _ := grpc.NewClient( "kubernetes:///my-service.default:8080", grpc.WithTransportCredentials(insecure.NewCredentials()), ) defer conn.Close() // Expose Prometheus metrics endpoint // Available metrics: // - kuberesolver_endpoints_total{target="..."} - Number of endpoints for a target // - kuberesolver_addresses_total{target="..."} - Number of addresses for a target // - kuberesolver_client_last_update{target="..."} - Unix timestamp of last update http.Handle("/metrics", promhttp.Handler()) http.ListenAndServe(":9090", nil) } ``` -------------------------------- ### Implement K8sClient Interface in Go Source: https://context7.com/sercand/kuberesolver/llms.txt Implement the K8sClient interface to create custom Kubernetes clients for specialized authentication or proxy scenarios. This example shows a client with API key authentication. ```go package main import ( "net/http" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc/resolver" ) // CustomK8sClient implements the kuberesolver.K8sClient interface type CustomK8sClient struct { baseURL string httpClient *http.Client apiKey string } func (c *CustomK8sClient) Do(req *http.Request) (*http.Response, error) { return c.httpClient.Do(req) } func (c *CustomK8sClient) GetRequest(url string) (*http.Request, error) { req, err := http.NewRequest("GET", c.baseURL+"/"+url, nil) if err != nil { return nil, err } // Add custom authentication header req.Header.Set("X-API-Key", c.apiKey) return req, nil } func (c *CustomK8sClient) Host() string { return c.baseURL } func main() { // Create custom client with API key authentication client := &CustomK8sClient{ baseURL: "https://kubernetes.example.com", httpClient: &http.Client{}, apiKey: "my-api-key", } // Use custom client with kuberesolver builder := kuberesolver.NewBuilder(client, "kubernetes") resolver.Register(builder) } ``` -------------------------------- ### Kubernetes Service URL Formats Source: https://github.com/sercand/kuberesolver/blob/master/README.md Examples of valid URL formats for specifying Kubernetes services with kuberesolver. The cluster name is optional for resolution. ```plaintext kubernetes:///service-name:8080 kubernetes:///service-name:portname kubernetes:///service-name.namespace:8080 kubernetes:///service-name.namespace.svc.cluster_name kubernetes:///service-name.namespace.svc.cluster_name:8080 kubernetes://namespace/service-name:8080 kubernetes://service-name:8080/ kubernetes://service-name.namespace:8080/ kubernetes://service-name.namespace.svc.cluster_name kubernetes://service-name.namespace.svc.cluster_name:8080 ``` -------------------------------- ### Create Kuberesolver Builder with Custom Client Source: https://context7.com/sercand/kuberesolver/llms.txt Creates a new kuberesolver builder with a custom Kubernetes client, suitable for testing or connecting via a proxy. The builder is then registered with gRPC. ```go package main import ( "log" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/resolver" ) func main() { // Create a custom insecure client for connecting via kubectl proxy client := kuberesolver.NewInsecureK8sClient("http://127.0.0.1:8001") // Create and register the builder with the custom client builder := kuberesolver.NewBuilder(client, "kubernetes") resolver.Register(builder) // Create gRPC connection using the registered resolver conn, err := grpc.NewClient( "kubernetes:///my-service.default:8080", grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { log.Fatalf("failed to connect: %v", err) } defer conn.Close() } ``` -------------------------------- ### Kubernetes Target URL Formats for gRPC Source: https://context7.com/sercand/kuberesolver/llms.txt Demonstrates various URL formats supported by the Kubernetes resolver for specifying services, including numeric and named ports, explicit namespaces, and fully qualified domain names. ```go package main import ( "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { kuberesolver.RegisterInCluster() opts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`), } // Format 1: Service with numeric port (uses current namespace) conn1, _ := grpc.NewClient("kubernetes:///my-service:8080", opts...) defer conn1.Close() // Format 2: Service with named port (resolves port name from EndpointSlice) conn2, _ := grpc.NewClient("kubernetes:///my-service:grpc", opts...) defer conn2.Close() // Format 3: Service with explicit namespace using dot notation conn3, _ := grpc.NewClient("kubernetes:///my-service.production:8080", opts...) defer conn3.Close() // Format 4: Fully qualified domain name conn4, _ := grpc.NewClient("kubernetes:///my-service.production.svc.cluster.local:8080", opts...) defer conn4.Close() // Format 5: Namespace in authority (host) part conn5, _ := grpc.NewClient("kubernetes://production/my-service:8080", opts...) defer conn5.Close() // Format 6: Service.namespace in authority part conn6, _ := grpc.NewClient("kubernetes://my-service.production:8080/", opts...) defer conn6.Close() } ``` -------------------------------- ### Register Kuberesolver for In-Cluster Use Source: https://github.com/sercand/kuberesolver/blob/master/README.md Import and register the kuberesolver module with gRPC before creating a client. This enables resolution of addresses using the 'kubernetes' schema. ```go // Import the module import "github.com/sercand/kuberesolver/v6" // Register kuberesolver to grpc before calling grpc.NewClient kuberesolver.RegisterInCluster() // it is same as resolver.Register(kuberesolver.NewBuilder(nil /*custom kubernetes client*/ , "kubernetes")) // if schema is 'kubernetes' then grpc will use kuberesolver to resolve addresses cc, err := grpc.NewClient("kubernetes:///service.namespace:portname", opts...) ``` -------------------------------- ### Create In-Cluster Kubernetes Client Source: https://context7.com/sercand/kuberesolver/llms.txt Manually creates an in-cluster Kubernetes client, automatically reading service account credentials and CA certificates. This client can be used with a custom builder and automatically handles token rotation. ```go package main import ( "log" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc/resolver" ) func main() { // Create an in-cluster Kubernetes client manually client, err := kuberesolver.NewInClusterK8sClient() if err != nil { log.Fatalf("failed to create k8s client: %v", err) } // Use the client with a custom builder builder := kuberesolver.NewBuilder(client, "kubernetes") resolver.Register(builder) // The client automatically: // - Reads token from /var/run/secrets/kubernetes.io/serviceaccount/token // - Reads CA cert from /var/run/secrets/kubernetes.io/serviceaccount/ca.crt // - Uses KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT env vars // - Watches for token rotation and updates automatically } ``` -------------------------------- ### Enable Client-Side Load Balancing with Round Robin Source: https://github.com/sercand/kuberesolver/blob/master/README.md Configure gRPC with a load balancing policy, such as 'round_robin', when creating a new client to distribute connections across service endpoints. ```go grpc.NewClient( "kubernetes:///service:grpc", grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`), grpc.WithTransportCredentials(insecure.NewCredentials()), ) ``` -------------------------------- ### Register Kuberesolver In-Cluster Source: https://context7.com/sercand/kuberesolver/llms.txt Registers the kuberesolver with gRPC using the default 'kubernetes' schema. This automatically creates an in-cluster Kubernetes client using service account credentials. Call this before creating gRPC connections. ```go package main import ( "log" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { // Register kuberesolver with gRPC before creating any connections kuberesolver.RegisterInCluster() // Create a gRPC client connection using the kubernetes:/// scheme conn, err := grpc.NewClient( "kubernetes:///my-service.default:8080", grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { log.Fatalf("failed to connect: %v", err) } defer conn.Close() // Use the connection for your gRPC client // client := pb.NewMyServiceClient(conn) } ``` -------------------------------- ### Register Kuberesolver with Alternative Schema Source: https://github.com/sercand/kuberesolver/blob/master/README.md Use `RegisterInClusterWithSchema` to specify a custom schema for kuberesolver instead of the default 'kubernetes'. ```go Use RegisterInClusterWithSchema(schema) instead of RegisterInCluster on start. ``` -------------------------------- ### Create Insecure Kubernetes Client Source: https://context7.com/sercand/kuberesolver/llms.txt Use this to create a Kubernetes client that bypasses TLS authentication, suitable for development environments connected via kubectl proxy. Ensure kubectl proxy is running before execution. ```go package main import ( "fmt" "log" "net/http" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc/resolver" ) func main() { // Start kubectl proxy in another terminal: kubectl proxy --port=8001 // Create an insecure client pointing to the proxy client := kuberesolver.NewInsecureK8sClient("http://127.0.0.1:8001") // Verify connectivity by making a request req, _ := client.GetRequest("/api/v1/namespaces") resp, err := client.Do(req) if err != nil { log.Fatalf("failed to connect to kubernetes API: %v", err) } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { fmt.Println("Successfully connected to Kubernetes API") } // Register the builder with this client builder := kuberesolver.NewBuilder(client, "kubernetes") resolver.Register(builder) } ``` -------------------------------- ### Apply RBAC Configuration using kubectl Source: https://context7.com/sercand/kuberesolver/llms.txt Apply the RBAC configuration defined in rbac.yaml using kubectl. This command ensures the necessary permissions are granted to the service account. ```bash # Apply the RBAC configuration kubectl apply -f rbac.yaml # Verify the service account has the correct permissions kubectl auth can-i get endpointslices --as=system:serviceaccount:default:my-app kubectl auth can-i watch endpointslices --as=system:serviceaccount:default:my-app ``` -------------------------------- ### gRPC Client-Side Load Balancing with Round Robin Source: https://context7.com/sercand/kuberesolver/llms.txt Configure gRPC to use round-robin load balancing for distributing requests evenly across discovered Kubernetes service endpoints. This enables zero-downtime deployments by automatically adapting to endpoint changes. ```go package main import ( "context" "log" "time" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { kuberesolver.RegisterInCluster() // Create connection with round-robin load balancing conn, err := grpc.NewClient( "kubernetes:///my-service.default:grpc", grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`), grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { log.Fatalf("failed to connect: %v", err) } defer conn.Close() // Each RPC call will be routed to different endpoints in round-robin fashion // The resolver automatically updates endpoints when pods scale or restart ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Example: Make multiple calls that will be distributed across endpoints for i := 0; i < 10; i++ { // client.SomeRPCMethod(ctx, request) _ = ctx // Calls will be distributed across all healthy endpoints } } ``` -------------------------------- ### Register Kuberesolver with Custom Schema Source: https://context7.com/sercand/kuberesolver/llms.txt Registers the kuberesolver builder with a custom schema name, allowing for multiple resolver configurations or avoiding naming conflicts. Use the custom schema in your connection string. ```go package main import ( "log" "github.com/sercand/kuberesolver/v6" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) func main() { // Register with a custom schema name kuberesolver.RegisterInClusterWithSchema("k8s") // Use the custom schema in your connection string conn, err := grpc.NewClient( "k8s:///my-service.production:grpc", grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { log.Fatalf("failed to connect: %v", err) } defer conn.Close() } ``` -------------------------------- ### Kubernetes RBAC Configuration for EndpointSlice Access Source: https://context7.com/sercand/kuberesolver/llms.txt Apply this YAML configuration to grant the 'endpointslice-reader' ClusterRole to a service account, allowing kuberesolver to watch EndpointSlice resources. ```yaml # rbac.yaml - Required Kubernetes RBAC configuration for kuberesolver apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: endpointslice-reader rules: - apiGroups: ["discovery.k8s.io"] resources: ["endpointslices"] verbs: ["get", "watch", "list"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: my-app-endpointslice-reader subjects: - kind: ServiceAccount name: my-app namespace: default roleRef: kind: ClusterRole name: endpointslice-reader apiGroup: rbac.authorization.k8s.io ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.