Documentation
¶
Overview ¶
Package k8cache provides caching utilities for Kubernetes API responses. It includes middleware for intercepting cluster API requests, generating unique cache keys, storing and retrieving responses, and invalidating entries when resources change. The package aims to reduce redundant API calls, improve performance, and handle authorization gracefully while maintaining consistency across multiple Kubernetes contexts.
Package k8cache provides caching utilities for Kubernetes API responses. It includes middleware for intercepting cluster API requests, generating unique cache keys, storing and retrieving responses, and invalidating entries when resources change. The package aims to reduce redundant API calls, improve performance, and handle authorization gracefully while maintaining consistency across multiple Kubernetes contexts.
Package k8cache provides caching utilities for Kubernetes API responses. It includes middleware for intercepting cluster API requests, generating unique cache keys, storing and retrieving responses, and invalidating entries when resources change. The package aims to reduce redundant API calls, improve performance, and handle authorization gracefully while maintaining consistency across multiple Kubernetes contexts.
Copyright 2025 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Package k8cache provides caching utilities for Kubernetes API responses. It includes middleware for intercepting cluster API requests, generating unique cache keys, storing and retrieving responses, and invalidating entries when resources change. The package aims to reduce redundant API calls, improve performance, and handle authorization gracefully while maintaining consistency across multiple Kubernetes contexts.
Index ¶
- func CheckForChanges(k8scache cache.Cache[string], contextKey string, kContext kubeconfig.Context)
- func DeleteKeys(key string, k8scache cache.Cache[string])
- func ExtractNamespace(rawURL string) (string, string)
- func FilterHeaderForCache(responseHeaders http.Header, encoding string) http.Header
- func GenerateKey(url *url.URL, contextID string) (string, error)
- func GetAPIGroup(path string) (apiGroup, version string, err error)
- func GetClientSet(k *kubeconfig.Context, token string) (*kubernetes.Clientset, error)
- func GetKindAndVerb(r *http.Request) (string, string)
- func GetResponseBody(bodyBytes []byte, encoding string) (string, error)
- func HandleNonGETCacheInvalidation(k8scache cache.Cache[string], w http.ResponseWriter, r *http.Request, ...) error
- func IsAllowed(k *kubeconfig.Context, r *http.Request) (bool, error)
- func IsAuthBypassURL(urlPath string) bool
- func LoadFromCache(k8scache cache.Cache[string], isAllowed bool, key string, ...) (bool, error)
- func ReturnAuthErrorResponse(w http.ResponseWriter, r *http.Request, contextKey string) error
- func RunInformerToWatch(gvrList []schema.GroupVersionResource, ...)
- func ServeFromCacheOrForwardToK8s(k8scache cache.Cache[string], isAllowed bool, next http.Handler, key string, ...)
- func SetHeader(cacheData CachedResponseData, w http.ResponseWriter)
- func SkipWebSocket(r *http.Request, next http.Handler, w http.ResponseWriter) bool
- func StoreK8sResponseInCache(k8scache cache.Cache[string], url *url.URL, rcw *ResponseCapture, ...) error
- func WriteResponseToClient(response []byte, w http.ResponseWriter) error
- type AuthErrResponse
- type CacheKey
- type CachedClientSet
- type CachedResponseData
- type Details
- type Metadata
- type ResponseCapture
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckForChanges ¶
func CheckForChanges( k8scache cache.Cache[string], contextKey string, kContext kubeconfig.Context, )
CheckForChanges lets 1 go routine to run for a contextKey which prevents running go routines for every requests which can become performance issue if there are many resource and events are going on.
func DeleteKeys ¶
DeleteKeys deletes keys from the cache if data is present in cache, this delete keys having namespace non-empty and also empty namespace.
func ExtractNamespace ¶
ExtractNamespace extracts the namespace from the parameter from the given raw URL. This is used to make cache key more specific to a particular namespace.
func FilterHeaderForCache ¶
FilterHeaderForCache ensures that the cached headers accurately reflect the state of the decompressed body that is being stored, and prevents client side decompression issues serving from cache.
func GenerateKey ¶
GenerateKey function helps to generate a unique key based on the request from the client The function accepts url( which includes all the information of request ) and contextID which helps to differentiate in multiple contexts.
func GetAPIGroup ¶
GetAPIGroup parses the URL path and returns the apiGroup and version.
func GetClientSet ¶
func GetClientSet(k *kubeconfig.Context, token string) (*kubernetes.Clientset, error)
GetClientSet return *kubernetes.ClientSet and error which further used for creating SSAR requests to k8s server to authorize user. GetClientSet uses kubeconfig.Context and authentication bearer token which will help to create clientSet based on the user's identity.
func GetKindAndVerb ¶
GetKindAndVerb extracts the Kubernetes resource kind and intended verb (e.g., get, watch) from the incoming HTTP request.
func GetResponseBody ¶
GetResponseBody decompresses a gzip-encoded response body and returns it as a string. If the encoding is not gzip, it returns the raw body as a string.
func HandleNonGETCacheInvalidation ¶
func HandleNonGETCacheInvalidation(k8scache cache.Cache[string], w http.ResponseWriter, r *http.Request, next http.Handler, contextKey string, ) error
handleNonGetInvalidation handle request which are modifying eg. POST/DELETE/PUT and delete keys if the data is present in the cache, if present PURGE the keys from the cache and make a fresh new request to k8s server and store into the cache, the cache has now latest changes.
func IsAllowed ¶
IsAllowed checks the user's permission to access the resource. If the user is authorized and has permission to view the resources, it returns true. Otherwise, it returns false if authorization fails.
func IsAuthBypassURL ¶
IsAuthBypassURL returns true if the given URL path should be checked for authorization errors, excluding known public or health-check endpoints.
func LoadFromCache ¶
func LoadFromCache(k8scache cache.Cache[string], isAllowed bool, key string, w http.ResponseWriter, r *http.Request, ) (bool, error)
LoadFromCache checks if a cached resource exists and the user has permission to view it. If found, it writes the cached data to the ResponseWriter and returns (true, nil). If not found or on error, it returns (false, error).
func ReturnAuthErrorResponse ¶
ReturnAuthErrorResponse return the AuthErrorResponse if the user is not Authorized this will returns directly without asking to K8's Server.
func RunInformerToWatch ¶
func RunInformerToWatch(gvrList []schema.GroupVersionResource, factory dynamicinformer.DynamicSharedInformerFactory, contextKey string, k8scache cache.Cache[string], )
runInformerToWatch watches changes such as Addition, Deletion and Updation of a resource and if so capture the data into the key and store all unique keys, and return unique keys which will be delete in runWatcher.
func ServeFromCacheOrForwardToK8s ¶
func ServeFromCacheOrForwardToK8s(k8scache cache.Cache[string], isAllowed bool, next http.Handler, key string, w http.ResponseWriter, r *http.Request, rcw *ResponseCapture, )
ServeFromCacheOrForwardToK8s attempts to serve a Kubernetes resource from cache. If no cached value is found (or `isAllowed` is false), it forwards the request to the next handler and stores the response in the cache for future requests.
func SetHeader ¶
func SetHeader(cacheData CachedResponseData, w http.ResponseWriter)
SetHeader function help to serve response from cache to ensure the client receives correct metadata about the response.
func SkipWebSocket ¶
SkipWebSocket skip all the websocket requests coming from the client/ frontend to ensure real time data updation in the frontend.
func StoreK8sResponseInCache ¶
func StoreK8sResponseInCache(k8scache cache.Cache[string], url *url.URL, rcw *ResponseCapture, r *http.Request, key string, ) error
StoreK8sResponseInCache ensures if the key was not found inside the cache then this will make actual call to k8's and this will capture the response body and convert the captured response to string. After converting it will store the response with the key and TTL of 10*min.
func WriteResponseToClient ¶
func WriteResponseToClient(response []byte, w http.ResponseWriter) error
WriteResponseToClient returns UnAuthorized error response when the user Unauthorized This helps to prevent requests to make actual call to clusterAPI.
Types ¶
type AuthErrResponse ¶
type AuthErrResponse struct { Kind string `json:"kind"` // The Kubernetes resource kind. APIVersion string `json:"apiVersion"` // APIVersion is version for the resource. MetaData Metadata `json:"metadata"` // Metadata for the resource. Message string `json:"message"` // A human-readable error message. Reason string `json:"reason"` // Reason for the error. Details Details `json:"details"` // Details about the resource kind. Code int `json:"code"` // The HTTP status code, typically 403. }
AuthErrResponse is the Unauthorized Error message that can be used for sending 403 or Unauthorized error when the user is not allowed to access resources.
type CacheKey ¶
type CacheKey struct { Kind string // Kind is the string object which is the user is requesting Namespace string // Namespace is string object which tells what Namespace is the user trying to access Context string // Context is the unique Id which helps to differentiate multi-context }
Key struct used to store different values to make Key unique for different requests.
type CachedClientSet ¶
type CachedClientSet struct {
// contains filtered or unexported fields
}
type CachedResponseData ¶
type CachedResponseData struct { StatusCode int `json:"statusCode"` Headers http.Header `json:"headers"` Body string `json:"body"` }
CachedResponseData stores information such as StatusCode, Headers, and Body. It helps cache responses efficiently and serve them from the cache.
type Details ¶
type Details struct {
Kind string `json:"kind"` // The resource Kind ie, Pods, Nodes etc.
}
Details provides information about a specific resource kind.
type Metadata ¶
type Metadata struct {
ResourceVersion string `json:"resourceVersion"`
}
Metadata holds core data about a resource, such as its version.
type ResponseCapture ¶
type ResponseCapture struct { http.ResponseWriter StatusCode int Body *bytes.Buffer }
ResponseCapture is a struct that will capture statusCode, Headers and Body while the response is coming from the K8s clusters.
func NewResponseCapture ¶
func NewResponseCapture(w http.ResponseWriter) *ResponseCapture
NewResponseCapture initializes ResponseCapture with a http.ResponseWriter and empty bytes.Buffer for the body.
func (*ResponseCapture) Write ¶
func (r *ResponseCapture) Write(b []byte) (int, error)
Write stores the response body and writes it to the underlying ResponseWriter.
func (*ResponseCapture) WriteHeader ¶
func (r *ResponseCapture) WriteHeader(code int)
WriteHeader sets the status code and delegates to the underlying ResponseWriter.