rewriter

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2026 License: Apache-2.0 Imports: 15 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PrometheusRuleKind     = "PrometheusRule"
	PrometheusRuleListKind = "PrometheusRuleList"
	ServiceMonitorKind     = "ServiceMonitor"
	ServiceMonitorListKind = "ServiceMonitorList"
)
View Source
const (
	ValidatingWebhookConfigurationKind     = "ValidatingWebhookConfiguration"
	ValidatingWebhookConfigurationListKind = "ValidatingWebhookConfigurationList"
	MutatingWebhookConfigurationKind       = "MutatingWebhookConfiguration"
	MutatingWebhookConfigurationListKind   = "MutatingWebhookConfigurationList"
)
View Source
const (
	ValidatingAdmissionPolicyKind            = "ValidatingAdmissionPolicy"
	ValidatingAdmissionPolicyListKind        = "ValidatingAdmissionPolicyList"
	ValidatingAdmissionPolicyBindingKind     = "ValidatingAdmissionPolicyBinding"
	ValidatingAdmissionPolicyBindingListKind = "ValidatingAdmissionPolicyBindingList"
)
View Source
const (
	CorePrefix = "api"
	APIsPrefix = "apis"

	NamespacesPart = "namespaces"

	CRDGroup        = "apiextensions.k8s.io"
	CRDResourceType = "customresourcedefinitions"

	WatchClause = "watch=true"
)
View Source
const (
	DeploymentKind      = "Deployment"
	DeploymentListKind  = "DeploymentList"
	DaemonSetKind       = "DaemonSet"
	DaemonSetListKind   = "DaemonSetList"
	StatefulSetKind     = "StatefulSet"
	StatefulSetListKind = "StatefulSetList"
)
View Source
const (
	PodKind                       = "Pod"
	PodListKind                   = "PodList"
	ServiceKind                   = "Service"
	ServiceListKind               = "ServiceList"
	JobKind                       = "Job"
	JobListKind                   = "JobList"
	PersistentVolumeClaimKind     = "PersistentVolumeClaim"
	PersistentVolumeClaimListKind = "PersistentVolumeClaimList"
)
View Source
const (
	CRDKind     = "CustomResourceDefinition"
	CRDListKind = "CustomResourceDefinitionList"
)
View Source
const (
	EventKind     = "Event"
	EventListKind = "EventList"
)
View Source
const (
	PodDisruptionBudgetKind     = "PodDisruptionBudget"
	PodDisruptionBudgetListKind = "PodDisruptionBudgetList"
)
View Source
const (
	ClusterRoleKind            = "ClusterRole"
	ClusterRoleListKind        = "ClusterRoleList"
	RoleKind                   = "Role"
	RoleListKind               = "RoleList"
	RoleBindingKind            = "RoleBinding"
	RoleBindingListKind        = "RoleBindingList"
	ControllerRevisionKind     = "ControllerRevision"
	ControllerRevisionListKind = "ControllerRevisionList"
	ClusterRoleBindingKind     = "ClusterRoleBinding"
	ClusterRoleBindingListKind = "ClusterRoleBindingList"
	APIServiceKind             = "APIService"
	APIServiceListKind         = "APIServiceList"
)
View Source
const PreservedPrefix = "preserved-original-"
View Source
const Root = "@ROOT"

Variables

View Source
var SkipItem = errors.New("remove item from the result")

SkipItem may be used by the transformFn to indicate that the item should be skipped from the result.

Functions

func GetBytes

func GetBytes(obj []byte, path string) gjson.Result

func RenameAPIVersionAndKind

func RenameAPIVersionAndKind(rules *RewriteRules, obj []byte) ([]byte, error)

func RenameAdmissionReviewResponse

func RenameAdmissionReviewResponse(rules *RewriteRules, obj []byte) ([]byte, error)

RenameAdmissionReviewResponse renames metadata in AdmissionReview response patch. AdmissionReview response example:

"response": {
   "uid": "<value from request.uid>",
   "allowed": true,
   "patchType": "JSONPatch",
   "patch": "W3sib3AiOiAiYWRkIiwgInBhdGgiOiAiL3NwZWMvcmVwbGljYXMiLCAidmFsdWUiOiAzfV0="
 }

TODO rename annotations in AuditAnnotations field. (Ignore for now, as not used by the kubevirt).

func RenameCRD

func RenameCRD(rules *RewriteRules, obj []byte) ([]byte, error)

RenameCRD renames fields in CRD.

Example: .metadata.name virtualmachines.kubevirt.io -> prefixedvirtualmachines.x.virtualization.deckhouse.io .spec.group kubevirt.io -> x.virtualization.deckhouse.io .spec.names

categories      all -> kubevirt
kind            VirtualMachine -> PrefixedVirtualMachines
listKind        VirtualMachineList -> PrefixedVirtualMachineList
plural          virtualmachines -> prefixedvirtualmachines
singular        virtualmachine -> prefixedvirtualmachine
shortNames      [vm vms] -> [xvm xvms]

func RenameCRDPatch

func RenameCRDPatch(rules *RewriteRules, resourceRule *ResourceRule, obj []byte) ([]byte, error)

func RenameManagedFields

func RenameManagedFields(rules *RewriteRules, obj []byte) ([]byte, error)

RenameManagedFields renames apiVersion in managedFields items.

Example request from the client:

"metadata": {
  "managedFields":[
    { "apiVersion":"original.group.io/v1", "fieldsType":"FieldsV1", "fieldsV1":{ ... }}, "manager": "Go-http-client", ...},
    { "apiVersion":"original.group.io/v1", "fieldsType":"FieldsV1", "fieldsV1":{ ... }}, "manager": "kubectl-edit", ...}
  ],

func RenameMetadataPatch

func RenameMetadataPatch(rules *RewriteRules, patch []byte) ([]byte, error)

RenameMetadataPatch transforms known metadata fields in patches. Example: - merge patch on metadata: {"metadata": { "labels": {"kubevirt.io/schedulable": "false", "cpumanager": "false"}, "annotations": {"kubevirt.io/heartbeat": "2024-06-07T23:27:53Z"}}} - JSON patch on metadata: [{"op":"test", "path":"/metadata/labels", "value":{"label":"value"}},

{"op":"replace", "path":"/metadata/labels", "value":{"label":"newValue"}}]

func RenameResource

func RenameResource(rules *RewriteRules, obj []byte) ([]byte, error)

func RenameResourcePatch

func RenameResourcePatch(rules *RewriteRules, patch []byte) ([]byte, error)

func RenameResourceRule

func RenameResourceRule(rules *RewriteRules, obj []byte) ([]byte, error)

RenameResourceRule renames apiGroups and resources in a single rule. Rule examples:

  • apiGroups:
  • original.group.io resources:
  • '*' verbs:
  • '*'
  • apiGroups:
  • original.group.io resources:
  • someresources
  • someresources/finalizers
  • someresources/status
  • someresources/scale verbs:
  • watch
  • list
  • create

func RenameResourcesList

func RenameResourcesList(rules *RewriteRules, obj []byte) ([]byte, error)

func RenameServicePatch

func RenameServicePatch(rules *RewriteRules, obj []byte) ([]byte, error)

func RenameSpecTemplatePatch

func RenameSpecTemplatePatch(rules *RewriteRules, obj []byte) ([]byte, error)

func RenameWebhookConfigurationPatch

func RenameWebhookConfigurationPatch(rules *RewriteRules, obj []byte) ([]byte, error)

func RestoreAPIVersionAndKind

func RestoreAPIVersionAndKind(rules *RewriteRules, obj []byte) ([]byte, error)

func RestoreAdmissionReviewObject

func RestoreAdmissionReviewObject(rules *RewriteRules, obj []byte) ([]byte, error)

RestoreAdmissionReviewObject fully restores object of known resource. TODO deduplicate with code in RewriteJSONPayload.

func RestoreAdmissionReviewRequest

func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte) ([]byte, error)

RestoreAdmissionReviewRequest restores apiVersion, kind and other fields in an AdmissionReview request. Only restoring is required, as AdmissionReview request only comes from API Server. Fields for AdmissionReview request:

kind, requestKind: - Fully-qualified group/version/kind of the incoming object
  kind - restore
  version
  group - restore
resource, requestResource - Fully-qualified group/version/kind of the resource being modified
  group - restore
  version
  resource - restore
object, oldObject - new and old objects being admitted, should be restored.

non-rewritable:
  uid - review uid, no rewrite
  subResource, requestSubResource - scale or status, no rewrite
  name
  namespace
  operation
  userInfo
  options
  dryRun

func RestoreAggregatedDiscoveryResource

func RestoreAggregatedDiscoveryResource(rules *RewriteRules, obj []byte) (string, []byte, error)

RestoreAggregatedDiscoveryResource restores fields in a renamed APIResourceDiscovery object.

Example of the APIResourceDiscovery object:

{
  "resource": "internalvirtualizationkubevirts",
  "responseKind": {
    "group": "internal.virtualization.deckhouse.io",
    "version": "v1",
    "kind": "InternalVirtualizationKubeVirt"
  },
  "scope": "Namespaced",
  "singularResource": "internalvirtualizationkubevirt",
  "verbs": [ "delete", "deletecollection", "get", ... ], // Optional
  "categories": [ "intvirt" ], // Optional
  "subresources": [ // Optional
    {
      "subresource": "status",
      "responseKind": {
        "group": "internal.virtualization.deckhouse.io",
        "version": "v1",
        "kind": "InternalVirtualizationKubeVirt"
      },
      "verbs": [ "get", "patch", "update" ]
    }
  ]
}

func RestoreAggregatedGroupDiscovery

func RestoreAggregatedGroupDiscovery(rules *RewriteRules, obj []byte) ([][]byte, error)

RestoreAggregatedGroupDiscovery returns an array of APIGroupDiscovery objects with restored resources.

obj is an APIGroupDiscovery object with renamed resources:

 {
	"metadata": {
	  "name": "internal.virtualization.deckhouse.io", <-- renamed group
	  "creationTimestamp": null
	},
    "versions": [
      {  // APIVersionDiscovery
	    "version": "v1",
	    "resources": [ APIResourceDiscovery{}, ..., APIResourceDiscovery{}] ,
	    "freshness": "Current"
      }, ... , more APIVersionDiscovery objects.
    ]
 }

Renamed resources in one version may belong to different original groups, so this method indexes and restores all resources in APIResourceDiscovery and then produces APIGroupDiscovery for each restored group.

func RestoreCRD

func RestoreCRD(rules *RewriteRules, obj []byte) ([]byte, error)

RestoreCRD restores fields in CRD to original.

Example: .metadata.name prefixedvirtualmachines.x.virtualization.deckhouse.io -> virtualmachines.kubevirt.io .spec.group x.virtualization.deckhouse.io -> kubevirt.io .spec.names

categories      kubevirt -> all
kind            PrefixedVirtualMachines -> VirtualMachine
listKind        PrefixedVirtualMachineList -> VirtualMachineList
plural          prefixedvirtualmachines -> virtualmachines
singular        prefixedvirtualmachine -> virtualmachine
shortNames      [xvm xvms] -> [vm vms]

func RestoreManagedFields

func RestoreManagedFields(rules *RewriteRules, obj []byte) ([]byte, error)

RestoreManagedFields restores apiVersion in managedFields items.

Example response from the server:

"metadata": {
  "managedFields":[
    { "apiVersion":"renamed.resource.group.io/v1", "fieldsType":"FieldsV1", "fieldsV1":{ ... }}, "manager": "Go-http-client", ...},
    { "apiVersion":"renamed.resource.group.io/v1", "fieldsType":"FieldsV1", "fieldsV1":{ ... }}, "manager": "kubectl-edit", ...}
  ],

func RestoreResource

func RestoreResource(rules *RewriteRules, obj []byte) ([]byte, error)

func RestoreResourceRule

func RestoreResourceRule(rules *RewriteRules, obj []byte) ([]byte, error)

RestoreResourceRule restores apiGroups and resources in a single rule.

func RestoreResourcesList

func RestoreResourcesList(rules *RewriteRules, obj []byte) ([]byte, error)

func RewriteAPIGroup

func RewriteAPIGroup(rules *RewriteRules, obj []byte) ([]byte, error)

RewriteAPIGroup restores apiGroup, kinds and versions in responses from renamed APIGroup query: /apis/renamed.resource.group.io

This call returns all versions for renamed.resource.group.io. Rewriter should reduce versions for only available in original group To reduce further requests with specific versions.

Example response with renamed group: { "kind":"APIGroup",

   "apiVersion":"v1",
   "name":"renamed.resource.group.io",
   "versions":[
	  {"groupVersion":"renamed.resource.group.io/v1","version":"v1"},
	  {"groupVersion":"renamed.resource.group.io/v1alpha1","version":"v1alpha1"}
   ],
  "preferredVersion": {
    "groupVersion":"renamed.resource.group.io/v1",
	"version":"v1"}
  }

Restored response should be: { "kind":"APIGroup",

   "apiVersion":"v1",
   "name":"original.group.io",
   "versions":[
	    {"groupVersion":"original.group.io/v1","version":"v1"},
     {"groupVersion":"original.group.io/v1alpha1","version":"v1alpha1"}
   ],
	  "preferredVersion": {
     "groupVersion":"original.group.io/v1",
		"version":"v1"}
	  }

func RewriteAPIGroupAndKind

func RewriteAPIGroupAndKind(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteAPIGroupDiscoveryList

func RewriteAPIGroupDiscoveryList(rules *RewriteRules, obj []byte) ([]byte, error)

func RewriteAPIGroupList

func RewriteAPIGroupList(rules *RewriteRules, obj []byte) ([]byte, error)

RewriteAPIGroupList restores groups and kinds in "groups" array in /apis/ response.

Response example:

{
  "kind": "APIGroupList",
  "apiVersion": "v1",
  "groups": [
    {
      "name": "prefixed.resources.group.io",
      "versions": [
        {"groupVersion":"prefixed.resources.group.io/v1","version":"v1"},
        {"groupVersion":"prefixed.resources.group.io/v1beta1","version":"v1beta1"},
        {"groupVersion":"prefixed.resources.group.io/v1alpha3","version":"v1alpha3"}
      ],
      "preferredVersion": {
        "groupVersion":"prefixed.resources.group.io/v1",
        "version":"v1"
      }
    }
  ]
}

func RewriteAPIResourceList

func RewriteAPIResourceList(rules *RewriteRules, obj []byte) ([]byte, error)

RewriteAPIResourceList rewrites server responses from /apis/GROUP/VERSION discovery requests.

Example:

Path rewrite: https://10.222.0.1:443/apis/original.group.io/v1 -> https://10.222.0.1:443/apis/prefixed.resources.group.io/v1 1. Restore "groupVersion" field. 2. Restore items in "resources": 2.1. If name is a resource type: restore "name", "singularName", "kind", "shortNames", and "categories". 2.2. If name contains "/status" suffix: restore "name" and "kind" fields 2.3. If name contains "/scale" suffix: restore "name" field as a resource type

Rewrite of response from /apis/prefixed.resources.group.io/v1:

{
  "kind":"APIResourceList",
  "apiVersion":"v1",
  "groupVersion":"prefixed.resources.group.io/v1",  --> Restore apiGroup, keep version: original.group.io/v1
  "resources":[
  {
    "name":"prefixedsomeresources", --> Restore resource type: someresources
    "singularName":"prefixedsomeresource",  --> Restore singular: someresource
    "namespaced":true,
    "kind":"PrefixedSomeResource",  --> restore kind: SomeResource
    "verbs":["delete","deletecollection","get","list","patch","create","update","watch"],
    "shortNames":["psr","psrs"], --> Restore shortNames: ["sr", "srs"]
    "categories":["prefixed"],  --> Restore categories: ["all"]
    "storageVersionHash":"QUMxLW9gfYs="
  },{
    "name":"prefixedsomeresources/status",  --> Restore resource type, keep suffix: someresources/status
    "singularName":"",
    "namespaced":true,
    "kind":"PrefixedSomeResource",  --> Restore kind: SomeResource
    "verbs":["get","patch","update"]
  },{
    "name":"prefixedsomeresources/scale",   --> Restore resource type, keep suffix: someresources/status
    "singularName":"",
	"namespaced":true,
	"group":"autoscaling",
	"version":"v1",
	"kind":"Scale",
	  "verbs":["get","patch","update"]
	}]
  }
}

func RewriteAPIVersionAndKind

func RewriteAPIVersionAndKind(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteAdmissionReview

func RewriteAdmissionReview(rules *RewriteRules, obj []byte) ([]byte, error)

RewriteAdmissionReview rewrites AdmissionReview request and response. NOTE: only one rewrite direction is supported for now: - Restore object in AdmissionReview request. - Do nothing for AdmissionReview response.

func RewriteAffinity

func RewriteAffinity(rules *RewriteRules, obj []byte, path string, action Action) ([]byte, error)

RewriteAffinity renames or restores labels in labelSelector of affinity structure. See https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity

func RewriteAnnotationsMap

func RewriteAnnotationsMap(rules *RewriteRules, obj []byte, path string, action Action) ([]byte, error)

func RewriteArray

func RewriteArray(obj []byte, arrayPath string, transformFn func(item []byte) ([]byte, error)) ([]byte, error)

RewriteArray gets array by path and transforms each item using transformFn. Use Root path to transform object itself. transformFn contract: return obj, nil -> obj is considered a replacement for the element. return nil, nil -> no transformation, element is added as-is. return any, SkipItem -> no transformation and no adding to the result. return any, err -> stop transformation, return error.

func RewriteCRDOrList

func RewriteCRDOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteClusterRoleOrList

func RewriteClusterRoleOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteCustomResourceOrList

func RewriteCustomResourceOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteDaemonSetOrList

func RewriteDaemonSetOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteDeploymentOrList

func RewriteDeploymentOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteEventOrList

func RewriteEventOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

RewriteEventOrList rewrites a single Event resource or a list of Events in EventList. The only field need to rewrite is involvedObject:

 {
  "metadata": { "name": "...", "namespace": "...", "managedFields": [...] },
  "involvedObject": {
    "kind": "SomeResource",
    "namespace": "name",
    "name": "ns",
    "uid": "a260fe4f-103a-41c6-996c-d29edb01fbbd",
    "apiVersion": "group.io/v1"
  },
  "type": "...",
  "reason": "...",
  "message": "...",
  "source": {
    "component": "...",
    "host": "..."
  },
  "reportingComponent": "...",
  "reportingInstance": "..."
},

func RewriteFinalizers

func RewriteFinalizers(rules *RewriteRules, obj []byte, path string, action Action) ([]byte, error)

func RewriteGVK

func RewriteGVK(rules *RewriteRules, obj []byte, action Action, gvFieldName string) ([]byte, error)

RewriteGVK rewrites a "kind" field and a field with the group if there is the rule for these particular kind and group.

func RewriteJobOrList

func RewriteJobOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

RewriteJobOrList transforms known fields in the Job manifest.

func RewriteLabelsMap

func RewriteLabelsMap(rules *RewriteRules, obj []byte, path string, action Action) ([]byte, error)

func RewriteMapStringString

func RewriteMapStringString(obj []byte, mapPath string, transformFn func(k, v string) (string, string)) ([]byte, error)

RewriteMapStringString transforms map[string]string value addressed by path.

func RewriteMetadata

func RewriteMetadata(rules *RewriteRules, metadataObj []byte, action Action) ([]byte, error)

func RewriteMutatingOrList

func RewriteMutatingOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteOwnerReferences

func RewriteOwnerReferences(rules *RewriteRules, obj []byte, path string, action Action) ([]byte, error)

func RewritePDBOrList

func RewritePDBOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewritePVCOrList

func RewritePVCOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

RewritePVCOrList transforms known fields in the PersistentVolumeClaim manifest.

func RewritePodOrList

func RewritePodOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteResourceOrList

func RewriteResourceOrList(payload []byte, listKind string, transformFn func(singleObj []byte) ([]byte, error)) ([]byte, error)

RewriteResourceOrList is a helper to transform a single resource or a list of resources.

func RewriteResourceOrList2

func RewriteResourceOrList2(payload []byte, transformFn func(singleObj []byte) ([]byte, error)) ([]byte, error)

RewriteResourceOrList2 is a helper to transform a single resource or a list of resources.

func RewriteRoleOrList

func RewriteRoleOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteServiceMonitorOrList

func RewriteServiceMonitorOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteServiceOrList

func RewriteServiceOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteSpecTemplateLabelsAnno

func RewriteSpecTemplateLabelsAnno(rules *RewriteRules, obj []byte, path string, action Action) ([]byte, error)

RewriteSpecTemplateLabelsAnno transforms labels and annotations in spec fields: - selector as LabelSelector - template.metadata.labels as labels map - template.metadata.annotations as annotations map - template.affinity as Affinity - template.nodeSelector as labels map.

func RewriteStatefulSetOrList

func RewriteStatefulSetOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteValidatingAdmissionPolicyBindingOrList

func RewriteValidatingAdmissionPolicyBindingOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteValidatingAdmissionPolicyOrList

func RewriteValidatingAdmissionPolicyOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func RewriteValidatingOrList

func RewriteValidatingOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error)

func SetBytes

func SetBytes(obj []byte, path string, value interface{}) ([]byte, error)

func SetRawBytes

func SetRawBytes(obj []byte, path string, value []byte) ([]byte, error)

func Shift

func Shift(items *[]string) (string, bool)

Shift deletes the first item from the array and returns it.

func TransformArrayOfStrings

func TransformArrayOfStrings(obj []byte, arrayPath string, transformFn func(item string) string) ([]byte, error)

TransformArrayOfStrings transforms array value addressed by path.

func TransformObject

func TransformObject(obj []byte, path string, transformFn func(item []byte) ([]byte, error)) ([]byte, error)

TransformObject transforms object value addressed by path.

func TransformPatch

func TransformPatch(
	obj []byte,
	transformMerge func(mergePatch []byte) ([]byte, error),
	transformJSON func(jsonPatch []byte) ([]byte, error)) ([]byte, error)

TransformPatch treats obj as a JSON patch or Merge patch and calls a corresponding transformFn.

func TransformString

func TransformString(obj []byte, path string, transformFn func(field string) string) ([]byte, error)

TransformString transforms string value addressed by path.

Types

type APIEndpoint

type APIEndpoint struct {
	// IsUknown indicates that path is unknown for rewriter and should be passed as is.
	IsUnknown bool
	RawPath   string

	IsRoot bool

	Prefix string
	IsCore bool

	Group        string
	Version      string
	Namespace    string
	ResourceType string
	Name         string
	Subresource  string
	Remainder    []string

	IsCRD           bool
	CRDResourceType string
	CRDGroup        string

	IsWatch  bool
	RawQuery string
}

func ParseAPIEndpoint

func ParseAPIEndpoint(apiURL *url.URL) *APIEndpoint

ParseAPIEndpoint breaks url path by parts.

func (*APIEndpoint) Clone

func (a *APIEndpoint) Clone() *APIEndpoint

func (*APIEndpoint) Path

func (a *APIEndpoint) Path() string

type APIGroupRule

type APIGroupRule struct {
	GroupRule     GroupRule               `json:"groupRule"`
	ResourceRules map[string]ResourceRule `json:"resourceRules"`
}

type Action

type Action string
const (
	// Restore is an action to restore resources to original.
	Restore Action = "restore"
	// Rename is an action to rename original resources.
	Rename Action = "rename"
)

type ExcludeRule

type ExcludeRule struct {
	Kinds       []string          `json:"kinds"`
	MatchNames  []string          `json:"matchNames"`
	MatchLabels map[string]string `json:"matchLabels"`
}

func (ExcludeRule) Match

func (r ExcludeRule) Match(obj []byte, kind string) bool

Match returns true if object matches all conditions in the exclude rule.

type GroupRule

type GroupRule struct {
	Group            string   `json:"group"`
	Versions         []string `json:"versions"`
	PreferredVersion string   `json:"preferredVersion"`
	Renamed          string   `json:"renamed"`
}

type MetadataReplace

type MetadataReplace struct {
	Prefixes []MetadataReplaceRule
	Names    []MetadataReplaceRule
}

type MetadataReplaceRule

type MetadataReplaceRule struct {
	Original      string `json:"original"`
	Renamed       string `json:"renamed"`
	OriginalValue string `json:"originalValue"`
	RenamedValue  string `json:"renamedValue"`
}

type PrefixedNameRewriter

type PrefixedNameRewriter struct {
	// contains filtered or unexported fields
}

func NewPrefixedNameRewriter

func NewPrefixedNameRewriter(replaceRules MetadataReplace) *PrefixedNameRewriter

func (*PrefixedNameRewriter) Rename

func (p *PrefixedNameRewriter) Rename(name, value string) (string, string)

func (*PrefixedNameRewriter) RenameMap

func (p *PrefixedNameRewriter) RenameMap(names map[string]string) map[string]string

func (*PrefixedNameRewriter) RenameSlice

func (p *PrefixedNameRewriter) RenameSlice(names []string) []string

func (*PrefixedNameRewriter) Restore

func (p *PrefixedNameRewriter) Restore(name, value string) (string, string)

func (*PrefixedNameRewriter) RestoreMap

func (p *PrefixedNameRewriter) RestoreMap(names map[string]string) map[string]string

func (*PrefixedNameRewriter) RestoreSlice

func (p *PrefixedNameRewriter) RestoreSlice(names []string) []string

func (*PrefixedNameRewriter) Rewrite

func (p *PrefixedNameRewriter) Rewrite(name string, action Action) string

func (*PrefixedNameRewriter) RewriteMap

func (p *PrefixedNameRewriter) RewriteMap(names map[string]string, action Action) map[string]string

func (*PrefixedNameRewriter) RewriteNameValue

func (p *PrefixedNameRewriter) RewriteNameValue(name, value string, action Action) (string, string)

func (*PrefixedNameRewriter) RewriteNameValues

func (p *PrefixedNameRewriter) RewriteNameValues(name string, values []string, action Action) (string, []string)

func (*PrefixedNameRewriter) RewriteSlice

func (p *PrefixedNameRewriter) RewriteSlice(names []string, action Action) []string

type ResourceRule

type ResourceRule struct {
	Kind             string   `json:"kind"`
	ListKind         string   `json:"listKind"`
	Plural           string   `json:"plural"`
	Singular         string   `json:"singular"`
	ShortNames       []string `json:"shortNames"`
	Categories       []string `json:"categories"`
	Versions         []string `json:"versions"`
	PreferredVersion string   `json:"preferredVersion"`
}

type RewriteRules

type RewriteRules struct {
	KindPrefix         string                  `json:"kindPrefix"`
	ResourceTypePrefix string                  `json:"resourceTypePrefix"`
	ShortNamePrefix    string                  `json:"shortNamePrefix"`
	Categories         []string                `json:"categories"`
	Rules              map[string]APIGroupRule `json:"rules"`
	Webhooks           map[string]WebhookRule  `json:"webhooks"`
	Labels             MetadataReplace         `json:"labels"`
	Annotations        MetadataReplace         `json:"annotations"`
	Finalizers         MetadataReplace         `json:"finalizers"`
	Excludes           []ExcludeRule           `json:"excludes"`
	// contains filtered or unexported fields
}

func LoadRules

func LoadRules(filename string) (*RewriteRules, error)

func (*RewriteRules) AnnotationsRewriter

func (rr *RewriteRules) AnnotationsRewriter() *PrefixedNameRewriter

func (*RewriteRules) FinalizersRewriter

func (rr *RewriteRules) FinalizersRewriter() *PrefixedNameRewriter

func (*RewriteRules) GetAPIGroupList

func (rr *RewriteRules) GetAPIGroupList() []interface{}

GetAPIGroupList returns an array of groups in format applicable to use in APIGroupList:

{
  name
  versions: [ { groupVersion, version } ... ]
  preferredVersion: { groupVersion, version }
}

func (*RewriteRules) GroupResourceRules

func (rr *RewriteRules) GroupResourceRules(resourceType string) (*GroupRule, *ResourceRule)

func (*RewriteRules) GroupResourceRulesByKind

func (rr *RewriteRules) GroupResourceRulesByKind(kind string) (*GroupRule, *ResourceRule)

func (*RewriteRules) GroupRule

func (rr *RewriteRules) GroupRule(group string) *GroupRule

func (*RewriteRules) HasGroup

func (rr *RewriteRules) HasGroup(group string) bool

func (*RewriteRules) Init

func (rr *RewriteRules) Init()

Init should be called before using rules in the RuleBasedRewriter.

func (*RewriteRules) IsRenamedGroup

func (rr *RewriteRules) IsRenamedGroup(apiGroup string) bool

func (*RewriteRules) KindRules

func (rr *RewriteRules) KindRules(apiGroup, kind string) (*GroupRule, *ResourceRule)

KindRules returns rule for group and resource by apiGroup and kind. apiGroup may be a group or a group with version.

func (*RewriteRules) LabelsRewriter

func (rr *RewriteRules) LabelsRewriter() *PrefixedNameRewriter

func (*RewriteRules) RenameApiVersion

func (rr *RewriteRules) RenameApiVersion(apiVersion string) string

RenameApiVersion returns apiVersion with renamed apiGroup part. It keeps with version suffix as-is if present.

func (*RewriteRules) RenameCategories

func (rr *RewriteRules) RenameCategories(categories []string) []string

func (*RewriteRules) RenameKind

func (rr *RewriteRules) RenameKind(kind string) string

func (*RewriteRules) RenameResource

func (rr *RewriteRules) RenameResource(resource string) string

func (*RewriteRules) RenameShortName

func (rr *RewriteRules) RenameShortName(shortName string) string

func (*RewriteRules) RenameShortNames

func (rr *RewriteRules) RenameShortNames(shortNames []string) []string

func (*RewriteRules) ResourceByKind

func (rr *RewriteRules) ResourceByKind(kind string) (string, string, bool)

func (*RewriteRules) ResourceRules

func (rr *RewriteRules) ResourceRules(apiGroup, resource string) (*GroupRule, *ResourceRule)

func (*RewriteRules) RestoreApiVersion

func (rr *RewriteRules) RestoreApiVersion(apiVersion string) string

RestoreApiVersion returns apiVersion with restored apiGroup part. It keeps with version suffix as-is if present.

func (*RewriteRules) RestoreCategories

func (rr *RewriteRules) RestoreCategories(resourceRule *ResourceRule) []string

func (*RewriteRules) RestoreKind

func (rr *RewriteRules) RestoreKind(kind string) string

func (*RewriteRules) RestoreResource

func (rr *RewriteRules) RestoreResource(resource string) string

RestoreResource restores renamed resource to its original state, keeping suffix. E.g. "prefixedsomeresources/scale" will be restored to "someresources/scale".

func (*RewriteRules) RestoreShortName

func (rr *RewriteRules) RestoreShortName(shortName string) string

func (*RewriteRules) RestoreShortNames

func (rr *RewriteRules) RestoreShortNames(shortNames []string) []string

func (*RewriteRules) ShouldExclude

func (rr *RewriteRules) ShouldExclude(obj []byte, kind string) bool

ShouldExclude returns true if object should be excluded from response back to the client. Set kind when obj has no kind, e.g. a list item.

func (*RewriteRules) WebhookRule

func (rr *RewriteRules) WebhookRule(path string) *WebhookRule

type RuleBasedRewriter

type RuleBasedRewriter struct {
	Rules *RewriteRules
}

func (*RuleBasedRewriter) FilterExcludes

func (rw *RuleBasedRewriter) FilterExcludes(obj []byte, action Action) ([]byte, error)

FilterExcludes removes excluded resources from the list or return SkipItem if resource itself is excluded.

func (*RuleBasedRewriter) RestoreBookmark

func (rw *RuleBasedRewriter) RestoreBookmark(targetReq *TargetRequest, obj []byte) ([]byte, error)

RestoreBookmark restores apiVersion and kind in an object in WatchEvent with type BOOKMARK. Bookmark is not a full object, so RewriteJSONPayload may add unexpected fields. Bookmark example: {"kind":"ConfigMap","apiVersion":"v1","metadata":{"resourceVersion":"438083871","creationTimestamp":null}}

func (*RuleBasedRewriter) RewriteAPIEndpoint

func (rw *RuleBasedRewriter) RewriteAPIEndpoint(ep *APIEndpoint) *APIEndpoint

RewriteAPIEndpoint renames group and resource in /apis/* endpoints. It assumes that ep contains original group and resourceType. Restoring of path is not implemented.

func (*RuleBasedRewriter) RewriteJSONPayload

func (rw *RuleBasedRewriter) RewriteJSONPayload(_ *TargetRequest, obj []byte, action Action) ([]byte, error)

RewriteJSONPayload does rewrite based on kind. TODO(future refactor): Remove targetReq in all callers.

func (*RuleBasedRewriter) RewritePatch

func (rw *RuleBasedRewriter) RewritePatch(targetReq *TargetRequest, patchBytes []byte) ([]byte, error)

RewritePatch rewrites patches for some known objects. Only rename action is required for patches.

type TargetRequest

type TargetRequest struct {
	// contains filtered or unexported fields
}

func NewTargetRequest

func NewTargetRequest(rwr *RuleBasedRewriter, req *http.Request) *TargetRequest

func (*TargetRequest) IsCRD

func (tr *TargetRequest) IsCRD() bool

func (*TargetRequest) IsCore

func (tr *TargetRequest) IsCore() bool

func (*TargetRequest) IsWatch

func (tr *TargetRequest) IsWatch() bool

func (*TargetRequest) IsWebhook

func (tr *TargetRequest) IsWebhook() bool

func (*TargetRequest) OrigGroup

func (tr *TargetRequest) OrigGroup() string

func (*TargetRequest) OrigResourceType

func (tr *TargetRequest) OrigResourceType() string

func (*TargetRequest) Path

func (tr *TargetRequest) Path() string

Path return possibly rewritten path for target endpoint.

func (*TargetRequest) RawQuery

func (tr *TargetRequest) RawQuery() string

func (*TargetRequest) RequestURI

func (tr *TargetRequest) RequestURI() string

func (*TargetRequest) ResourceForLog

func (tr *TargetRequest) ResourceForLog() string

func (*TargetRequest) ShouldRewriteRequest

func (tr *TargetRequest) ShouldRewriteRequest() bool

ShouldRewriteRequest returns true if incoming payload should be rewritten.

func (*TargetRequest) ShouldRewriteResponse

func (tr *TargetRequest) ShouldRewriteResponse() bool

ShouldRewriteResponse return true if response rewrite is needed. Response may be passed as is if false.

type WebhookRule

type WebhookRule struct {
	Path     string `json:"path"`
	Group    string `json:"group"`
	Resource string `json:"resource"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL