diff --git a/go.mod b/go.mod index bff0607fb..3fc74a219 100644 --- a/go.mod +++ b/go.mod @@ -43,8 +43,8 @@ require ( gopkg.in/natefinch/lumberjack.v2 v2.0.0 gopkg.in/square/go-jose.v2 v2.6.0 k8s.io/api v0.0.0-20230308234233-a4afee70a903 - k8s.io/apimachinery v0.0.0-20230303235435-f357b1fa74b7 - k8s.io/client-go v0.0.0-20230309033544-64e2c7ff167c + k8s.io/apimachinery v0.0.0-20230310053422-8ac57a9747bc + k8s.io/client-go v0.0.0-20230310084516-756a0f3ae9a9 k8s.io/component-base v0.0.0-20230308075123-cfc68dcaff73 k8s.io/klog/v2 v2.90.1 k8s.io/kms v0.0.0-20230304001132-5439f76ca4a7 @@ -125,8 +125,8 @@ require ( replace ( k8s.io/api => k8s.io/api v0.0.0-20230308234233-a4afee70a903 - k8s.io/apimachinery => k8s.io/apimachinery v0.0.0-20230303235435-f357b1fa74b7 - k8s.io/client-go => k8s.io/client-go v0.0.0-20230309033544-64e2c7ff167c + k8s.io/apimachinery => k8s.io/apimachinery v0.0.0-20230310053422-8ac57a9747bc + k8s.io/client-go => k8s.io/client-go v0.0.0-20230310084516-756a0f3ae9a9 k8s.io/component-base => k8s.io/component-base v0.0.0-20230308075123-cfc68dcaff73 k8s.io/kms => k8s.io/kms v0.0.0-20230304001132-5439f76ca4a7 ) diff --git a/go.sum b/go.sum index 39a2821b6..529742a90 100644 --- a/go.sum +++ b/go.sum @@ -876,10 +876,10 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= k8s.io/api v0.0.0-20230308234233-a4afee70a903 h1:TmxUf1tDcGUHE8qZKLRWmn2nr2FypkwvqC2qviOUmQc= k8s.io/api v0.0.0-20230308234233-a4afee70a903/go.mod h1:esKbT+6XB9TZUHyxlJVQ3zUM0abhQZ81Ic68eirO+xM= -k8s.io/apimachinery v0.0.0-20230303235435-f357b1fa74b7 h1:YN43Lvs3Pj9iQmuWGojeBiFdz1mkrxe0EZn7Ba3TMpQ= -k8s.io/apimachinery v0.0.0-20230303235435-f357b1fa74b7/go.mod h1:jlJwObMa4oKAEOMnAeEaqeiM+Fwd/CbAwNyQ7OaEwS0= -k8s.io/client-go v0.0.0-20230309033544-64e2c7ff167c h1:1IXuG9QQvPMR3GbYgBhOKre47MAIq+U41cWOGoAHpd8= -k8s.io/client-go v0.0.0-20230309033544-64e2c7ff167c/go.mod h1:hjEB5iFHr17qVb6wnh6w2LQvO5DfoP6rzLN8NAE8K6U= +k8s.io/apimachinery v0.0.0-20230310053422-8ac57a9747bc h1:iUeJrNH0Issnw4YeNTz6uNuWuA24Eh01HhHiO3IyCg0= +k8s.io/apimachinery v0.0.0-20230310053422-8ac57a9747bc/go.mod h1:jlJwObMa4oKAEOMnAeEaqeiM+Fwd/CbAwNyQ7OaEwS0= +k8s.io/client-go v0.0.0-20230310084516-756a0f3ae9a9 h1:Nd40oJXB53lEpVRBPPCtUaUKwkKa70OxCDKsESBeGFY= +k8s.io/client-go v0.0.0-20230310084516-756a0f3ae9a9/go.mod h1:hjEB5iFHr17qVb6wnh6w2LQvO5DfoP6rzLN8NAE8K6U= k8s.io/component-base v0.0.0-20230308075123-cfc68dcaff73 h1:MEKvhkstqrRFmA9+qQlnkA/jPbZUH/VnMKiEfBeLbf8= k8s.io/component-base v0.0.0-20230308075123-cfc68dcaff73/go.mod h1:MB0hQ6Wy3OOZ/dr+sy5FwxCJhDJ4hszX743ar8dd2zE= k8s.io/klog/v2 v2.90.1 h1:m4bYOKall2MmOiRaR1J+We67Do7vm9KiQVlT96lnHUw= diff --git a/pkg/endpoints/groupversion.go b/pkg/endpoints/groupversion.go index f33d4bac6..3c70e89ec 100644 --- a/pkg/endpoints/groupversion.go +++ b/pkg/endpoints/groupversion.go @@ -27,11 +27,11 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" utilerrors "k8s.io/apimachinery/pkg/util/errors" + "k8s.io/apimachinery/pkg/util/managedfields" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/authorization/authorizer" "k8s.io/apiserver/pkg/endpoints/discovery" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/apiserver/pkg/storageversion" ) @@ -81,7 +81,7 @@ type APIGroupVersion struct { Defaulter runtime.ObjectDefaulter Namer runtime.Namer UnsafeConvertor runtime.ObjectConvertor - TypeConverter fieldmanager.TypeConverter + TypeConverter managedfields.TypeConverter EquivalentResourceRegistry runtime.EquivalentResourceRegistry diff --git a/pkg/endpoints/handlers/fieldmanager/admission.go b/pkg/endpoints/handlers/fieldmanager/admission.go index eb20d42ce..bbc657168 100644 --- a/pkg/endpoints/handlers/fieldmanager/admission.go +++ b/pkg/endpoints/handlers/fieldmanager/admission.go @@ -21,6 +21,7 @@ import ( "fmt" "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/util/managedfields" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/warning" ) @@ -70,7 +71,7 @@ func (admit *managedFieldsValidatingAdmissionController) Admit(ctx context.Conte return err } managedFieldsAfterAdmission := objectMeta.GetManagedFields() - if err := ValidateManagedFields(managedFieldsAfterAdmission); err != nil { + if err := managedfields.ValidateManagedFields(managedFieldsAfterAdmission); err != nil { objectMeta.SetManagedFields(managedFieldsBeforeAdmission) warning.AddWarning(ctx, "", fmt.Sprintf(InvalidManagedFieldsAfterMutatingAdmissionWarningFormat, diff --git a/pkg/endpoints/handlers/fieldmanager/bench_test.go b/pkg/endpoints/handlers/fieldmanager/bench_test.go index 56a383aec..75749791f 100644 --- a/pkg/endpoints/handlers/fieldmanager/bench_test.go +++ b/pkg/endpoints/handlers/fieldmanager/bench_test.go @@ -17,7 +17,11 @@ limitations under the License. package fieldmanager_test import ( + "encoding/json" "fmt" + "io/ioutil" + "path/filepath" + "strings" "testing" corev1 "k8s.io/api/core/v1" @@ -27,10 +31,42 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanagertest" + "k8s.io/apimachinery/pkg/util/managedfields" + "k8s.io/apimachinery/pkg/util/managedfields/managedfieldstest" + "k8s.io/kube-openapi/pkg/validation/spec" "sigs.k8s.io/yaml" ) +var fakeTypeConverter = func() managedfields.TypeConverter { + data, err := ioutil.ReadFile(filepath.Join(strings.Repeat(".."+string(filepath.Separator), 8), + "api", "openapi-spec", "swagger.json")) + if err != nil { + panic(err) + } + swagger := spec.Swagger{} + if err := json.Unmarshal(data, &swagger); err != nil { + panic(err) + } + definitions := map[string]*spec.Schema{} + for k, v := range swagger.Definitions { + p := v + definitions[k] = &p + } + typeConverter, err := managedfields.NewTypeConverter(definitions, false) + if err != nil { + panic(err) + } + return typeConverter +}() + +func getObjectBytes(file string) []byte { + s, err := ioutil.ReadFile(file) + if err != nil { + panic(err) + } + return s +} + func BenchmarkNewObject(b *testing.B) { tests := []struct { gvk schema.GroupVersionKind @@ -55,7 +91,7 @@ func BenchmarkNewObject(b *testing.B) { } for _, test := range tests { b.Run(test.gvk.Kind, func(b *testing.B) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, test.gvk) + f := managedfieldstest.NewTestFieldManager(fakeTypeConverter, test.gvk) decoder := serializer.NewCodecFactory(scheme).UniversalDecoder(test.gvk.GroupVersion()) newObj, err := runtime.Decode(decoder, test.obj) @@ -268,7 +304,7 @@ func BenchmarkCompare(b *testing.B) { } func BenchmarkRepeatedUpdate(b *testing.B) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) + f := managedfieldstest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) podBytes := getObjectBytes("pod.yaml") var obj *corev1.Pod diff --git a/pkg/endpoints/handlers/fieldmanager/fieldmanager.go b/pkg/endpoints/handlers/fieldmanager/fieldmanager.go deleted file mode 100644 index 668f76882..000000000 --- a/pkg/endpoints/handlers/fieldmanager/fieldmanager.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2018 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 fieldmanager - -import ( - "fmt" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -// FieldManager updates the managed fields and merges applied -// configurations. -type FieldManager = internal.FieldManager - -// NewDefaultFieldManager creates a new FieldManager that merges apply requests -// and update managed fields for other types of requests. -func NewDefaultFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (*FieldManager, error) { - f, err := internal.NewStructuredMergeManager(typeConverter, objectConverter, objectDefaulter, kind.GroupVersion(), hub, resetFields) - if err != nil { - return nil, fmt.Errorf("failed to create field manager: %v", err) - } - return internal.NewDefaultFieldManager(f, typeConverter, objectConverter, objectCreater, kind, subresource), nil -} - -// NewDefaultCRDFieldManager creates a new FieldManager specifically for -// CRDs. This allows for the possibility of fields which are not defined -// in models, as well as having no models defined at all. -func NewDefaultCRDFieldManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, hub schema.GroupVersion, subresource string, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (_ *FieldManager, err error) { - f, err := internal.NewCRDStructuredMergeManager(typeConverter, objectConverter, objectDefaulter, kind.GroupVersion(), hub, resetFields) - if err != nil { - return nil, fmt.Errorf("failed to create field manager: %v", err) - } - return internal.NewDefaultFieldManager(f, typeConverter, objectConverter, objectCreater, kind, subresource), nil -} - -func ValidateManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) error { - _, err := internal.DecodeManagedFields(encodedManagedFields) - return err -} diff --git a/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go b/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go deleted file mode 100644 index db5cbabcb..000000000 --- a/pkg/endpoints/handlers/fieldmanager/fieldmanager_test.go +++ /dev/null @@ -1,1138 +0,0 @@ -/* -Copyright 2019 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 fieldmanager_test - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "path/filepath" - "reflect" - "strings" - "testing" - "time" - - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - yamlutil "k8s.io/apimachinery/pkg/util/yaml" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanagertest" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "k8s.io/kube-openapi/pkg/validation/spec" - "sigs.k8s.io/yaml" -) - -var fakeTypeConverter = func() fieldmanager.TypeConverter { - data, err := ioutil.ReadFile(filepath.Join(strings.Repeat(".."+string(filepath.Separator), 8), - "api", "openapi-spec", "swagger.json")) - if err != nil { - panic(err) - } - swag := spec.Swagger{} - if err := json.Unmarshal(data, &swag); err != nil { - panic(err) - } - convertedDefs := map[string]*spec.Schema{} - for k, v := range swag.Definitions { - vCopy := v - convertedDefs[k] = &vCopy - } - typeConverter, err := fieldmanager.NewTypeConverter(convertedDefs, false) - if err != nil { - panic(err) - } - return typeConverter -}() - -// TestUpdateApplyConflict tests that applying to an object, which -// wasn't created by apply, will give conflicts -func TestUpdateApplyConflict(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - patch := []byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - "labels": {"app": "nginx"} - }, - "spec": { - "replicas": 3, - "selector": { - "matchLabels": { - "app": "nginx" - } - }, - "template": { - "metadata": { - "labels": { - "app": "nginx" - } - }, - "spec": { - "containers": [{ - "name": "nginx", - "image": "nginx:latest" - }] - } - } - } - }`) - newObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(patch, &newObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - if err := f.Update(newObj, "fieldmanager_test"); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - }, - "spec": { - "replicas": 101, - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - err := f.Apply(appliedObj, "fieldmanager_conflict", false) - if err == nil || !apierrors.IsConflict(err) { - t.Fatalf("Expecting to get conflicts but got %v", err) - } -} - -func TestApplyStripsFields(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - newObj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": "apps/v1", - "kind": "Deployment", - }, - } - - newObj.SetName("b") - newObj.SetNamespace("b") - newObj.SetUID("b") - newObj.SetGeneration(0) - newObj.SetResourceVersion("b") - newObj.SetCreationTimestamp(metav1.NewTime(time.Now())) - newObj.SetManagedFields([]metav1.ManagedFieldsEntry{ - { - Manager: "update", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - }, - }) - if err := f.Update(newObj, "fieldmanager_test"); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - if m := f.ManagedFields(); len(m) != 0 { - t.Fatalf("fields did not get stripped: %v", m) - } -} - -func TestVersionCheck(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // patch has 'apiVersion: apps/v1' and live version is apps/v1 -> no errors - err := f.Apply(appliedObj, "fieldmanager_test", false) - if err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - appliedObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1beta1", - "kind": "Deployment", - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // patch has 'apiVersion: apps/v2' but live version is apps/v1 -> error - err = f.Apply(appliedObj, "fieldmanager_test", false) - if err == nil { - t.Fatalf("expected an error from mismatched patch and live versions") - } - switch typ := err.(type) { - default: - t.Fatalf("expected error to be of type %T was %T", apierrors.StatusError{}, typ) - case apierrors.APIStatus: - if typ.Status().Code != http.StatusBadRequest { - t.Fatalf("expected status code to be %d but was %d", - http.StatusBadRequest, typ.Status().Code) - } - } -} -func TestVersionCheckDoesNotPanic(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // patch has 'apiVersion: apps/v1' and live version is apps/v1 -> no errors - err := f.Apply(appliedObj, "fieldmanager_test", false) - if err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - appliedObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // patch has 'apiVersion: apps/v2' but live version is apps/v1 -> error - err = f.Apply(appliedObj, "fieldmanager_test", false) - if err == nil { - t.Fatalf("expected an error from mismatched patch and live versions") - } - switch typ := err.(type) { - default: - t.Fatalf("expected error to be of type %T was %T", apierrors.StatusError{}, typ) - case apierrors.APIStatus: - if typ.Status().Code != http.StatusBadRequest { - t.Fatalf("expected status code to be %d but was %d", - http.StatusBadRequest, typ.Status().Code) - } - } -} - -func TestApplyDoesNotStripLabels(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "labels": { - "a": "b" - }, - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - err := f.Apply(appliedObj, "fieldmanager_test", false) - if err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - if m := f.ManagedFields(); len(m) != 1 { - t.Fatalf("labels shouldn't get stripped on apply: %v", m) - } -} - -func getObjectBytes(file string) []byte { - s, err := ioutil.ReadFile(file) - if err != nil { - panic(err) - } - return s -} - -func TestApplyNewObject(t *testing.T) { - tests := []struct { - gvk schema.GroupVersionKind - obj []byte - }{ - { - gvk: schema.FromAPIVersionAndKind("v1", "Pod"), - obj: getObjectBytes("pod.yaml"), - }, - { - gvk: schema.FromAPIVersionAndKind("v1", "Node"), - obj: getObjectBytes("node.yaml"), - }, - { - gvk: schema.FromAPIVersionAndKind("v1", "Endpoints"), - obj: getObjectBytes("endpoints.yaml"), - }, - } - - for _, test := range tests { - t.Run(test.gvk.String(), func(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, test.gvk) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(test.obj, &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - if err := f.Apply(appliedObj, "fieldmanager_test", false); err != nil { - t.Fatal(err) - } - }) - } -} - -func TestApplyFailsWithManagedFields(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "managedFields": [ - { - "manager": "test", - } - ] - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - err := f.Apply(appliedObj, "fieldmanager_test", false) - - if err == nil { - t.Fatalf("successfully applied with set managed fields") - } -} - -func TestApplySuccessWithNoManagedFields(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "labels": { - "a": "b" - }, - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - err := f.Apply(appliedObj, "fieldmanager_test", false) - - if err != nil { - t.Fatalf("failed to apply object: %v", err) - } -} - -// Run an update and apply, and make sure that nothing has changed. -func TestNoOpChanges(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "labels": { - "a": "b" - }, - "creationTimestamp": null, - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - if err := f.Apply(obj.DeepCopyObject(), "fieldmanager_test_apply", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - before := f.Live() - // Wait to make sure the timestamp is different - time.Sleep(time.Second) - // Applying with a different fieldmanager will create an entry.. - if err := f.Apply(obj.DeepCopyObject(), "fieldmanager_test_apply_other", false); err != nil { - t.Fatalf("failed to update object: %v", err) - } - if reflect.DeepEqual(before, f.Live()) { - t.Fatalf("Applying no-op apply with new manager didn't change object: \n%v", f.Live()) - } - before = f.Live() - // Wait to make sure the timestamp is different - time.Sleep(time.Second) - if err := f.Update(obj.DeepCopyObject(), "fieldmanager_test_update"); err != nil { - t.Fatalf("failed to update object: %v", err) - } - if !reflect.DeepEqual(before, f.Live()) { - t.Fatalf("No-op update has changed the object:\n%v\n---\n%v", before, f.Live()) - } - before = f.Live() - // Wait to make sure the timestamp is different - time.Sleep(time.Second) - if err := f.Apply(obj.DeepCopyObject(), "fieldmanager_test_apply", true); err != nil { - t.Fatalf("failed to re-apply object: %v", err) - } - if !reflect.DeepEqual(before, f.Live()) { - t.Fatalf("No-op apply has changed the object:\n%v\n---\n%v", before, f.Live()) - } -} - -// Tests that one can reset the managedFields by sending either an empty -// list -func TestResetManagedFieldsEmptyList(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "labels": { - "a": "b" - }, - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - if err := f.Apply(obj, "fieldmanager_test_apply", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "managedFields": [], - "labels": { - "a": "b" - }, - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - if err := f.Update(obj, "update_manager"); err != nil { - t.Fatalf("failed to update with empty manager: %v", err) - } - - if len(f.ManagedFields()) != 0 { - t.Fatalf("failed to reset managedFields: %v", f.ManagedFields()) - } -} - -// Tests that one can reset the managedFields by sending either a list with one empty item. -func TestResetManagedFieldsEmptyItem(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "labels": { - "a": "b" - }, - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - if err := f.Apply(obj, "fieldmanager_test_apply", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "managedFields": [{}], - "labels": { - "a": "b" - }, - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - if err := f.Update(obj, "update_manager"); err != nil { - t.Fatalf("failed to update with empty manager: %v", err) - } - - if len(f.ManagedFields()) != 0 { - t.Fatalf("failed to reset managedFields: %v", f.ManagedFields()) - } -} - -func TestServerSideApplyWithInvalidLastApplied(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - // create object with client-side apply - newObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment := []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app-v1 -spec: - replicas: 1 -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - - invalidLastApplied := "invalid-object" - if err := internal.SetLastApplied(newObj, invalidLastApplied); err != nil { - t.Errorf("failed to set last applied: %v", err) - } - - if err := f.Update(newObj, "kubectl-client-side-apply-test"); err != nil { - t.Errorf("failed to update object: %v", err) - } - - lastApplied, err := getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if lastApplied != invalidLastApplied { - t.Errorf("expected last applied annotation to be set to %q, but got: %q", invalidLastApplied, lastApplied) - } - - // upgrade management of the object from client-side apply to server-side apply - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - appliedDeployment := []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app-v2 -spec: - replicas: 100 -`) - if err := yaml.Unmarshal(appliedDeployment, &appliedObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - - if err := f.Apply(appliedObj, "kubectl", false); err == nil || !apierrors.IsConflict(err) { - t.Errorf("expected conflict when applying with invalid last-applied annotation, but got no error for object: \n%+v", appliedObj) - } - - lastApplied, err = getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if lastApplied != invalidLastApplied { - t.Errorf("expected last applied annotation to be NOT be updated, but got: %q", lastApplied) - } - - // force server-side apply should work and fix the annotation - if err := f.Apply(appliedObj, "kubectl", true); err != nil { - t.Errorf("failed to force server-side apply with: %v", err) - } - - lastApplied, err = getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if lastApplied == invalidLastApplied || - !strings.Contains(lastApplied, "my-app-v2") { - t.Errorf("expected last applied annotation to be updated, but got: %q", lastApplied) - } -} - -func TestInteropForClientSideApplyAndServerSideApply(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - // create object with client-side apply - newObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment := []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image-v1 -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - if err := setLastAppliedFromEncoded(newObj, deployment); err != nil { - t.Errorf("failed to set last applied: %v", err) - } - - if err := f.Update(newObj, "kubectl-client-side-apply-test"); err != nil { - t.Errorf("failed to update object: %v", err) - } - lastApplied, err := getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if !strings.Contains(lastApplied, "my-image-v1") { - t.Errorf("expected last applied annotation to be set properly, but got: %q", lastApplied) - } - - // upgrade management of the object from client-side apply to server-side apply - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - appliedDeployment := []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app-v2 # change -spec: - replicas: 8 # change - selector: - matchLabels: - app: my-app-v2 # change - template: - metadata: - labels: - app: my-app-v2 # change - spec: - containers: - - name: my-c - image: my-image-v2 # change -`) - if err := yaml.Unmarshal(appliedDeployment, &appliedObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - - if err := f.Apply(appliedObj, "kubectl", false); err != nil { - t.Errorf("error applying object: %v", err) - } - - lastApplied, err = getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if !strings.Contains(lastApplied, "my-image-v2") { - t.Errorf("expected last applied annotation to be updated, but got: %q", lastApplied) - } -} - -func TestNoTrackManagedFieldsForClientSideApply(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - // create object - newObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment := []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - if err := f.Update(newObj, "test_kubectl_create"); err != nil { - t.Errorf("failed to update object: %v", err) - } - if m := f.ManagedFields(); len(m) == 0 { - t.Errorf("expected to have managed fields, but got: %v", m) - } - - // stop tracking managed fields - newObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment = []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - managedFields: [] # stop tracking managed fields - labels: - app: my-app -spec: - replicas: 100 -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - newObj.SetUID("nonempty") - if err := f.Update(newObj, "test_kubectl_replace"); err != nil { - t.Errorf("failed to update object: %v", err) - } - if m := f.ManagedFields(); len(m) != 0 { - t.Errorf("expected to have stop tracking managed fields, but got: %v", m) - } - - // check that we still don't track managed fields - newObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment = []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - if err := setLastAppliedFromEncoded(newObj, deployment); err != nil { - t.Errorf("failed to set last applied: %v", err) - } - if err := f.Update(newObj, "test_k_client_side_apply"); err != nil { - t.Errorf("failed to update object: %v", err) - } - if m := f.ManagedFields(); len(m) != 0 { - t.Errorf("expected to continue to not track managed fields, but got: %v", m) - } - lastApplied, err := getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if !strings.Contains(lastApplied, "my-app") { - t.Errorf("expected last applied annotation to be set properly, but got: %q", lastApplied) - } - - // start tracking managed fields - newObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment = []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - if err := f.Apply(newObj, "test_server_side_apply_without_upgrade", false); err != nil { - t.Errorf("error applying object: %v", err) - } - if m := f.ManagedFields(); len(m) < 2 { - t.Errorf("expected to start tracking managed fields with at least 2 field managers, but got: %v", m) - } - if e, a := "test_server_side_apply_without_upgrade", f.ManagedFields()[0].Manager; e != a { - t.Fatalf("exected first manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } - if e, a := "before-first-apply", f.ManagedFields()[1].Manager; e != a { - t.Fatalf("exected second manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } - - // upgrade management of the object from client-side apply to server-side apply - newObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - deployment = []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app-v2 # change -spec: - replicas: 8 # change -`) - if err := yaml.Unmarshal(deployment, &newObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - if err := f.Apply(newObj, "kubectl", false); err != nil { - t.Errorf("error applying object: %v", err) - } - if m := f.ManagedFields(); len(m) == 0 { - t.Errorf("expected to track managed fields, but got: %v", m) - } - lastApplied, err = getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - if !strings.Contains(lastApplied, "my-app-v2") { - t.Errorf("expected last applied annotation to be updated, but got: %q", lastApplied) - } -} - -func yamlToJSON(y []byte) (string, error) { - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(y, &obj.Object); err != nil { - return "", fmt.Errorf("error decoding YAML: %v", err) - } - serialization, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj) - if err != nil { - return "", fmt.Errorf("error encoding object: %v", err) - } - json, err := yamlutil.ToJSON(serialization) - if err != nil { - return "", fmt.Errorf("error converting to json: %v", err) - } - return string(json), nil -} - -func setLastAppliedFromEncoded(obj runtime.Object, lastApplied []byte) error { - lastAppliedJSON, err := yamlToJSON(lastApplied) - if err != nil { - return err - } - return internal.SetLastApplied(obj, lastAppliedJSON) -} - -func getLastApplied(obj runtime.Object) (string, error) { - accessor := meta.NewAccessor() - annotations, err := accessor.Annotations(obj) - if err != nil { - return "", fmt.Errorf("failed to access annotations: %v", err) - } - if annotations == nil { - return "", fmt.Errorf("no annotations on obj: %v", obj) - } - - lastApplied, ok := annotations[internal.LastAppliedConfigAnnotation] - if !ok { - return "", fmt.Errorf("expected last applied annotation, but got none for object: %v", obj) - } - return lastApplied, nil -} - -func TestUpdateViaSubresources(t *testing.T) { - f := fieldmanagertest.NewTestFieldManagerSubresource(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod"), "scale") - - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "labels": { - "a":"b" - }, - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - obj.SetManagedFields([]metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{ - Raw: []byte(`{"f:metadata":{"f:labels":{"f:another_field":{}}}}`), - }, - }, - }) - - // Check that managed fields cannot be changed explicitly via subresources - expectedManager := "fieldmanager_test_subresource" - if err := f.Update(obj, expectedManager); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - managedFields := f.ManagedFields() - if len(managedFields) != 1 { - t.Fatalf("Expected new managed fields to have one entry. Got:\n%#v", managedFields) - } - if managedFields[0].Manager != expectedManager { - t.Fatalf("Expected first item to have manager set to: %s. Got: %s", expectedManager, managedFields[0].Manager) - } - - // Check that managed fields cannot be reset via subresources - newObj := obj.DeepCopy() - newObj.SetManagedFields([]metav1.ManagedFieldsEntry{}) - if err := f.Update(newObj, expectedManager); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - newManagedFields := f.ManagedFields() - if len(newManagedFields) != 1 { - t.Fatalf("Expected new managed fields to have one entry. Got:\n%#v", newManagedFields) - } -} - -// Ensures that a no-op Apply does not mutate managed fields -func TestApplyDoesNotChangeManagedFields(t *testing.T) { - originalManagedFields := []metav1.ManagedFieldsEntry{} - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, - schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - newObj := &unstructured.Unstructured{ - Object: map[string]interface{}{}, - } - appliedObj := &unstructured.Unstructured{ - Object: map[string]interface{}{}, - } - - // Convert YAML string inputs to unstructured instances - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - "labels": {"app": "nginx"} - }, - "spec": { - "selector": { - "matchLabels": { - "app": "nginx" - } - }, - "template": { - "metadata": { - "labels": { - "app": "nginx" - } - }, - "spec": { - "containers": [{ - "name": "nginx", - "image": "nginx:latest" - }] - } - } - } - }`), &newObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - }, - "spec": { - "replicas": 101, - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // Agent A applies initial configuration - if err := f.Apply(newObj.DeepCopyObject(), "fieldmanager_z", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - // Agent B applies additive configuration - if err := f.Apply(appliedObj, "fieldmanager_b", false); err != nil { - t.Fatalf("failed to apply object %v", err) - } - - // Next, agent A applies the initial configuration again, but we expect - // a no-op to managed fields. - // - // The following update is expected not to change the liveObj, save off - // the fields - for _, field := range f.ManagedFields() { - originalManagedFields = append(originalManagedFields, *field.DeepCopy()) - } - - // Make sure timestamp change would be caught - time.Sleep(2 * time.Second) - - if err := f.Apply(newObj, "fieldmanager_z", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - // ensure that the live object is unchanged - if !reflect.DeepEqual(originalManagedFields, f.ManagedFields()) { - originalYAML, _ := yaml.Marshal(originalManagedFields) - current, _ := yaml.Marshal(f.ManagedFields()) - - // should have been a no-op w.r.t. managed fields - t.Fatalf("managed fields changed: ORIGINAL\n%v\nCURRENT\n%v", - string(originalYAML), string(current)) - } -} - -// Ensures that a no-op Update does not mutate managed fields -func TestUpdateDoesNotChangeManagedFields(t *testing.T) { - originalManagedFields := []metav1.ManagedFieldsEntry{} - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, - schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - newObj := &unstructured.Unstructured{ - Object: map[string]interface{}{}, - } - - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - "labels": {"app": "nginx"} - }, - "spec": { - "selector": { - "matchLabels": { - "app": "nginx" - } - }, - "template": { - "metadata": { - "labels": { - "app": "nginx" - } - }, - "spec": { - "containers": [{ - "name": "nginx", - "image": "nginx:latest" - }] - } - } - } - }`), &newObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // Agent A updates with initial configuration - if err := f.Update(newObj.DeepCopyObject(), "fieldmanager_z"); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - for _, field := range f.ManagedFields() { - originalManagedFields = append(originalManagedFields, *field.DeepCopy()) - } - - // Make sure timestamp change would be caught - time.Sleep(2 * time.Second) - - // If the same exact configuration is updated once again, the - // managed fields are not expected to change - // - // However, a change in field ownership WOULD be a semantic change which - // should cause managed fields to change. - if err := f.Update(newObj, "fieldmanager_z"); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - // ensure that the live object is unchanged - if !reflect.DeepEqual(originalManagedFields, f.ManagedFields()) { - originalYAML, _ := yaml.Marshal(originalManagedFields) - current, _ := yaml.Marshal(f.ManagedFields()) - - // should have been a no-op w.r.t. managed fields - t.Fatalf("managed fields changed: ORIGINAL\n%v\nCURRENT\n%v", - string(originalYAML), string(current)) - } -} - -// This test makes sure that the liveObject during a patch does not mutate -// its managed fields. -func TestLiveObjectManagedFieldsNotRemoved(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, - schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - newObj := &unstructured.Unstructured{ - Object: map[string]interface{}{}, - } - appliedObj := &unstructured.Unstructured{ - Object: map[string]interface{}{}, - } - // Convert YAML string inputs to unstructured instances - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - "labels": {"app": "nginx"} - }, - "spec": { - "selector": { - "matchLabels": { - "app": "nginx" - } - }, - "template": { - "metadata": { - "labels": { - "app": "nginx" - } - }, - "spec": { - "containers": [{ - "name": "nginx", - "image": "nginx:latest" - }] - } - } - } - }`), &newObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "apps/v1", - "kind": "Deployment", - "metadata": { - "name": "deployment", - }, - "spec": { - "replicas": 101, - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - // Agent A applies initial configuration - if err := f.Apply(newObj.DeepCopyObject(), "fieldmanager_z", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - originalLiveObj := f.Live() - - accessor, err := meta.Accessor(originalLiveObj) - if err != nil { - panic(fmt.Errorf("couldn't get accessor: %v", err)) - } - - // Managed fields should not be stripped - if len(accessor.GetManagedFields()) == 0 { - t.Fatalf("empty managed fields of object which expected nonzero fields") - } - - // Agent A applies the exact same configuration - if err := f.Apply(appliedObj.DeepCopyObject(), "fieldmanager_z", false); err != nil { - t.Fatalf("failed to apply object: %v", err) - } - - accessor, err = meta.Accessor(originalLiveObj) - if err != nil { - panic(fmt.Errorf("couldn't get accessor: %v", err)) - } - - // Managed fields should not be stripped - if len(accessor.GetManagedFields()) == 0 { - t.Fatalf("empty managed fields of object which expected nonzero fields") - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/fieldmanagertest/testfieldmanager.go b/pkg/endpoints/handlers/fieldmanager/fieldmanagertest/testfieldmanager.go deleted file mode 100644 index d188d171d..000000000 --- a/pkg/endpoints/handlers/fieldmanager/fieldmanagertest/testfieldmanager.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2022 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 fieldmanagertest - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal/testing" -) - -// TestFieldManager is a FieldManager that can be used in test to -// simulate the behavior of Server-Side Apply and field tracking. This -// also has a few methods to get a sense of the state of the object. -// -// This TestFieldManager uses a series of "fake" objects to simulate -// some behavior which come with the limitation that you can only use -// one version since there is no version conversion logic. -// -// You can use this rather than NewDefaultTestFieldManager if you want -// to specify either a sub-resource, or a set of modified Manager to -// test them specifically. -type TestFieldManager interface { - // APIVersion of the object that we're tracking. - APIVersion() string - // Reset resets the state of the liveObject by resetting it to an empty object. - Reset() - // Live returns a copy of the current liveObject. - Live() runtime.Object - // Apply applies the given object on top of the current liveObj, for the - // given manager and force flag. - Apply(obj runtime.Object, manager string, force bool) error - // Update will updates the managed fields in the liveObj based on the - // changes performed by the update. - Update(obj runtime.Object, manager string) error - // ManagedFields returns the list of existing managed fields for the - // liveObj. - ManagedFields() []metav1.ManagedFieldsEntry -} - -// NewTestFieldManager returns a new TestFieldManager built for the -// given gvk, on the main resource. -func NewTestFieldManager(typeConverter fieldmanager.TypeConverter, gvk schema.GroupVersionKind) TestFieldManager { - return testing.NewTestFieldManagerImpl(typeConverter, gvk, "", nil) -} - -// NewTestFieldManagerSubresource returns a new TestFieldManager built -// for the given gvk, on the given sub-resource. -func NewTestFieldManagerSubresource(typeConverter fieldmanager.TypeConverter, gvk schema.GroupVersionKind, subresource string) TestFieldManager { - return testing.NewTestFieldManagerImpl(typeConverter, gvk, subresource, nil) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/atmostevery.go b/pkg/endpoints/handlers/fieldmanager/internal/atmostevery.go deleted file mode 100644 index b75ef7416..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/atmostevery.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2020 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 internal - -import ( - "sync" - "time" -) - -// AtMostEvery will never run the method more than once every specified -// duration. -type AtMostEvery struct { - delay time.Duration - lastCall time.Time - mutex sync.Mutex -} - -// NewAtMostEvery creates a new AtMostEvery, that will run the method at -// most every given duration. -func NewAtMostEvery(delay time.Duration) *AtMostEvery { - return &AtMostEvery{ - delay: delay, - } -} - -// updateLastCall returns true if the lastCall time has been updated, -// false if it was too early. -func (s *AtMostEvery) updateLastCall() bool { - s.mutex.Lock() - defer s.mutex.Unlock() - if time.Since(s.lastCall) < s.delay { - return false - } - s.lastCall = time.Now() - return true -} - -// Do will run the method if enough time has passed, and return true. -// Otherwise, it does nothing and returns false. -func (s *AtMostEvery) Do(fn func()) bool { - if !s.updateLastCall() { - return false - } - fn() - return true -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/atmostevery_test.go b/pkg/endpoints/handlers/fieldmanager/internal/atmostevery_test.go deleted file mode 100644 index 51df7b8cd..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/atmostevery_test.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2020 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 internal_test - -import ( - "testing" - "time" - - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" -) - -func TestAtMostEvery(t *testing.T) { - duration := time.Second - delay := 179 * time.Millisecond - atMostEvery := internal.NewAtMostEvery(delay) - count := 0 - exit := time.NewTicker(duration) - tick := time.NewTicker(2 * time.Millisecond) - defer exit.Stop() - defer tick.Stop() - - done := false - for !done { - select { - case <-exit.C: - done = true - case <-tick.C: - atMostEvery.Do(func() { - count++ - }) - } - } - - if expected := int(duration/delay) + 1; count > expected { - t.Fatalf("Function called %d times, should have been called less than or equal to %d times", count, expected) - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/buildmanagerinfo.go b/pkg/endpoints/handlers/fieldmanager/internal/buildmanagerinfo.go deleted file mode 100644 index fa342ca13..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/buildmanagerinfo.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2019 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 internal - -import ( - "fmt" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type buildManagerInfoManager struct { - fieldManager Manager - groupVersion schema.GroupVersion - subresource string -} - -var _ Manager = &buildManagerInfoManager{} - -// NewBuildManagerInfoManager creates a new Manager that converts the manager name into a unique identifier -// combining operation and version for update requests, and just operation for apply requests. -func NewBuildManagerInfoManager(f Manager, gv schema.GroupVersion, subresource string) Manager { - return &buildManagerInfoManager{ - fieldManager: f, - groupVersion: gv, - subresource: subresource, - } -} - -// Update implements Manager. -func (f *buildManagerInfoManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - manager, err := f.buildManagerInfo(manager, metav1.ManagedFieldsOperationUpdate) - if err != nil { - return nil, nil, fmt.Errorf("failed to build manager identifier: %v", err) - } - return f.fieldManager.Update(liveObj, newObj, managed, manager) -} - -// Apply implements Manager. -func (f *buildManagerInfoManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { - manager, err := f.buildManagerInfo(manager, metav1.ManagedFieldsOperationApply) - if err != nil { - return nil, nil, fmt.Errorf("failed to build manager identifier: %v", err) - } - return f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force) -} - -func (f *buildManagerInfoManager) buildManagerInfo(prefix string, operation metav1.ManagedFieldsOperationType) (string, error) { - managerInfo := metav1.ManagedFieldsEntry{ - Manager: prefix, - Operation: operation, - APIVersion: f.groupVersion.String(), - Subresource: f.subresource, - } - if managerInfo.Manager == "" { - managerInfo.Manager = "unknown" - } - return BuildManagerIdentifier(&managerInfo) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/capmanagers.go b/pkg/endpoints/handlers/fieldmanager/internal/capmanagers.go deleted file mode 100644 index 8951932ba..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/capmanagers.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2019 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 internal - -import ( - "fmt" - "sort" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -type capManagersManager struct { - fieldManager Manager - maxUpdateManagers int - oldUpdatesManagerName string -} - -var _ Manager = &capManagersManager{} - -// NewCapManagersManager creates a new wrapped FieldManager which ensures that the number of managers from updates -// does not exceed maxUpdateManagers, by merging some of the oldest entries on each update. -func NewCapManagersManager(fieldManager Manager, maxUpdateManagers int) Manager { - return &capManagersManager{ - fieldManager: fieldManager, - maxUpdateManagers: maxUpdateManagers, - oldUpdatesManagerName: "ancient-changes", - } -} - -// Update implements Manager. -func (f *capManagersManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - object, managed, err := f.fieldManager.Update(liveObj, newObj, managed, manager) - if err != nil { - return object, managed, err - } - if managed, err = f.capUpdateManagers(managed); err != nil { - return nil, nil, fmt.Errorf("failed to cap update managers: %v", err) - } - return object, managed, nil -} - -// Apply implements Manager. -func (f *capManagersManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { - return f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) -} - -// capUpdateManagers merges a number of the oldest update entries into versioned buckets, -// such that the number of entries from updates does not exceed f.maxUpdateManagers. -func (f *capManagersManager) capUpdateManagers(managed Managed) (newManaged Managed, err error) { - // Gather all entries from updates - updaters := []string{} - for manager, fields := range managed.Fields() { - if !fields.Applied() { - updaters = append(updaters, manager) - } - } - if len(updaters) <= f.maxUpdateManagers { - return managed, nil - } - - // If we have more than the maximum, sort the update entries by time, oldest first. - sort.Slice(updaters, func(i, j int) bool { - iTime, jTime, iSeconds, jSeconds := managed.Times()[updaters[i]], managed.Times()[updaters[j]], int64(0), int64(0) - if iTime != nil { - iSeconds = iTime.Unix() - } - if jTime != nil { - jSeconds = jTime.Unix() - } - if iSeconds != jSeconds { - return iSeconds < jSeconds - } - return updaters[i] < updaters[j] - }) - - // Merge the oldest updaters with versioned bucket managers until the number of updaters is under the cap - versionToFirstManager := map[string]string{} - for i, length := 0, len(updaters); i < len(updaters) && length > f.maxUpdateManagers; i++ { - manager := updaters[i] - vs := managed.Fields()[manager] - time := managed.Times()[manager] - version := string(vs.APIVersion()) - - // Create a new manager identifier for the versioned bucket entry. - // The version for this manager comes from the version of the update being merged into the bucket. - bucket, err := BuildManagerIdentifier(&metav1.ManagedFieldsEntry{ - Manager: f.oldUpdatesManagerName, - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: version, - }) - if err != nil { - return managed, fmt.Errorf("failed to create bucket manager for version %v: %v", version, err) - } - - // Merge the fieldets if this is not the first time the version was seen. - // Otherwise just record the manager name in versionToFirstManager - if first, ok := versionToFirstManager[version]; ok { - // If the bucket doesn't exists yet, create one. - if _, ok := managed.Fields()[bucket]; !ok { - s := managed.Fields()[first] - delete(managed.Fields(), first) - managed.Fields()[bucket] = s - } - - managed.Fields()[bucket] = fieldpath.NewVersionedSet(vs.Set().Union(managed.Fields()[bucket].Set()), vs.APIVersion(), vs.Applied()) - delete(managed.Fields(), manager) - length-- - - // Use the time from the update being merged into the bucket, since it is more recent. - managed.Times()[bucket] = time - } else { - versionToFirstManager[version] = manager - } - } - - return managed, nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/capmanagers_test.go b/pkg/endpoints/handlers/fieldmanager/internal/capmanagers_test.go deleted file mode 100644 index bab471ba3..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/capmanagers_test.go +++ /dev/null @@ -1,294 +0,0 @@ -/* -Copyright 2019 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 internal_test - -import ( - "bytes" - "encoding/json" - "fmt" - "testing" - "time" - - apiequality "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanagertest" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - internaltesting "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal/testing" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -type fakeManager struct{} - -var _ internal.Manager = &fakeManager{} - -func (*fakeManager) Update(_, newObj runtime.Object, managed internal.Managed, _ string) (runtime.Object, internal.Managed, error) { - return newObj, managed, nil -} - -func (*fakeManager) Apply(_, _ runtime.Object, _ internal.Managed, _ string, _ bool) (runtime.Object, internal.Managed, error) { - panic("not implemented") -} - -func TestCapManagersManagerMergesEntries(t *testing.T) { - f := internaltesting.NewTestFieldManagerImpl(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod"), - "", - func(m internal.Manager) internal.Manager { - return internal.NewCapManagersManager(m, 3) - }) - - podWithLabels := func(labels ...string) runtime.Object { - labelMap := map[string]interface{}{} - for _, key := range labels { - labelMap[key] = "true" - } - obj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "metadata": map[string]interface{}{ - "labels": labelMap, - }, - }, - } - obj.SetKind("Pod") - obj.SetAPIVersion("v1") - return obj - } - - if err := f.Update(podWithLabels("one"), "fieldmanager_test_update_1"); err != nil { - t.Fatalf("failed to update object: %v", err) - } - expectIdempotence(t, f) - - if err := f.Update(podWithLabels("one", "two"), "fieldmanager_test_update_2"); err != nil { - t.Fatalf("failed to update object: %v", err) - } - expectIdempotence(t, f) - - if err := f.Update(podWithLabels("one", "two", "three"), "fieldmanager_test_update_3"); err != nil { - t.Fatalf("failed to update object: %v", err) - } - expectIdempotence(t, f) - - if err := f.Update(podWithLabels("one", "two", "three", "four"), "fieldmanager_test_update_4"); err != nil { - t.Fatalf("failed to update object: %v", err) - } - expectIdempotence(t, f) - - if e, a := 3, len(f.ManagedFields()); e != a { - t.Fatalf("exected %v entries in managedFields, but got %v: %#v", e, a, f.ManagedFields()) - } - - if e, a := "ancient-changes", f.ManagedFields()[0].Manager; e != a { - t.Fatalf("exected first manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } - - if e, a := "fieldmanager_test_update_3", f.ManagedFields()[1].Manager; e != a { - t.Fatalf("exected second manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } - - if e, a := "fieldmanager_test_update_4", f.ManagedFields()[2].Manager; e != a { - t.Fatalf("exected third manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } - - expectManagesField(t, f, "ancient-changes", fieldpath.MakePathOrDie("metadata", "labels", "one")) - expectManagesField(t, f, "ancient-changes", fieldpath.MakePathOrDie("metadata", "labels", "two")) - expectManagesField(t, f, "fieldmanager_test_update_3", fieldpath.MakePathOrDie("metadata", "labels", "three")) - expectManagesField(t, f, "fieldmanager_test_update_4", fieldpath.MakePathOrDie("metadata", "labels", "four")) -} - -func TestCapUpdateManagers(t *testing.T) { - f := internaltesting.NewTestFieldManagerImpl(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod"), - "", - func(m internal.Manager) internal.Manager { - return internal.NewCapManagersManager(m, 3) - }) - - set := func(fields ...string) *metav1.FieldsV1 { - s := fieldpath.NewSet() - for _, f := range fields { - s.Insert(fieldpath.MakePathOrDie(f)) - } - b, err := s.ToJSON() - if err != nil { - panic(fmt.Sprintf("error building ManagedFieldsEntry for test: %v", err)) - } - return &metav1.FieldsV1{Raw: b} - } - - entry := func(name string, version string, order int, fields *metav1.FieldsV1) metav1.ManagedFieldsEntry { - return metav1.ManagedFieldsEntry{ - Manager: name, - APIVersion: version, - Operation: "Update", - FieldsType: "FieldsV1", - FieldsV1: fields, - Time: &metav1.Time{Time: time.Time{}.Add(time.Hour * time.Duration(order))}, - } - } - - testCases := []struct { - name string - input []metav1.ManagedFieldsEntry - expected []metav1.ManagedFieldsEntry - }{ - { - name: "one version, no ancient changes", - input: []metav1.ManagedFieldsEntry{ - entry("update-manager1", "v1", 1, set("a")), - entry("update-manager2", "v1", 2, set("b")), - entry("update-manager3", "v1", 3, set("c")), - entry("update-manager4", "v1", 4, set("d")), - }, - expected: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 2, set("a", "b")), - entry("update-manager3", "v1", 3, set("c")), - entry("update-manager4", "v1", 4, set("d")), - }, - }, { - name: "one version, one ancient changes", - input: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 2, set("a", "b")), - entry("update-manager3", "v1", 3, set("c")), - entry("update-manager4", "v1", 4, set("d")), - entry("update-manager5", "v1", 5, set("e")), - }, - expected: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 3, set("a", "b", "c")), - entry("update-manager4", "v1", 4, set("d")), - entry("update-manager5", "v1", 5, set("e")), - }, - }, { - name: "two versions, no ancient changes", - input: []metav1.ManagedFieldsEntry{ - entry("update-manager1", "v1", 1, set("a")), - entry("update-manager2", "v2", 2, set("b")), - entry("update-manager3", "v1", 3, set("c")), - entry("update-manager4", "v1", 4, set("d")), - entry("update-manager5", "v1", 5, set("e")), - }, - expected: []metav1.ManagedFieldsEntry{ - entry("update-manager2", "v2", 2, set("b")), - entry("ancient-changes", "v1", 4, set("a", "c", "d")), - entry("update-manager5", "v1", 5, set("e")), - }, - }, { - name: "three versions, one ancient changes", - input: []metav1.ManagedFieldsEntry{ - entry("update-manager2", "v2", 2, set("b")), - entry("ancient-changes", "v1", 4, set("a", "c", "d")), - entry("update-manager5", "v1", 5, set("e")), - entry("update-manager6", "v3", 6, set("f")), - entry("update-manager7", "v2", 7, set("g")), - }, - expected: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 5, set("a", "c", "d", "e")), - entry("update-manager6", "v3", 6, set("f")), - entry("ancient-changes", "v2", 7, set("b", "g")), - }, - }, { - name: "three versions, two ancient changes", - input: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 5, set("a", "c", "d", "e")), - entry("update-manager6", "v3", 6, set("f")), - entry("ancient-changes", "v2", 7, set("b", "g")), - entry("update-manager8", "v3", 8, set("h")), - }, - expected: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 5, set("a", "c", "d", "e")), - entry("ancient-changes", "v2", 7, set("b", "g")), - entry("ancient-changes", "v3", 8, set("f", "h")), - }, - }, { - name: "four versions, two ancient changes", - input: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 5, set("a", "c", "d", "e")), - entry("update-manager6", "v3", 6, set("f")), - entry("ancient-changes", "v2", 7, set("b", "g")), - entry("update-manager8", "v4", 8, set("h")), - }, - expected: []metav1.ManagedFieldsEntry{ - entry("ancient-changes", "v1", 5, set("a", "c", "d", "e")), - entry("update-manager6", "v3", 6, set("f")), - entry("ancient-changes", "v2", 7, set("b", "g")), - entry("update-manager8", "v4", 8, set("h")), - }, - }, - } - - for _, tc := range testCases { - f.Reset() - live := f.Live() - accessor, err := meta.Accessor(live) - if err != nil { - t.Fatalf("%v: couldn't get accessor: %v", tc.name, err) - } - accessor.SetManagedFields(tc.input) - if err := f.Update(live, "no-op-update"); err != nil { - t.Fatalf("%v: failed to do no-op update to object: %v", tc.name, err) - } - - if e, a := tc.expected, f.ManagedFields(); !apiequality.Semantic.DeepEqual(e, a) { - t.Errorf("%v: unexpected value for managedFields:\nexpected: %v\n but got: %v", tc.name, mustMarshal(e), mustMarshal(a)) - } - expectIdempotence(t, f) - } -} - -// expectIdempotence does a no-op update and ensures that managedFields doesn't change by calling capUpdateManagers. -func expectIdempotence(t *testing.T, f fieldmanagertest.TestFieldManager) { - before := []metav1.ManagedFieldsEntry{} - for _, m := range f.ManagedFields() { - before = append(before, *m.DeepCopy()) - } - - if err := f.Update(f.Live(), "no-op-update"); err != nil { - t.Fatalf("failed to do no-op update to object: %v", err) - } - - if after := f.ManagedFields(); !apiequality.Semantic.DeepEqual(before, after) { - t.Fatalf("exected idempotence, but managedFields changed:\nbefore: %v\n after: %v", mustMarshal(before), mustMarshal(after)) - } -} - -// expectManagesField ensures that manager m currently manages field path p. -func expectManagesField(t *testing.T, f fieldmanagertest.TestFieldManager, m string, p fieldpath.Path) { - for _, e := range f.ManagedFields() { - if e.Manager == m { - var s fieldpath.Set - err := s.FromJSON(bytes.NewReader(e.FieldsV1.Raw)) - if err != nil { - t.Fatalf("error parsing managedFields for %v: %v: %#v", m, err, f.ManagedFields()) - } - if !s.Has(p) { - t.Fatalf("expected managedFields for %v to contain %v, but got:\n%v", m, p.String(), s.String()) - } - return - } - } - t.Fatalf("exected to find manager name %v, but got: %#v", m, f.ManagedFields()) -} - -func mustMarshal(i interface{}) string { - b, err := json.MarshalIndent(i, "", " ") - if err != nil { - panic(fmt.Sprintf("error marshalling %v to json: %v", i, err)) - } - return string(b) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/conflict.go b/pkg/endpoints/handlers/fieldmanager/internal/conflict.go deleted file mode 100644 index 8c044c915..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/conflict.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2019 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 internal - -import ( - "encoding/json" - "fmt" - "sort" - "strings" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" -) - -// NewConflictError returns an error including details on the requests apply conflicts -func NewConflictError(conflicts merge.Conflicts) *errors.StatusError { - causes := []metav1.StatusCause{} - for _, conflict := range conflicts { - causes = append(causes, metav1.StatusCause{ - Type: metav1.CauseTypeFieldManagerConflict, - Message: fmt.Sprintf("conflict with %v", printManager(conflict.Manager)), - Field: conflict.Path.String(), - }) - } - return errors.NewApplyConflict(causes, getConflictMessage(conflicts)) -} - -func getConflictMessage(conflicts merge.Conflicts) string { - if len(conflicts) == 1 { - return fmt.Sprintf("Apply failed with 1 conflict: conflict with %v: %v", printManager(conflicts[0].Manager), conflicts[0].Path) - } - - m := map[string][]fieldpath.Path{} - for _, conflict := range conflicts { - m[conflict.Manager] = append(m[conflict.Manager], conflict.Path) - } - - uniqueManagers := []string{} - for manager := range m { - uniqueManagers = append(uniqueManagers, manager) - } - - // Print conflicts by sorted managers. - sort.Strings(uniqueManagers) - - messages := []string{} - for _, manager := range uniqueManagers { - messages = append(messages, fmt.Sprintf("conflicts with %v:", printManager(manager))) - for _, path := range m[manager] { - messages = append(messages, fmt.Sprintf("- %v", path)) - } - } - return fmt.Sprintf("Apply failed with %d conflicts: %s", len(conflicts), strings.Join(messages, "\n")) -} - -func printManager(manager string) string { - encodedManager := &metav1.ManagedFieldsEntry{} - if err := json.Unmarshal([]byte(manager), encodedManager); err != nil { - return fmt.Sprintf("%q", manager) - } - managerStr := fmt.Sprintf("%q", encodedManager.Manager) - if encodedManager.Subresource != "" { - managerStr = fmt.Sprintf("%s with subresource %q", managerStr, encodedManager.Subresource) - } - if encodedManager.Operation == metav1.ManagedFieldsOperationUpdate { - if encodedManager.Time == nil { - return fmt.Sprintf("%s using %v", managerStr, encodedManager.APIVersion) - } - return fmt.Sprintf("%s using %v at %v", managerStr, encodedManager.APIVersion, encodedManager.Time.UTC().Format(time.RFC3339)) - } - return managerStr -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/conflict_test.go b/pkg/endpoints/handlers/fieldmanager/internal/conflict_test.go deleted file mode 100644 index f9fc757c5..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/conflict_test.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2019 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 internal_test - -import ( - "net/http" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" -) - -// TestNewConflictError tests that NewConflictError creates the correct StatusError for a given smd Conflicts -func TestNewConflictError(t *testing.T) { - testCases := []struct { - conflict merge.Conflicts - expected *errors.StatusError - }{ - { - conflict: merge.Conflicts{ - merge.Conflict{ - Manager: `{"manager":"foo","operation":"Update","apiVersion":"v1","time":"2001-02-03T04:05:06Z"}`, - Path: fieldpath.MakePathOrDie("spec", "replicas"), - }, - }, - expected: &errors.StatusError{ - ErrStatus: metav1.Status{ - Status: metav1.StatusFailure, - Code: http.StatusConflict, - Reason: metav1.StatusReasonConflict, - Details: &metav1.StatusDetails{ - Causes: []metav1.StatusCause{ - { - Type: metav1.CauseTypeFieldManagerConflict, - Message: `conflict with "foo" using v1 at 2001-02-03T04:05:06Z`, - Field: ".spec.replicas", - }, - }, - }, - Message: `Apply failed with 1 conflict: conflict with "foo" using v1 at 2001-02-03T04:05:06Z: .spec.replicas`, - }, - }, - }, - { - conflict: merge.Conflicts{ - merge.Conflict{ - Manager: `{"manager":"foo","operation":"Update","apiVersion":"v1","time":"2001-02-03T04:05:06Z"}`, - Path: fieldpath.MakePathOrDie("spec", "replicas"), - }, - merge.Conflict{ - Manager: `{"manager":"bar","operation":"Apply"}`, - Path: fieldpath.MakePathOrDie("metadata", "labels", "app"), - }, - }, - expected: &errors.StatusError{ - ErrStatus: metav1.Status{ - Status: metav1.StatusFailure, - Code: http.StatusConflict, - Reason: metav1.StatusReasonConflict, - Details: &metav1.StatusDetails{ - Causes: []metav1.StatusCause{ - { - Type: metav1.CauseTypeFieldManagerConflict, - Message: `conflict with "foo" using v1 at 2001-02-03T04:05:06Z`, - Field: ".spec.replicas", - }, - { - Type: metav1.CauseTypeFieldManagerConflict, - Message: `conflict with "bar"`, - Field: ".metadata.labels.app", - }, - }, - }, - Message: `Apply failed with 2 conflicts: conflicts with "bar": -- .metadata.labels.app -conflicts with "foo" using v1 at 2001-02-03T04:05:06Z: -- .spec.replicas`, - }, - }, - }, - { - conflict: merge.Conflicts{ - merge.Conflict{ - Manager: `{"manager":"foo","operation":"Update","subresource":"scale","apiVersion":"v1","time":"2001-02-03T04:05:06Z"}`, - Path: fieldpath.MakePathOrDie("spec", "replicas"), - }, - }, - expected: &errors.StatusError{ - ErrStatus: metav1.Status{ - Status: metav1.StatusFailure, - Code: http.StatusConflict, - Reason: metav1.StatusReasonConflict, - Details: &metav1.StatusDetails{ - Causes: []metav1.StatusCause{ - { - Type: metav1.CauseTypeFieldManagerConflict, - Message: `conflict with "foo" with subresource "scale" using v1 at 2001-02-03T04:05:06Z`, - Field: ".spec.replicas", - }, - }, - }, - Message: `Apply failed with 1 conflict: conflict with "foo" with subresource "scale" using v1 at 2001-02-03T04:05:06Z: .spec.replicas`, - }, - }, - }, - } - for _, tc := range testCases { - actual := internal.NewConflictError(tc.conflict) - if !reflect.DeepEqual(tc.expected, actual) { - t.Errorf("Expected to get\n%+v\nbut got\n%+v", tc.expected.ErrStatus, actual.ErrStatus) - } - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/fieldmanager.go b/pkg/endpoints/handlers/fieldmanager/internal/fieldmanager.go deleted file mode 100644 index f3111d4bc..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/fieldmanager.go +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright 2022 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 internal - -import ( - "fmt" - "reflect" - "time" - - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/klog/v2" - "sigs.k8s.io/structured-merge-diff/v4/merge" -) - -// DefaultMaxUpdateManagers defines the default maximum retained number of managedFields entries from updates -// if the number of update managers exceeds this, the oldest entries will be merged until the number is below the maximum. -// TODO(jennybuckley): Determine if this is really the best value. Ideally we wouldn't unnecessarily merge too many entries. -const DefaultMaxUpdateManagers int = 10 - -// DefaultTrackOnCreateProbability defines the default probability that the field management of an object -// starts being tracked from the object's creation, instead of from the first time the object is applied to. -const DefaultTrackOnCreateProbability float32 = 1 - -var atMostEverySecond = NewAtMostEvery(time.Second) - -// FieldManager updates the managed fields and merges applied -// configurations. -type FieldManager struct { - fieldManager Manager - subresource string -} - -// NewFieldManager creates a new FieldManager that decodes, manages, then re-encodes managedFields -// on update and apply requests. -func NewFieldManager(f Manager, subresource string) *FieldManager { - return &FieldManager{fieldManager: f, subresource: subresource} -} - -// newDefaultFieldManager is a helper function which wraps a Manager with certain default logic. -func NewDefaultFieldManager(f Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, subresource string) *FieldManager { - return NewFieldManager( - NewLastAppliedUpdater( - NewLastAppliedManager( - NewProbabilisticSkipNonAppliedManager( - NewCapManagersManager( - NewBuildManagerInfoManager( - NewManagedFieldsUpdater( - NewStripMetaManager(f), - ), kind.GroupVersion(), subresource, - ), DefaultMaxUpdateManagers, - ), objectCreater, kind, DefaultTrackOnCreateProbability, - ), typeConverter, objectConverter, kind.GroupVersion()), - ), subresource, - ) -} - -func decodeLiveOrNew(liveObj, newObj runtime.Object, ignoreManagedFieldsFromRequestObject bool) (Managed, error) { - liveAccessor, err := meta.Accessor(liveObj) - if err != nil { - return nil, err - } - - // We take the managedFields of the live object in case the request tries to - // manually set managedFields via a subresource. - if ignoreManagedFieldsFromRequestObject { - return emptyManagedFieldsOnErr(DecodeManagedFields(liveAccessor.GetManagedFields())) - } - - // If the object doesn't have metadata, we should just return without trying to - // set the managedFields at all, so creates/updates/patches will work normally. - newAccessor, err := meta.Accessor(newObj) - if err != nil { - return nil, err - } - - if isResetManagedFields(newAccessor.GetManagedFields()) { - return NewEmptyManaged(), nil - } - - // If the managed field is empty or we failed to decode it, - // let's try the live object. This is to prevent clients who - // don't understand managedFields from deleting it accidentally. - managed, err := DecodeManagedFields(newAccessor.GetManagedFields()) - if err != nil || len(managed.Fields()) == 0 { - return emptyManagedFieldsOnErr(DecodeManagedFields(liveAccessor.GetManagedFields())) - } - return managed, nil -} - -func emptyManagedFieldsOnErr(managed Managed, err error) (Managed, error) { - if err != nil { - return NewEmptyManaged(), nil - } - return managed, nil -} - -// Update is used when the object has already been merged (non-apply -// use-case), and simply updates the managed fields in the output -// object. -func (f *FieldManager) Update(liveObj, newObj runtime.Object, manager string) (object runtime.Object, err error) { - // First try to decode the managed fields provided in the update, - // This is necessary to allow directly updating managed fields. - isSubresource := f.subresource != "" - managed, err := decodeLiveOrNew(liveObj, newObj, isSubresource) - if err != nil { - return newObj, nil - } - - RemoveObjectManagedFields(newObj) - - if object, managed, err = f.fieldManager.Update(liveObj, newObj, managed, manager); err != nil { - return nil, err - } - - if err = EncodeObjectManagedFields(object, managed); err != nil { - return nil, fmt.Errorf("failed to encode managed fields: %v", err) - } - - return object, nil -} - -// UpdateNoErrors is the same as Update, but it will not return -// errors. If an error happens, the object is returned with -// managedFields cleared. -func (f *FieldManager) UpdateNoErrors(liveObj, newObj runtime.Object, manager string) runtime.Object { - obj, err := f.Update(liveObj, newObj, manager) - if err != nil { - atMostEverySecond.Do(func() { - ns, name := "unknown", "unknown" - if accessor, err := meta.Accessor(newObj); err == nil { - ns = accessor.GetNamespace() - name = accessor.GetName() - } - - klog.ErrorS(err, "[SHOULD NOT HAPPEN] failed to update managedFields", "versionKind", - newObj.GetObjectKind().GroupVersionKind(), "namespace", ns, "name", name) - }) - // Explicitly remove managedFields on failure, so that - // we can't have garbage in it. - RemoveObjectManagedFields(newObj) - return newObj - } - return obj -} - -// Returns true if the managedFields indicate that the user is trying to -// reset the managedFields, i.e. if the list is non-nil but empty, or if -// the list has one empty item. -func isResetManagedFields(managedFields []metav1.ManagedFieldsEntry) bool { - if len(managedFields) == 0 { - return managedFields != nil - } - - if len(managedFields) == 1 { - return reflect.DeepEqual(managedFields[0], metav1.ManagedFieldsEntry{}) - } - - return false -} - -// Apply is used when server-side apply is called, as it merges the -// object and updates the managed fields. -func (f *FieldManager) Apply(liveObj, appliedObj runtime.Object, manager string, force bool) (object runtime.Object, err error) { - // If the object doesn't have metadata, apply isn't allowed. - accessor, err := meta.Accessor(liveObj) - if err != nil { - return nil, fmt.Errorf("couldn't get accessor: %v", err) - } - - // Decode the managed fields in the live object, since it isn't allowed in the patch. - managed, err := DecodeManagedFields(accessor.GetManagedFields()) - if err != nil { - return nil, fmt.Errorf("failed to decode managed fields: %v", err) - } - - object, managed, err = f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force) - if err != nil { - if conflicts, ok := err.(merge.Conflicts); ok { - return nil, NewConflictError(conflicts) - } - return nil, err - } - - if err = EncodeObjectManagedFields(object, managed); err != nil { - return nil, fmt.Errorf("failed to encode managed fields: %v", err) - } - - return object, nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/fieldmanager_test.go b/pkg/endpoints/handlers/fieldmanager/internal/fieldmanager_test.go deleted file mode 100644 index b51f5b5ef..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/fieldmanager_test.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2019 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 internal_test - -import ( - "encoding/json" - "io/ioutil" - "path/filepath" - "strings" - - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "k8s.io/kube-openapi/pkg/validation/spec" -) - -var fakeTypeConverter = func() internal.TypeConverter { - data, err := ioutil.ReadFile(filepath.Join( - strings.Repeat(".."+string(filepath.Separator), 9), - "api", "openapi-spec", "swagger.json")) - if err != nil { - panic(err) - } - convertedDefs := map[string]*spec.Schema{} - spec := spec.Swagger{} - if err := json.Unmarshal(data, &spec); err != nil { - panic(err) - } - - for k, v := range spec.Definitions { - vCopy := v - convertedDefs[k] = &vCopy - } - - typeConverter, err := internal.NewTypeConverter(convertedDefs, false) - if err != nil { - panic(err) - } - return typeConverter -}() diff --git a/pkg/endpoints/handlers/fieldmanager/internal/fields.go b/pkg/endpoints/handlers/fieldmanager/internal/fields.go deleted file mode 100644 index 08186191a..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/fields.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "bytes" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -// EmptyFields represents a set with no paths -// It looks like metav1.Fields{Raw: []byte("{}")} -var EmptyFields = func() metav1.FieldsV1 { - f, err := SetToFields(*fieldpath.NewSet()) - if err != nil { - panic("should never happen") - } - return f -}() - -// FieldsToSet creates a set paths from an input trie of fields -func FieldsToSet(f metav1.FieldsV1) (s fieldpath.Set, err error) { - err = s.FromJSON(bytes.NewReader(f.Raw)) - return s, err -} - -// SetToFields creates a trie of fields from an input set of paths -func SetToFields(s fieldpath.Set) (f metav1.FieldsV1, err error) { - f.Raw, err = s.ToJSON() - return f, err -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/fields_test.go b/pkg/endpoints/handlers/fieldmanager/internal/fields_test.go deleted file mode 100644 index 57727f331..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/fields_test.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "reflect" - "strings" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -// TestFieldsRoundTrip tests that a fields trie can be round tripped as a path set -func TestFieldsRoundTrip(t *testing.T) { - tests := []metav1.FieldsV1{ - { - Raw: []byte(`{"f:metadata":{".":{},"f:name":{}}}`), - }, - EmptyFields, - } - - for _, test := range tests { - set, err := FieldsToSet(test) - if err != nil { - t.Fatalf("Failed to create path set: %v", err) - } - output, err := SetToFields(set) - if err != nil { - t.Fatalf("Failed to create fields trie from path set: %v", err) - } - if !reflect.DeepEqual(test, output) { - t.Fatalf("Expected round-trip:\ninput: %v\noutput: %v", test, output) - } - } -} - -// TestFieldsToSetError tests that errors are picked up by FieldsToSet -func TestFieldsToSetError(t *testing.T) { - tests := []struct { - fields metav1.FieldsV1 - errString string - }{ - { - fields: metav1.FieldsV1{ - Raw: []byte(`{"k:{invalid json}":{"f:name":{},".":{}}}`), - }, - errString: "ReadObjectCB", - }, - } - - for _, test := range tests { - _, err := FieldsToSet(test.fields) - if err == nil || !strings.Contains(err.Error(), test.errString) { - t.Fatalf("Expected error to contain %q but got: %v", test.errString, err) - } - } -} - -// TestSetToFieldsError tests that errors are picked up by SetToFields -func TestSetToFieldsError(t *testing.T) { - validName := "ok" - invalidPath := fieldpath.Path([]fieldpath.PathElement{{}, {FieldName: &validName}}) - - tests := []struct { - set fieldpath.Set - errString string - }{ - { - set: *fieldpath.NewSet(invalidPath), - errString: "invalid PathElement", - }, - } - - for _, test := range tests { - _, err := SetToFields(test.set) - if err == nil || !strings.Contains(err.Error(), test.errString) { - t.Fatalf("Expected error to contain %q but got: %v", test.errString, err) - } - } -} - -func BenchmarkSetToFields(b *testing.B) { - set := fieldpath.NewSet( - fieldpath.MakePathOrDie("foo", 0, "bar", "baz"), - fieldpath.MakePathOrDie("foo", 0, "bar", "zot"), - fieldpath.MakePathOrDie("foo", 0, "bar"), - fieldpath.MakePathOrDie("foo", 0), - fieldpath.MakePathOrDie("foo", 1, "bar", "baz"), - fieldpath.MakePathOrDie("foo", 1, "bar"), - fieldpath.MakePathOrDie("qux", fieldpath.KeyByFields("name", "first")), - fieldpath.MakePathOrDie("qux", fieldpath.KeyByFields("name", "first"), "bar"), - fieldpath.MakePathOrDie("qux", fieldpath.KeyByFields("name", "second"), "bar"), - ) - - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - _, err := SetToFields(*set) - if err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkFieldsToSet(b *testing.B) { - set := fieldpath.NewSet( - fieldpath.MakePathOrDie("foo", 0, "bar", "baz"), - fieldpath.MakePathOrDie("foo", 0, "bar", "zot"), - fieldpath.MakePathOrDie("foo", 0, "bar"), - fieldpath.MakePathOrDie("foo", 0), - fieldpath.MakePathOrDie("foo", 1, "bar", "baz"), - fieldpath.MakePathOrDie("foo", 1, "bar"), - fieldpath.MakePathOrDie("qux", fieldpath.KeyByFields("name", "first")), - fieldpath.MakePathOrDie("qux", fieldpath.KeyByFields("name", "first"), "bar"), - fieldpath.MakePathOrDie("qux", fieldpath.KeyByFields("name", "second"), "bar"), - ) - fields, err := SetToFields(*set) - if err != nil { - b.Fatal(err) - } - b.ReportAllocs() - b.ResetTimer() - for n := 0; n < b.N; n++ { - _, err := FieldsToSet(fields) - if err != nil { - b.Fatal(err) - } - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/lastapplied.go b/pkg/endpoints/handlers/fieldmanager/internal/lastapplied.go deleted file mode 100644 index b00b6b829..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/lastapplied.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2022 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 internal - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/api/meta" - apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation" - "k8s.io/apimachinery/pkg/runtime" -) - -// LastAppliedConfigAnnotation is the annotation used to store the previous -// configuration of a resource for use in a three way diff by UpdateApplyAnnotation. -// -// This is a copy of the corev1 annotation since we don't want to depend on the whole package. -const LastAppliedConfigAnnotation = "kubectl.kubernetes.io/last-applied-configuration" - -// SetLastApplied sets the last-applied annotation the given value in -// the object. -func SetLastApplied(obj runtime.Object, value string) error { - accessor, err := meta.Accessor(obj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - var annotations = accessor.GetAnnotations() - if annotations == nil { - annotations = map[string]string{} - } - annotations[LastAppliedConfigAnnotation] = value - if err := apimachineryvalidation.ValidateAnnotationsSize(annotations); err != nil { - delete(annotations, LastAppliedConfigAnnotation) - } - accessor.SetAnnotations(annotations) - return nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedmanager.go b/pkg/endpoints/handlers/fieldmanager/internal/lastappliedmanager.go deleted file mode 100644 index 3f6cf8821..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedmanager.go +++ /dev/null @@ -1,171 +0,0 @@ -/* -Copyright 2020 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 internal - -import ( - "encoding/json" - "fmt" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" -) - -type lastAppliedManager struct { - fieldManager Manager - typeConverter TypeConverter - objectConverter runtime.ObjectConvertor - groupVersion schema.GroupVersion -} - -var _ Manager = &lastAppliedManager{} - -// NewLastAppliedManager converts the client-side apply annotation to -// server-side apply managed fields -func NewLastAppliedManager(fieldManager Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, groupVersion schema.GroupVersion) Manager { - return &lastAppliedManager{ - fieldManager: fieldManager, - typeConverter: typeConverter, - objectConverter: objectConverter, - groupVersion: groupVersion, - } -} - -// Update implements Manager. -func (f *lastAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - return f.fieldManager.Update(liveObj, newObj, managed, manager) -} - -// Apply will consider the last-applied annotation -// for upgrading an object managed by client-side apply to server-side apply -// without conflicts. -func (f *lastAppliedManager) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { - newLiveObj, newManaged, newErr := f.fieldManager.Apply(liveObj, newObj, managed, manager, force) - // Upgrade the client-side apply annotation only from kubectl server-side-apply. - // To opt-out of this behavior, users may specify a different field manager. - if manager != "kubectl" { - return newLiveObj, newManaged, newErr - } - - // Check if we have conflicts - if newErr == nil { - return newLiveObj, newManaged, newErr - } - conflicts, ok := newErr.(merge.Conflicts) - if !ok { - return newLiveObj, newManaged, newErr - } - conflictSet := conflictsToSet(conflicts) - - // Check if conflicts are allowed due to client-side apply, - // and if so, then force apply - allowedConflictSet, err := f.allowedConflictsFromLastApplied(liveObj) - if err != nil { - return newLiveObj, newManaged, newErr - } - if !conflictSet.Difference(allowedConflictSet).Empty() { - newConflicts := conflictsDifference(conflicts, allowedConflictSet) - return newLiveObj, newManaged, newConflicts - } - - return f.fieldManager.Apply(liveObj, newObj, managed, manager, true) -} - -func (f *lastAppliedManager) allowedConflictsFromLastApplied(liveObj runtime.Object) (*fieldpath.Set, error) { - var accessor, err = meta.Accessor(liveObj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - - // If there is no client-side apply annotation, then there is nothing to do - var annotations = accessor.GetAnnotations() - if annotations == nil { - return nil, fmt.Errorf("no last applied annotation") - } - var lastApplied, ok = annotations[LastAppliedConfigAnnotation] - if !ok || lastApplied == "" { - return nil, fmt.Errorf("no last applied annotation") - } - - liveObjVersioned, err := f.objectConverter.ConvertToVersion(liveObj, f.groupVersion) - if err != nil { - return nil, fmt.Errorf("failed to convert live obj to versioned: %v", err) - } - - liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned) - if err != nil { - return nil, fmt.Errorf("failed to convert live obj to typed: %v", err) - } - - var lastAppliedObj = &unstructured.Unstructured{Object: map[string]interface{}{}} - err = json.Unmarshal([]byte(lastApplied), lastAppliedObj) - if err != nil { - return nil, fmt.Errorf("failed to decode last applied obj: %v in '%s'", err, lastApplied) - } - - if lastAppliedObj.GetAPIVersion() != f.groupVersion.String() { - return nil, fmt.Errorf("expected version of last applied to match live object '%s', but got '%s': %v", f.groupVersion.String(), lastAppliedObj.GetAPIVersion(), err) - } - - lastAppliedObjTyped, err := f.typeConverter.ObjectToTyped(lastAppliedObj) - if err != nil { - return nil, fmt.Errorf("failed to convert last applied to typed: %v", err) - } - - lastAppliedObjFieldSet, err := lastAppliedObjTyped.ToFieldSet() - if err != nil { - return nil, fmt.Errorf("failed to create fieldset for last applied object: %v", err) - } - - comparison, err := lastAppliedObjTyped.Compare(liveObjTyped) - if err != nil { - return nil, fmt.Errorf("failed to compare last applied object and live object: %v", err) - } - - // Remove fields in last applied that are different, added, or missing in - // the live object. - // Because last-applied fields don't match the live object fields, - // then we don't own these fields. - lastAppliedObjFieldSet = lastAppliedObjFieldSet. - Difference(comparison.Modified). - Difference(comparison.Added). - Difference(comparison.Removed) - - return lastAppliedObjFieldSet, nil -} - -// TODO: replace with merge.Conflicts.ToSet() -func conflictsToSet(conflicts merge.Conflicts) *fieldpath.Set { - conflictSet := fieldpath.NewSet() - for _, conflict := range []merge.Conflict(conflicts) { - conflictSet.Insert(conflict.Path) - } - return conflictSet -} - -func conflictsDifference(conflicts merge.Conflicts, s *fieldpath.Set) merge.Conflicts { - newConflicts := []merge.Conflict{} - for _, conflict := range []merge.Conflict(conflicts) { - if !s.Has(conflict.Path) { - newConflicts = append(newConflicts, conflict) - } - } - return newConflicts -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedmanager_test.go b/pkg/endpoints/handlers/fieldmanager/internal/lastappliedmanager_test.go deleted file mode 100644 index e3460ca42..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedmanager_test.go +++ /dev/null @@ -1,1007 +0,0 @@ -/* -Copyright 2020 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 internal_test - -import ( - "fmt" - "reflect" - "testing" - - apiequality "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - yamlutil "k8s.io/apimachinery/pkg/util/yaml" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanagertest" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" - "sigs.k8s.io/yaml" -) - -type testArgs struct { - lastApplied []byte - original []byte - applied []byte - fieldManager string - expectConflictSet *fieldpath.Set -} - -// TestApplyUsingLastAppliedAnnotation tests that applying to an object -// created with the client-side apply last-applied annotation -// will not give conflicts -func TestApplyUsingLastAppliedAnnotation(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment")) - - tests := []testArgs{ - { - fieldManager: "kubectl", - lastApplied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image-v1 - - name: my-c2 - image: my-image2 -`), - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app # missing from last-applied -spec: - replicas: 100 # does not match last-applied - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image-v2 # does no match last-applied - # note that second container in last-applied is missing -`), - applied: []byte(` -# test conflicts due to fields not allowed by last-applied - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-new-label # NOT allowed: update label -spec: - replicas: 333 # NOT allowed: update replicas - selector: - matchLabels: - app: my-new-label # allowed: update label - template: - metadata: - labels: - app: my-new-label # allowed: update-label - spec: - containers: - - name: my-c - image: my-image-new # NOT allowed: update image -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("metadata", "labels", "app"), - fieldpath.MakePathOrDie("spec", "replicas"), - fieldpath.MakePathOrDie("spec", "template", "spec", "containers", fieldpath.KeyByFields("name", "my-c"), "image"), - ), - }, - { - fieldManager: "kubectl", - lastApplied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 # does not match last applied - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - applied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-new-label -spec: - replicas: 3 # expect conflict - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "replicas"), - ), - }, - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - applied: []byte(` -# applied object matches original - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - }, - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - applied: []byte(` -# test allowed update with no conflicts - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-new-label # update label -spec: - replicas: 333 # update replicas - selector: - matchLabels: - app: my-new-label # update label - template: - metadata: - labels: - app: my-new-label # update-label - spec: - containers: - - name: my-c - image: my-image -`), - }, - { - fieldManager: "not_kubectl", - lastApplied: []byte(` -# expect conflicts because field manager is NOT kubectl - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image-v1 -`), - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 # does not match last-applied - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image-v2 # does no match last-applied -`), - applied: []byte(` -# test conflicts due to fields not allowed by last-applied - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-new-label # update label -spec: - replicas: 333 # update replicas - selector: - matchLabels: - app: my-new-label # update label - template: - metadata: - labels: - app: my-new-label # update-label - spec: - containers: - - name: my-c - image: my-image-new # update image -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("metadata", "labels", "app"), - fieldpath.MakePathOrDie("spec", "replicas"), - fieldpath.MakePathOrDie("spec", "selector"), // selector is atomic - fieldpath.MakePathOrDie("spec", "template", "metadata", "labels", "app"), - fieldpath.MakePathOrDie("spec", "template", "spec", "containers", fieldpath.KeyByFields("name", "my-c"), "image"), - ), - }, - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - applied: []byte(` -# test allowed update with no conflicts - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-new-label -spec: - replicas: 3 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-new-image # update image -`), - }, - { - fieldManager: "not_kubectl", - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-app -spec: - replicas: 100 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`), - applied: []byte(` - -# expect changes to fail because field manager is not kubectl - -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - labels: - app: my-new-label # update label -spec: - replicas: 3 # update replicas - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-new-image # update image -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("metadata", "labels", "app"), - fieldpath.MakePathOrDie("spec", "replicas"), - fieldpath.MakePathOrDie("spec", "template", "spec", "containers", fieldpath.KeyByFields("name", "my-c"), "image"), - ), - }, - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 3 -`), - applied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 100 # update replicas -`), - }, - { - fieldManager: "kubectl", - lastApplied: []byte(` -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 3 -`), - original: []byte(` -apiVersion: apps/v1 # expect conflict due to apiVersion mismatch with last-applied -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 3 -`), - applied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 100 # update replicas -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "replicas"), - ), - }, - { - fieldManager: "kubectl", - lastApplied: []byte(` -apiVerison: foo -kind: bar -spec: expect conflict due to invalid object -`), - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 3 -`), - applied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 100 # update replicas -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "replicas"), - ), - }, - { - fieldManager: "kubectl", - // last-applied is empty - lastApplied: []byte{}, - original: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 3 -`), - applied: []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment -spec: - replicas: 100 # update replicas -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "replicas"), - ), - }, - } - - testConflicts(t, f, tests) -} - -func TestServiceApply(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Service")) - - tests := []testArgs{ - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: v1 -kind: Service -metadata: - name: test -spec: - ports: - - name: https - port: 443 - protocol: TCP - targetPort: 8443 - selector: - old: test -`), - applied: []byte(` -# All accepted while using the same field manager - -apiVersion: v1 -kind: Service -metadata: - name: test -spec: - ports: - - name: https - port: 443 - protocol: TCP - targetPort: 8444 - selector: - new: test -`), - }, - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: v1 -kind: Service -metadata: - name: test -spec: - ports: - - name: https - port: 443 - protocol: TCP - targetPort: 8443 - selector: - old: test -`), - applied: []byte(` -# Allowed to remove selectors while using the same field manager - -apiVersion: v1 -kind: Service -metadata: - name: test -spec: - ports: - - name: https - port: 443 - protocol: TCP - targetPort: 8444 - selector: {} -`), - }, - { - fieldManager: "not_kubectl", - original: []byte(` -apiVersion: v1 -kind: Service -metadata: - name: test -spec: - ports: - - name: https - port: 443 - protocol: TCP # TODO: issue - this is a defaulted field, should not be required in a new spec - targetPort: 8443 - selector: - old: test -`), - applied: []byte(` -# test selector update not allowed by last-applied - -apiVersion: v1 -kind: Service -metadata: - name: test -spec: - ports: - - name: https - port: 443 - protocol: TCP - targetPort: 8444 - selector: - new: test -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "selector"), // selector is atomic - fieldpath.MakePathOrDie("spec", "ports", fieldpath.KeyByFields("port", 443, "protocol", "TCP"), "targetPort"), - ), - }, - } - - testConflicts(t, f, tests) -} - -func TestReplicationControllerApply(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ReplicationController")) - - tests := []testArgs{ - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: v1 -kind: ReplicationController -metadata: - name: test -spec: - replicas: 0 - selector: - old: test -`), - applied: []byte(` -# All accepted while using the same field manager - -apiVersion: v1 -kind: ReplicationController -metadata: - name: test -spec: - replicas: 3 - selector: - new: test -`), - }, - { - fieldManager: "not_kubectl", - original: []byte(` -apiVersion: v1 -kind: ReplicationController -metadata: - name: test -spec: - replicas: 0 - selector: - old: test -`), - applied: []byte(` -# test selector update not allowed by last-applied - -apiVersion: v1 -kind: ReplicationController -metadata: - name: test -spec: - replicas: 3 - selector: - new: test -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "selector"), // selector is atomic - fieldpath.MakePathOrDie("spec", "replicas"), - ), - }, - } - - testConflicts(t, f, tests) -} - -func TestPodApply(t *testing.T) { - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod")) - - tests := []testArgs{ - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: definetlyControlPlane - nodeSelector: - node-role.kubernetes.io/master: "" -`), - applied: []byte(` -# All accepted while using the same field manager - -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeSelector: - node-role.kubernetes.io/worker: "" -`), - }, - { - fieldManager: "not_kubectl", - original: []byte(` -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: definetlyControlPlane - nodeSelector: - node-role.kubernetes.io/master: "" -`), - applied: []byte(` -# test selector update not allowed by last-applied - -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: definetlyControlPlane - nodeSelector: - node-role.kubernetes.io/master: "" - otherNodeType: "" -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "nodeSelector"), // selector is atomic - ), - }, - { - fieldManager: "not_kubectl", - original: []byte(` -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: definetlyControlPlane - nodeSelector: - node-role.kubernetes.io/master: "" -`), - applied: []byte(` -# purging selector not allowed for different manager - -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: another - nodeSelector: {} -`), - expectConflictSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("spec", "nodeSelector"), // selector is atomic - fieldpath.MakePathOrDie("spec", "nodeName"), - ), - }, - { - fieldManager: "kubectl", - original: []byte(` -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: definetlyControlPlane - nodeSelector: - node-role.kubernetes.io/master: "" -`), - applied: []byte(` -# same manager could purge nodeSelector - -apiVersion: v1 -kind: Pod -metadata: - name: test - namespace: test -spec: - containers: - - args: - - -v=2 - command: - - controller - image: some.registry/app:latest - name: doJob - nodeName: another - nodeSelector: {} -`), - }, - } - - testConflicts(t, f, tests) -} - -func testConflicts(t *testing.T, f fieldmanagertest.TestFieldManager, tests []testArgs) { - for i, test := range tests { - t.Run(fmt.Sprintf("test %d", i), func(t *testing.T) { - f.Reset() - - originalObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(test.original, &originalObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - - if test.lastApplied == nil { - test.lastApplied = test.original - } - if err := setLastAppliedFromEncoded(originalObj, test.lastApplied); err != nil { - t.Errorf("failed to set last applied: %v", err) - } - - if err := f.Update(originalObj, "test_client_side_apply"); err != nil { - t.Errorf("failed to apply object: %v", err) - } - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(test.applied, &appliedObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - - err := f.Apply(appliedObj, test.fieldManager, false) - - if test.expectConflictSet == nil { - if err != nil { - t.Errorf("expected no error but got %v", err) - } - } else { - if err == nil || !apierrors.IsConflict(err) { - t.Errorf("expected to get conflicts but got %v", err) - } - - expectedConflicts := merge.Conflicts{} - test.expectConflictSet.Iterate(func(p fieldpath.Path) { - expectedConflicts = append(expectedConflicts, merge.Conflict{ - Manager: fmt.Sprintf(`{"manager":"test_client_side_apply","operation":"Update","apiVersion":"%s"}`, f.APIVersion()), - Path: p, - }) - }) - expectedConflictErr := internal.NewConflictError(expectedConflicts) - if !reflect.DeepEqual(expectedConflictErr, err) { - t.Errorf("expected to get\n%+v\nbut got\n%+v", expectedConflictErr, err) - } - - // Yet force should resolve all conflicts - err = f.Apply(appliedObj, test.fieldManager, true) - if err != nil { - t.Errorf("unexpected error during force ownership apply: %v", err) - } - - } - - // Eventually resource should contain applied changes - if !apiequality.Semantic.DeepDerivative(appliedObj, f.Live()) { - t.Errorf("expected equal resource: \n%#v, got: \n%#v", appliedObj, f.Live()) - } - }) - } -} - -func yamlToJSON(y []byte) (string, error) { - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(y, &obj.Object); err != nil { - return "", fmt.Errorf("error decoding YAML: %v", err) - } - serialization, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj) - if err != nil { - return "", fmt.Errorf("error encoding object: %v", err) - } - json, err := yamlutil.ToJSON(serialization) - if err != nil { - return "", fmt.Errorf("error converting to json: %v", err) - } - return string(json), nil -} - -func setLastAppliedFromEncoded(obj runtime.Object, lastApplied []byte) error { - lastAppliedJSON, err := yamlToJSON(lastApplied) - if err != nil { - return err - } - return internal.SetLastApplied(obj, lastAppliedJSON) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedupdater.go b/pkg/endpoints/handlers/fieldmanager/internal/lastappliedupdater.go deleted file mode 100644 index 06e6c5d8c..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedupdater.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright 2020 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 internal - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" -) - -type lastAppliedUpdater struct { - fieldManager Manager -} - -var _ Manager = &lastAppliedUpdater{} - -// NewLastAppliedUpdater sets the client-side apply annotation up to date with -// server-side apply managed fields -func NewLastAppliedUpdater(fieldManager Manager) Manager { - return &lastAppliedUpdater{ - fieldManager: fieldManager, - } -} - -// Update implements Manager. -func (f *lastAppliedUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - return f.fieldManager.Update(liveObj, newObj, managed, manager) -} - -// server-side apply managed fields -func (f *lastAppliedUpdater) Apply(liveObj, newObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { - liveObj, managed, err := f.fieldManager.Apply(liveObj, newObj, managed, manager, force) - if err != nil { - return liveObj, managed, err - } - - // Sync the client-side apply annotation only from kubectl server-side apply. - // To opt-out of this behavior, users may specify a different field manager. - // - // If the client-side apply annotation doesn't exist, - // then continue because we have no annotation to update - if manager == "kubectl" && hasLastApplied(liveObj) { - lastAppliedValue, err := buildLastApplied(newObj) - if err != nil { - return nil, nil, fmt.Errorf("failed to build last-applied annotation: %v", err) - } - err = SetLastApplied(liveObj, lastAppliedValue) - if err != nil { - return nil, nil, fmt.Errorf("failed to set last-applied annotation: %v", err) - } - } - return liveObj, managed, err -} - -func hasLastApplied(obj runtime.Object) bool { - var accessor, err = meta.Accessor(obj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - var annotations = accessor.GetAnnotations() - if annotations == nil { - return false - } - lastApplied, ok := annotations[LastAppliedConfigAnnotation] - return ok && len(lastApplied) > 0 -} - -func buildLastApplied(obj runtime.Object) (string, error) { - obj = obj.DeepCopyObject() - - var accessor, err = meta.Accessor(obj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - - // Remove the annotation from the object before encoding the object - var annotations = accessor.GetAnnotations() - delete(annotations, LastAppliedConfigAnnotation) - accessor.SetAnnotations(annotations) - - lastApplied, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj) - if err != nil { - return "", fmt.Errorf("couldn't encode object into last applied annotation: %v", err) - } - return string(lastApplied), nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedupdater_test.go b/pkg/endpoints/handlers/fieldmanager/internal/lastappliedupdater_test.go deleted file mode 100644 index d4870634e..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/lastappliedupdater_test.go +++ /dev/null @@ -1,268 +0,0 @@ -/* -Copyright 2020 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 internal_test - -import ( - "encoding/json" - "fmt" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - internaltesting "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal/testing" - "sigs.k8s.io/yaml" -) - -func TestLastAppliedUpdater(t *testing.T) { - f := internaltesting.NewTestFieldManagerImpl(fakeTypeConverter, schema.FromAPIVersionAndKind("apps/v1", "Deployment"), - "", - func(m internal.Manager) internal.Manager { - return internal.NewLastAppliedUpdater(m) - }) - - originalLastApplied := `nonempty` - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - appliedDeployment := []byte(` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: my-deployment - annotations: - "kubectl.kubernetes.io/last-applied-configuration": "` + originalLastApplied + `" - labels: - app: my-app -spec: - replicas: 20 - selector: - matchLabels: - app: my-app - template: - metadata: - labels: - app: my-app - spec: - containers: - - name: my-c - image: my-image -`) - if err := yaml.Unmarshal(appliedDeployment, &appliedObj.Object); err != nil { - t.Errorf("error decoding YAML: %v", err) - } - - if err := f.Apply(appliedObj, "NOT-KUBECTL", false); err != nil { - t.Errorf("error applying object: %v", err) - } - - lastApplied, err := getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - - if lastApplied != originalLastApplied { - t.Errorf("expected last applied annotation to be %q and NOT be updated, but got: %q", originalLastApplied, lastApplied) - } - - if err := f.Apply(appliedObj, "kubectl", false); err != nil { - t.Errorf("error applying object: %v", err) - } - - lastApplied, err = getLastApplied(f.Live()) - if err != nil { - t.Errorf("failed to get last applied: %v", err) - } - - if lastApplied == originalLastApplied || - !strings.Contains(lastApplied, "my-app") || - !strings.Contains(lastApplied, "my-image") { - t.Errorf("expected last applied annotation to be updated, but got: %q", lastApplied) - } -} - -func TestLargeLastApplied(t *testing.T) { - tests := []struct { - name string - oldObject *unstructured.Unstructured - newObject *unstructured.Unstructured - }{ - { - name: "old object + new object last-applied annotation is too big", - oldObject: func() *unstructured.Unstructured { - u := &unstructured.Unstructured{} - err := json.Unmarshal([]byte(` -{ - "metadata": { - "name": "large-update-test-cm", - "namespace": "default", - "annotations": { - "kubectl.kubernetes.io/last-applied-configuration": "nonempty" - } - }, - "apiVersion": "v1", - "kind": "ConfigMap", - "data": { - "k": "v" - } -}`), &u) - if err != nil { - panic(err) - } - return u - }(), - newObject: func() *unstructured.Unstructured { - u := &unstructured.Unstructured{} - err := json.Unmarshal([]byte(` -{ - "metadata": { - "name": "large-update-test-cm", - "namespace": "default", - "annotations": { - "kubectl.kubernetes.io/last-applied-configuration": "nonempty" - } - }, - "apiVersion": "v1", - "kind": "ConfigMap", - "data": { - "k": "v" - } -}`), &u) - if err != nil { - panic(err) - } - for i := 0; i < 9999; i++ { - unique := fmt.Sprintf("this-key-is-very-long-so-as-to-create-a-very-large-serialized-fieldset-%v", i) - unstructured.SetNestedField(u.Object, "A", "data", unique) - } - return u - }(), - }, - { - name: "old object + new object annotations + new object last-applied annotation is too big", - oldObject: func() *unstructured.Unstructured { - u := &unstructured.Unstructured{} - err := json.Unmarshal([]byte(` -{ - "metadata": { - "name": "large-update-test-cm", - "namespace": "default", - "annotations": { - "kubectl.kubernetes.io/last-applied-configuration": "nonempty" - } - }, - "apiVersion": "v1", - "kind": "ConfigMap", - "data": { - "k": "v" - } -}`), &u) - if err != nil { - panic(err) - } - for i := 0; i < 2000; i++ { - unique := fmt.Sprintf("this-key-is-very-long-so-as-to-create-a-very-large-serialized-fieldset-%v", i) - unstructured.SetNestedField(u.Object, "A", "data", unique) - } - return u - }(), - newObject: func() *unstructured.Unstructured { - u := &unstructured.Unstructured{} - err := json.Unmarshal([]byte(` -{ - "metadata": { - "name": "large-update-test-cm", - "namespace": "default", - "annotations": { - "kubectl.kubernetes.io/last-applied-configuration": "nonempty" - } - }, - "apiVersion": "v1", - "kind": "ConfigMap", - "data": { - "k": "v" - } -}`), &u) - if err != nil { - panic(err) - } - for i := 0; i < 2000; i++ { - unique := fmt.Sprintf("this-key-is-very-long-so-as-to-create-a-very-large-serialized-fieldset-%v", i) - unstructured.SetNestedField(u.Object, "A", "data", unique) - unstructured.SetNestedField(u.Object, "A", "metadata", "annotations", unique) - } - return u - }(), - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - f := internaltesting.NewTestFieldManagerImpl(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap"), - "", - func(m internal.Manager) internal.Manager { - return internal.NewLastAppliedUpdater(m) - }) - - if err := f.Apply(test.oldObject, "kubectl", false); err != nil { - t.Errorf("Error applying object: %v", err) - } - - lastApplied, err := getLastApplied(f.Live()) - if err != nil { - t.Errorf("Failed to access last applied annotation: %v", err) - } - if len(lastApplied) == 0 || lastApplied == "nonempty" { - t.Errorf("Expected an updated last-applied annotation, but got: %q", lastApplied) - } - - if err := f.Apply(test.newObject, "kubectl", false); err != nil { - t.Errorf("Error applying object: %v", err) - } - - accessor := meta.NewAccessor() - annotations, err := accessor.Annotations(f.Live()) - if err != nil { - t.Errorf("Failed to access annotations: %v", err) - } - if annotations == nil { - t.Errorf("No annotations on obj: %v", f.Live()) - } - lastApplied, ok := annotations[internal.LastAppliedConfigAnnotation] - if ok || len(lastApplied) > 0 { - t.Errorf("Expected no last applied annotation, but got last applied with length: %d", len(lastApplied)) - } - }) - } -} - -func getLastApplied(obj runtime.Object) (string, error) { - accessor := meta.NewAccessor() - annotations, err := accessor.Annotations(obj) - if err != nil { - return "", fmt.Errorf("failed to access annotations: %v", err) - } - if annotations == nil { - return "", fmt.Errorf("no annotations on obj: %v", obj) - } - - lastApplied, ok := annotations[internal.LastAppliedConfigAnnotation] - if !ok { - return "", fmt.Errorf("expected last applied annotation, but got none for object: %v", obj) - } - return lastApplied, nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/managedfields.go b/pkg/endpoints/handlers/fieldmanager/internal/managedfields.go deleted file mode 100644 index 9b4c20326..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/managedfields.go +++ /dev/null @@ -1,248 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "encoding/json" - "fmt" - "sort" - - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -// ManagedInterface groups a fieldpath.ManagedFields together with the timestamps associated with each operation. -type ManagedInterface interface { - // Fields gets the fieldpath.ManagedFields. - Fields() fieldpath.ManagedFields - - // Times gets the timestamps associated with each operation. - Times() map[string]*metav1.Time -} - -type managedStruct struct { - fields fieldpath.ManagedFields - times map[string]*metav1.Time -} - -var _ ManagedInterface = &managedStruct{} - -// Fields implements ManagedInterface. -func (m *managedStruct) Fields() fieldpath.ManagedFields { - return m.fields -} - -// Times implements ManagedInterface. -func (m *managedStruct) Times() map[string]*metav1.Time { - return m.times -} - -// NewEmptyManaged creates an empty ManagedInterface. -func NewEmptyManaged() ManagedInterface { - return NewManaged(fieldpath.ManagedFields{}, map[string]*metav1.Time{}) -} - -// NewManaged creates a ManagedInterface from a fieldpath.ManagedFields and the timestamps associated with each operation. -func NewManaged(f fieldpath.ManagedFields, t map[string]*metav1.Time) ManagedInterface { - return &managedStruct{ - fields: f, - times: t, - } -} - -// RemoveObjectManagedFields removes the ManagedFields from the object -// before we merge so that it doesn't appear in the ManagedFields -// recursively. -func RemoveObjectManagedFields(obj runtime.Object) { - accessor, err := meta.Accessor(obj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - accessor.SetManagedFields(nil) -} - -// EncodeObjectManagedFields converts and stores the fieldpathManagedFields into the objects ManagedFields -func EncodeObjectManagedFields(obj runtime.Object, managed ManagedInterface) error { - accessor, err := meta.Accessor(obj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - - encodedManagedFields, err := encodeManagedFields(managed) - if err != nil { - return fmt.Errorf("failed to convert back managed fields to API: %v", err) - } - accessor.SetManagedFields(encodedManagedFields) - - return nil -} - -// DecodeManagedFields converts ManagedFields from the wire format (api format) -// to the format used by sigs.k8s.io/structured-merge-diff -func DecodeManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (ManagedInterface, error) { - managed := managedStruct{} - managed.fields = make(fieldpath.ManagedFields, len(encodedManagedFields)) - managed.times = make(map[string]*metav1.Time, len(encodedManagedFields)) - - for i, encodedVersionedSet := range encodedManagedFields { - switch encodedVersionedSet.Operation { - case metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate: - default: - return nil, fmt.Errorf("operation must be `Apply` or `Update`") - } - if len(encodedVersionedSet.APIVersion) < 1 { - return nil, fmt.Errorf("apiVersion must not be empty") - } - switch encodedVersionedSet.FieldsType { - case "FieldsV1": - // Valid case. - case "": - return nil, fmt.Errorf("missing fieldsType in managed fields entry %d", i) - default: - return nil, fmt.Errorf("invalid fieldsType %q in managed fields entry %d", encodedVersionedSet.FieldsType, i) - } - manager, err := BuildManagerIdentifier(&encodedVersionedSet) - if err != nil { - return nil, fmt.Errorf("error decoding manager from %v: %v", encodedVersionedSet, err) - } - managed.fields[manager], err = decodeVersionedSet(&encodedVersionedSet) - if err != nil { - return nil, fmt.Errorf("error decoding versioned set from %v: %v", encodedVersionedSet, err) - } - managed.times[manager] = encodedVersionedSet.Time - } - return &managed, nil -} - -// BuildManagerIdentifier creates a manager identifier string from a ManagedFieldsEntry -func BuildManagerIdentifier(encodedManager *metav1.ManagedFieldsEntry) (manager string, err error) { - encodedManagerCopy := *encodedManager - - // Never include fields type in the manager identifier - encodedManagerCopy.FieldsType = "" - - // Never include the fields in the manager identifier - encodedManagerCopy.FieldsV1 = nil - - // Never include the time in the manager identifier - encodedManagerCopy.Time = nil - - // For appliers, don't include the APIVersion in the manager identifier, - // so it will always have the same manager identifier each time it applied. - if encodedManager.Operation == metav1.ManagedFieldsOperationApply { - encodedManagerCopy.APIVersion = "" - } - - // Use the remaining fields to build the manager identifier - b, err := json.Marshal(&encodedManagerCopy) - if err != nil { - return "", fmt.Errorf("error marshalling manager identifier: %v", err) - } - - return string(b), nil -} - -func decodeVersionedSet(encodedVersionedSet *metav1.ManagedFieldsEntry) (versionedSet fieldpath.VersionedSet, err error) { - fields := EmptyFields - if encodedVersionedSet.FieldsV1 != nil { - fields = *encodedVersionedSet.FieldsV1 - } - set, err := FieldsToSet(fields) - if err != nil { - return nil, fmt.Errorf("error decoding set: %v", err) - } - return fieldpath.NewVersionedSet(&set, fieldpath.APIVersion(encodedVersionedSet.APIVersion), encodedVersionedSet.Operation == metav1.ManagedFieldsOperationApply), nil -} - -// encodeManagedFields converts ManagedFields from the format used by -// sigs.k8s.io/structured-merge-diff to the wire format (api format) -func encodeManagedFields(managed ManagedInterface) (encodedManagedFields []metav1.ManagedFieldsEntry, err error) { - if len(managed.Fields()) == 0 { - return nil, nil - } - encodedManagedFields = []metav1.ManagedFieldsEntry{} - for manager := range managed.Fields() { - versionedSet := managed.Fields()[manager] - v, err := encodeManagerVersionedSet(manager, versionedSet) - if err != nil { - return nil, fmt.Errorf("error encoding versioned set for %v: %v", manager, err) - } - if t, ok := managed.Times()[manager]; ok { - v.Time = t - } - encodedManagedFields = append(encodedManagedFields, *v) - } - return sortEncodedManagedFields(encodedManagedFields) -} - -func sortEncodedManagedFields(encodedManagedFields []metav1.ManagedFieldsEntry) (sortedManagedFields []metav1.ManagedFieldsEntry, err error) { - sort.Slice(encodedManagedFields, func(i, j int) bool { - p, q := encodedManagedFields[i], encodedManagedFields[j] - - if p.Operation != q.Operation { - return p.Operation < q.Operation - } - - pSeconds, qSeconds := int64(0), int64(0) - if p.Time != nil { - pSeconds = p.Time.Unix() - } - if q.Time != nil { - qSeconds = q.Time.Unix() - } - if pSeconds != qSeconds { - return pSeconds < qSeconds - } - - if p.Manager != q.Manager { - return p.Manager < q.Manager - } - - if p.APIVersion != q.APIVersion { - return p.APIVersion < q.APIVersion - } - return p.Subresource < q.Subresource - }) - - return encodedManagedFields, nil -} - -func encodeManagerVersionedSet(manager string, versionedSet fieldpath.VersionedSet) (encodedVersionedSet *metav1.ManagedFieldsEntry, err error) { - encodedVersionedSet = &metav1.ManagedFieldsEntry{} - - // Get as many fields as we can from the manager identifier - err = json.Unmarshal([]byte(manager), encodedVersionedSet) - if err != nil { - return nil, fmt.Errorf("error unmarshalling manager identifier %v: %v", manager, err) - } - - // Get the APIVersion, Operation, and Fields from the VersionedSet - encodedVersionedSet.APIVersion = string(versionedSet.APIVersion()) - if versionedSet.Applied() { - encodedVersionedSet.Operation = metav1.ManagedFieldsOperationApply - } - encodedVersionedSet.FieldsType = "FieldsV1" - fields, err := SetToFields(*versionedSet.Set()) - if err != nil { - return nil, fmt.Errorf("error encoding set: %v", err) - } - encodedVersionedSet.FieldsV1 = &fields - - return encodedVersionedSet, nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/managedfields_test.go b/pkg/endpoints/handlers/fieldmanager/internal/managedfields_test.go deleted file mode 100644 index 2d8cb1240..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/managedfields_test.go +++ /dev/null @@ -1,520 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "fmt" - "reflect" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "sigs.k8s.io/yaml" -) - -// TestHasFieldsType makes sure that we fail if we don't have a -// FieldsType set properly. -func TestHasFieldsType(t *testing.T) { - var unmarshaled []metav1.ManagedFieldsEntry - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:field: {} - manager: foo - operation: Apply -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err != nil { - t.Fatalf("did not expect decoding error but got: %v", err) - } - - // Invalid fieldsType V2. - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsType: FieldsV2 - fieldsV1: - f:field: {} - manager: foo - operation: Apply -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err == nil { - t.Fatal("Expect decoding error but got none") - } - - // Missing fieldsType. - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsV1: - f:field: {} - manager: foo - operation: Apply -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err == nil { - t.Fatal("Expect decoding error but got none") - } -} - -// TestHasAPIVersion makes sure that we fail if we don't have an -// APIVersion set. -func TestHasAPIVersion(t *testing.T) { - var unmarshaled []metav1.ManagedFieldsEntry - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:field: {} - manager: foo - operation: Apply -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err != nil { - t.Fatalf("did not expect decoding error but got: %v", err) - } - - // Missing apiVersion. - unmarshaled = nil - if err := yaml.Unmarshal([]byte(`- fieldsType: FieldsV1 - fieldsV1: - f:field: {} - manager: foo - operation: Apply -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err == nil { - t.Fatal("Expect decoding error but got none") - } -} - -// TestHasOperation makes sure that we fail if we don't have an -// Operation set properly. -func TestHasOperation(t *testing.T) { - var unmarshaled []metav1.ManagedFieldsEntry - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:field: {} - manager: foo - operation: Apply -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err != nil { - t.Fatalf("did not expect decoding error but got: %v", err) - } - - // Invalid operation. - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:field: {} - manager: foo - operation: Invalid -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err == nil { - t.Fatal("Expect decoding error but got none") - } - - // Missing operation. - unmarshaled = nil - if err := yaml.Unmarshal([]byte(`- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:field: {} - manager: foo -`), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - if _, err := DecodeManagedFields(unmarshaled); err == nil { - t.Fatal("Expect decoding error but got none") - } -} - -// TestRoundTripManagedFields will roundtrip ManagedFields from the wire format -// (api format) to the format used by sigs.k8s.io/structured-merge-diff and back -func TestRoundTripManagedFields(t *testing.T) { - tests := []string{ - `null -`, - `- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - v:3: - f:alsoPi: {} - v:3.1415: - f:pi: {} - v:false: - f:notTrue: {} - manager: foo - operation: Update - time: "2001-02-03T04:05:06Z" -- apiVersion: v1beta1 - fieldsType: FieldsV1 - fieldsV1: - i:5: - f:i: {} - manager: foo - operation: Update - time: "2011-12-13T14:15:16Z" -`, - `- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:spec: - f:containers: - k:{"name":"c"}: - f:image: {} - f:name: {} - manager: foo - operation: Apply -`, - `- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:apiVersion: {} - f:kind: {} - f:metadata: - f:labels: - f:app: {} - f:name: {} - f:spec: - f:replicas: {} - f:selector: - f:matchLabels: - f:app: {} - f:template: - f:medatada: - f:labels: - f:app: {} - f:spec: - f:containers: - k:{"name":"nginx"}: - .: {} - f:image: {} - f:name: {} - f:ports: - i:0: - f:containerPort: {} - manager: foo - operation: Update -`, - `- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:allowVolumeExpansion: {} - f:apiVersion: {} - f:kind: {} - f:metadata: - f:name: {} - f:parameters: - f:resturl: {} - f:restuser: {} - f:secretName: {} - f:secretNamespace: {} - f:provisioner: {} - manager: foo - operation: Apply -`, - `- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:apiVersion: {} - f:kind: {} - f:metadata: - f:name: {} - f:spec: - f:group: {} - f:names: - f:kind: {} - f:plural: {} - f:shortNames: - i:0: {} - f:singular: {} - f:scope: {} - f:versions: - k:{"name":"v1"}: - f:name: {} - f:served: {} - f:storage: {} - manager: foo - operation: Update -`, - `- apiVersion: v1 - fieldsType: FieldsV1 - fieldsV1: - f:spec: - f:replicas: {} - manager: foo - operation: Update - subresource: scale -`, - } - - for _, test := range tests { - t.Run(test, func(t *testing.T) { - var unmarshaled []metav1.ManagedFieldsEntry - if err := yaml.Unmarshal([]byte(test), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - decoded, err := DecodeManagedFields(unmarshaled) - if err != nil { - t.Fatalf("did not expect decoding error but got: %v", err) - } - encoded, err := encodeManagedFields(decoded) - if err != nil { - t.Fatalf("did not expect encoding error but got: %v", err) - } - marshaled, err := yaml.Marshal(&encoded) - if err != nil { - t.Fatalf("did not expect yaml marshalling error but got: %v", err) - } - if !reflect.DeepEqual(string(marshaled), test) { - t.Fatalf("expected:\n%v\nbut got:\n%v", test, string(marshaled)) - } - }) - } -} - -func TestBuildManagerIdentifier(t *testing.T) { - tests := []struct { - managedFieldsEntry string - expected string - }{ - { - managedFieldsEntry: ` -apiVersion: v1 -fieldsV1: - f:apiVersion: {} -manager: foo -operation: Update -time: "2001-02-03T04:05:06Z" -`, - expected: "{\"manager\":\"foo\",\"operation\":\"Update\",\"apiVersion\":\"v1\"}", - }, - { - managedFieldsEntry: ` -apiVersion: v1 -fieldsV1: - f:apiVersion: {} -manager: foo -operation: Apply -time: "2001-02-03T04:05:06Z" -`, - expected: "{\"manager\":\"foo\",\"operation\":\"Apply\"}", - }, - { - managedFieldsEntry: ` -apiVersion: v1 -fieldsV1: - f:apiVersion: {} -manager: foo -operation: Apply -subresource: scale -time: "2001-02-03T04:05:06Z" -`, - expected: "{\"manager\":\"foo\",\"operation\":\"Apply\",\"subresource\":\"scale\"}", - }, - } - - for _, test := range tests { - t.Run(test.managedFieldsEntry, func(t *testing.T) { - var unmarshaled metav1.ManagedFieldsEntry - if err := yaml.Unmarshal([]byte(test.managedFieldsEntry), &unmarshaled); err != nil { - t.Fatalf("did not expect yaml unmarshalling error but got: %v", err) - } - decoded, err := BuildManagerIdentifier(&unmarshaled) - if err != nil { - t.Fatalf("did not expect decoding error but got: %v", err) - } - if !reflect.DeepEqual(decoded, test.expected) { - t.Fatalf("expected:\n%v\nbut got:\n%v", test.expected, decoded) - } - }) - } -} - -func TestSortEncodedManagedFields(t *testing.T) { - tests := []struct { - name string - managedFields []metav1.ManagedFieldsEntry - expected []metav1.ManagedFieldsEntry - }{ - { - name: "empty", - managedFields: []metav1.ManagedFieldsEntry{}, - expected: []metav1.ManagedFieldsEntry{}, - }, - { - name: "nil", - managedFields: nil, - expected: nil, - }, - { - name: "remains untouched", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - }, - { - name: "manager without time first", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - }, - { - name: "manager without time first name last", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - }, - { - name: "apply first", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - }, - { - name: "newest last", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2002-01-01T01:00:00Z")}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2002-01-01T01:00:00Z")}, - }, - }, - { - name: "manager last", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "d", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "d", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - }, - }, - { - name: "manager sorted", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "g", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "f", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2002-01-01T01:00:00Z")}, - {Manager: "i", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "d", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2002-01-01T01:00:00Z")}, - {Manager: "h", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "e", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2003-01-01T01:00:00Z")}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "g", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "h", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "i", Operation: metav1.ManagedFieldsOperationApply, Time: nil}, - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2001-01-01T01:00:00Z")}, - {Manager: "d", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2002-01-01T01:00:00Z")}, - {Manager: "f", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2002-01-01T01:00:00Z")}, - {Manager: "e", Operation: metav1.ManagedFieldsOperationUpdate, Time: parseTimeOrPanic("2003-01-01T01:00:00Z")}, - }, - }, - { - name: "sort drops nanoseconds", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 1, time.UTC)}}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 2, time.UTC)}}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 3, time.UTC)}}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 2, time.UTC)}}, - {Manager: "b", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 3, time.UTC)}}, - {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 1, time.UTC)}}, - }, - }, - { - name: "entries with subresource field", - managedFields: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Subresource: "status"}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Subresource: "scale"}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply}, - }, - expected: []metav1.ManagedFieldsEntry{ - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Subresource: "scale"}, - {Manager: "a", Operation: metav1.ManagedFieldsOperationApply, Subresource: "status"}, - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - sorted, err := sortEncodedManagedFields(test.managedFields) - if err != nil { - t.Fatalf("did not expect error when sorting but got: %v", err) - } - if !reflect.DeepEqual(sorted, test.expected) { - t.Fatalf("expected:\n%v\nbut got:\n%v", test.expected, sorted) - } - }) - } -} - -func parseTimeOrPanic(s string) *metav1.Time { - t, err := time.Parse(time.RFC3339, s) - if err != nil { - panic(fmt.Sprintf("failed to parse time %s, got: %v", s, err)) - } - return &metav1.Time{Time: t.UTC()} -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/managedfieldsupdater.go b/pkg/endpoints/handlers/fieldmanager/internal/managedfieldsupdater.go deleted file mode 100644 index 376eed6b2..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/managedfieldsupdater.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2020 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 internal - -import ( - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -type managedFieldsUpdater struct { - fieldManager Manager -} - -var _ Manager = &managedFieldsUpdater{} - -// NewManagedFieldsUpdater is responsible for updating the managedfields -// in the object, updating the time of the operation as necessary. For -// updates, it uses a hard-coded manager to detect if things have -// changed, and swaps back the correct manager after the operation is -// done. -func NewManagedFieldsUpdater(fieldManager Manager) Manager { - return &managedFieldsUpdater{ - fieldManager: fieldManager, - } -} - -// Update implements Manager. -func (f *managedFieldsUpdater) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - self := "current-operation" - object, managed, err := f.fieldManager.Update(liveObj, newObj, managed, self) - if err != nil { - return object, managed, err - } - - // If the current operation took any fields from anything, it means the object changed, - // so update the timestamp of the managedFieldsEntry and merge with any previous updates from the same manager - if vs, ok := managed.Fields()[self]; ok { - delete(managed.Fields(), self) - - if previous, ok := managed.Fields()[manager]; ok { - managed.Fields()[manager] = fieldpath.NewVersionedSet(vs.Set().Union(previous.Set()), vs.APIVersion(), vs.Applied()) - } else { - managed.Fields()[manager] = vs - } - - managed.Times()[manager] = &metav1.Time{Time: time.Now().UTC()} - } - - return object, managed, nil -} - -// Apply implements Manager. -func (f *managedFieldsUpdater) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { - object, managed, err := f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) - if err != nil { - return object, managed, err - } - if object != nil { - managed.Times()[fieldManager] = &metav1.Time{Time: time.Now().UTC()} - } else { - object = liveObj.DeepCopyObject() - RemoveObjectManagedFields(object) - } - return object, managed, nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/managedfieldsupdater_test.go b/pkg/endpoints/handlers/fieldmanager/internal/managedfieldsupdater_test.go deleted file mode 100644 index 11aaedc29..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/managedfieldsupdater_test.go +++ /dev/null @@ -1,524 +0,0 @@ -/* -Copyright 2020 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 internal_test - -import ( - "fmt" - "reflect" - "testing" - "time" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/fieldmanagertest" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "sigs.k8s.io/yaml" -) - -func TestManagedFieldsUpdateDoesModifyTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = updateObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - - time.Sleep(time.Second) - - err = updateObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "new-value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - - if previousManagedFields[0].Time.Equal(newManagedFields[0].Time) { - t.Errorf("ManagedFields time has not been updated:\n%v", newManagedFields) - } -} - -func TestManagedFieldsApplyDoesModifyTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = applyObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - - time.Sleep(time.Second) - - err = applyObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "new-value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - - if previousManagedFields[0].Time.Equal(newManagedFields[0].Time) { - t.Errorf("ManagedFields time has not been updated:\n%v", newManagedFields) - } -} - -func TestManagedFieldsUpdateWithoutChangesDoesNotModifyTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = updateObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - - time.Sleep(time.Second) - - err = updateObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - - if !previousManagedFields[0].Time.Equal(newManagedFields[0].Time) { - t.Errorf("ManagedFields time has changed:\nBefore:\n%v\nAfter:\n%v", previousManagedFields, newManagedFields) - } -} - -func TestManagedFieldsApplyWithoutChangesDoesNotModifyTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = applyObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - - time.Sleep(time.Second) - - err = applyObject(f, "fieldmanager_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - - if !previousManagedFields[0].Time.Equal(newManagedFields[0].Time) { - t.Errorf("ManagedFields time has changed:\nBefore:\n%v\nAfter:\n%v", previousManagedFields, newManagedFields) - } -} - -func TestNonManagedFieldsUpdateDoesNotModifyTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = updateObject(f, "fieldmanager_a_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_a": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - err = updateObject(f, "fieldmanager_b_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_b": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - previousEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range previousManagedFields { - previousEntries[entry.Manager] = entry - } - - time.Sleep(time.Second) - - err = updateObject(f, "fieldmanager_a_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_a": "value", - "key_b": "new-value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - newEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range newManagedFields { - newEntries[entry.Manager] = entry - } - - if _, ok := newEntries["fieldmanager_b_test"]; ok { - t.Errorf("FieldManager B ManagedFields has changed:\n%v", newEntries["fieldmanager_b_test"]) - } -} - -func TestNonManagedFieldsApplyDoesNotModifyTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = applyObject(f, "fieldmanager_a_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_a": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - err = applyObject(f, "fieldmanager_b_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_b": "value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - previousEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range previousManagedFields { - previousEntries[entry.Manager] = entry - } - - time.Sleep(time.Second) - - err = applyObject(f, "fieldmanager_a_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_a": "new-value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - newEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range newManagedFields { - newEntries[entry.Manager] = entry - } - - if !previousEntries["fieldmanager_b_test"].Time.Equal(newEntries["fieldmanager_b_test"].Time) { - t.Errorf("FieldManager B ManagedFields time changed:\nBefore:\n%v\nAfter:\n%v", - previousEntries["fieldmanager_b_test"], newEntries["fieldmanager_b_test"]) - } -} - -func TestTakingOverManagedFieldsDuringUpdateDoesNotModifyPreviousManagerTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = updateObject(f, "fieldmanager_a_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_a": "value", - "key_b": value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - previousEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range previousManagedFields { - previousEntries[entry.Manager] = entry - } - - time.Sleep(time.Second) - - err = updateObject(f, "fieldmanager_b_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_b": "new-value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - newEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range newManagedFields { - newEntries[entry.Manager] = entry - } - - if !previousEntries["fieldmanager_a_test"].Time.Equal(newEntries["fieldmanager_a_test"].Time) { - t.Errorf("FieldManager A ManagedFields time has been updated:\nBefore:\n%v\nAfter:\n%v", - previousEntries["fieldmanager_a_test"], newEntries["fieldmanager_a_test"]) - } -} - -func TestTakingOverManagedFieldsDuringApplyDoesNotModifyPreviousManagerTime(t *testing.T) { - var err error - f := fieldmanagertest.NewTestFieldManager(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "ConfigMap")) - - err = applyObject(f, "fieldmanager_a_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_a": "value", - "key_b": value" - } - }`)) - if err != nil { - t.Fatal(err) - } - previousManagedFields := f.ManagedFields() - previousEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range previousManagedFields { - previousEntries[entry.Manager] = entry - } - - time.Sleep(time.Second) - - err = applyObject(f, "fieldmanager_b_test", []byte(`{ - "apiVersion": "v1", - "kind": "ConfigMap", - "metadata": { - "name": "configmap" - }, - "data": { - "key_b": "new-value" - } - }`)) - if err != nil { - t.Fatal(err) - } - newManagedFields := f.ManagedFields() - newEntries := map[string]v1.ManagedFieldsEntry{} - for _, entry := range newManagedFields { - newEntries[entry.Manager] = entry - } - - if !previousEntries["fieldmanager_a_test"].Time.Equal(newEntries["fieldmanager_a_test"].Time) { - t.Errorf("FieldManager A ManagedFields time has been updated:\nBefore:\n%v\nAfter:\n%v", - previousEntries["fieldmanager_a_test"], newEntries["fieldmanager_a_test"]) - } -} - -type NoopManager struct{} - -func (NoopManager) Apply(liveObj, appliedObj runtime.Object, managed internal.Managed, fieldManager string, force bool) (runtime.Object, internal.Managed, error) { - return nil, managed, nil -} - -func (NoopManager) Update(liveObj, newObj runtime.Object, managed internal.Managed, manager string) (runtime.Object, internal.Managed, error) { - return nil, nil, nil -} - -func updateObject(f fieldmanagertest.TestFieldManager, fieldManagerName string, object []byte) error { - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(object, &obj.Object); err != nil { - return fmt.Errorf("error decoding YAML: %v", err) - } - if err := f.Update(obj, fieldManagerName); err != nil { - return fmt.Errorf("failed to update object: %v", err) - } - return nil -} - -func applyObject(f fieldmanagertest.TestFieldManager, fieldManagerName string, object []byte) error { - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal(object, &obj.Object); err != nil { - return fmt.Errorf("error decoding YAML: %v", err) - } - if err := f.Apply(obj, fieldManagerName, true); err != nil { - return fmt.Errorf("failed to apply object: %v", err) - } - return nil -} - -// Ensures that if ManagedFieldsUpdater gets a nil value from its nested manager -// chain (meaning the operation was a no-op), then the ManagedFieldsUpdater -// itself will return a copy of the input live object, with its managed fields -// removed -func TestNilNewObjectReplacedWithDeepCopyExcludingManagedFields(t *testing.T) { - // Initialize our "live object" with some managed fields - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "name": "pod", - "labels": {"app": "nginx"}, - "managedFields": [ - { - "apiVersion": "v1", - "fieldsType": "FieldsV1", - "fieldsV1": { - "f:metadata": { - "f:labels": { - "f:app": {} - } - } - }, - "manager": "fieldmanager_test", - "operation": "Apply", - "time": "2021-11-11T18:41:17Z" - } - ] - } - }`), &obj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - accessor, err := meta.Accessor(obj) - if err != nil { - t.Fatalf("couldn't get accessor: %v", err) - } - - // Decode the managed fields in the live object, since it isn't allowed in the patch. - managed, err := internal.DecodeManagedFields(accessor.GetManagedFields()) - if err != nil { - t.Fatalf("failed to decode managed fields: %v", err) - } - - updater := internal.NewManagedFieldsUpdater(NoopManager{}) - - newObject, _, err := updater.Apply(obj, obj.DeepCopyObject(), managed, "some_manager", false) - if err != nil { - t.Fatalf("failed to apply configuration %v", err) - } - - if newObject == obj { - t.Fatalf("returned newObject must not be the same instance as the passed in liveObj") - } - - // Rip off managed fields of live, and check that it is deeply - // equal to newObject - liveWithoutManaged := obj.DeepCopyObject() - internal.RemoveObjectManagedFields(liveWithoutManaged) - - if !reflect.DeepEqual(liveWithoutManaged, newObject) { - t.Fatalf("returned newObject must be deeply equal to the input live object, without managed fields") - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/manager.go b/pkg/endpoints/handlers/fieldmanager/internal/manager.go deleted file mode 100644 index 053936103..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/manager.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2022 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 internal - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -// Managed groups a fieldpath.ManagedFields together with the timestamps associated with each operation. -type Managed interface { - // Fields gets the fieldpath.ManagedFields. - Fields() fieldpath.ManagedFields - - // Times gets the timestamps associated with each operation. - Times() map[string]*metav1.Time -} - -// Manager updates the managed fields and merges applied configurations. -type Manager interface { - // Update is used when the object has already been merged (non-apply - // use-case), and simply updates the managed fields in the output - // object. - // * `liveObj` is not mutated by this function - // * `newObj` may be mutated by this function - // Returns the new object with managedFields removed, and the object's new - // proposed managedFields separately. - Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) - - // Apply is used when server-side apply is called, as it merges the - // object and updates the managed fields. - // * `liveObj` is not mutated by this function - // * `newObj` may be mutated by this function - // Returns the new object with managedFields removed, and the object's new - // proposed managedFields separately. - Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/pathelement.go b/pkg/endpoints/handlers/fieldmanager/internal/pathelement.go deleted file mode 100644 index 1954d65d3..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/pathelement.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "encoding/json" - "errors" - "fmt" - "strconv" - "strings" - - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/value" -) - -const ( - // Field indicates that the content of this path element is a field's name - Field = "f" - - // Value indicates that the content of this path element is a field's value - Value = "v" - - // Index indicates that the content of this path element is an index in an array - Index = "i" - - // Key indicates that the content of this path element is a key value map - Key = "k" - - // Separator separates the type of a path element from the contents - Separator = ":" -) - -// NewPathElement parses a serialized path element -func NewPathElement(s string) (fieldpath.PathElement, error) { - split := strings.SplitN(s, Separator, 2) - if len(split) < 2 { - return fieldpath.PathElement{}, fmt.Errorf("missing colon: %v", s) - } - switch split[0] { - case Field: - return fieldpath.PathElement{ - FieldName: &split[1], - }, nil - case Value: - val, err := value.FromJSON([]byte(split[1])) - if err != nil { - return fieldpath.PathElement{}, err - } - return fieldpath.PathElement{ - Value: &val, - }, nil - case Index: - i, err := strconv.Atoi(split[1]) - if err != nil { - return fieldpath.PathElement{}, err - } - return fieldpath.PathElement{ - Index: &i, - }, nil - case Key: - kv := map[string]json.RawMessage{} - err := json.Unmarshal([]byte(split[1]), &kv) - if err != nil { - return fieldpath.PathElement{}, err - } - fields := value.FieldList{} - for k, v := range kv { - b, err := json.Marshal(v) - if err != nil { - return fieldpath.PathElement{}, err - } - val, err := value.FromJSON(b) - if err != nil { - return fieldpath.PathElement{}, err - } - - fields = append(fields, value.Field{ - Name: k, - Value: val, - }) - } - return fieldpath.PathElement{ - Key: &fields, - }, nil - default: - // Ignore unknown key types - return fieldpath.PathElement{}, nil - } -} - -// PathElementString serializes a path element -func PathElementString(pe fieldpath.PathElement) (string, error) { - switch { - case pe.FieldName != nil: - return Field + Separator + *pe.FieldName, nil - case pe.Key != nil: - kv := map[string]json.RawMessage{} - for _, k := range *pe.Key { - b, err := value.ToJSON(k.Value) - if err != nil { - return "", err - } - m := json.RawMessage{} - err = json.Unmarshal(b, &m) - if err != nil { - return "", err - } - kv[k.Name] = m - } - b, err := json.Marshal(kv) - if err != nil { - return "", err - } - return Key + ":" + string(b), nil - case pe.Value != nil: - b, err := value.ToJSON(*pe.Value) - if err != nil { - return "", err - } - return Value + ":" + string(b), nil - case pe.Index != nil: - return Index + ":" + strconv.Itoa(*pe.Index), nil - default: - return "", errors.New("Invalid type of path element") - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/pathelement_test.go b/pkg/endpoints/handlers/fieldmanager/internal/pathelement_test.go deleted file mode 100644 index bd119e03c..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/pathelement_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2018 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 internal - -import "testing" - -func TestPathElementRoundTrip(t *testing.T) { - tests := []string{ - `i:0`, - `i:1234`, - `f:`, - `f:spec`, - `f:more-complicated-string`, - `k:{"name":"my-container"}`, - `k:{"port":"8080","protocol":"TCP"}`, - `k:{"optionalField":null}`, - `k:{"jsonField":{"A":1,"B":null,"C":"D","E":{"F":"G"}}}`, - `k:{"listField":["1","2","3"]}`, - `v:null`, - `v:"some-string"`, - `v:1234`, - `v:{"some":"json"}`, - } - - for _, test := range tests { - t.Run(test, func(t *testing.T) { - pe, err := NewPathElement(test) - if err != nil { - t.Fatalf("Failed to create path element: %v", err) - } - output, err := PathElementString(pe) - if err != nil { - t.Fatalf("Failed to create string from path element: %v", err) - } - if test != output { - t.Fatalf("Expected round-trip:\ninput: %v\noutput: %v", test, output) - } - }) - } -} - -func TestPathElementIgnoreUnknown(t *testing.T) { - _, err := NewPathElement("r:Hello") - if err != nil { - t.Fatalf("Unknown qualifiers should be ignored") - } -} - -func TestNewPathElementError(t *testing.T) { - tests := []string{ - ``, - `no-colon`, - `i:index is not a number`, - `i:1.23`, - `i:`, - `v:invalid json`, - `v:`, - `k:invalid json`, - `k:{"name":invalid}`, - } - - for _, test := range tests { - t.Run(test, func(t *testing.T) { - _, err := NewPathElement(test) - if err == nil { - t.Fatalf("Expected error, no error found") - } - }) - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/skipnonapplied.go b/pkg/endpoints/handlers/fieldmanager/internal/skipnonapplied.go deleted file mode 100644 index 6b281ec1e..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/skipnonapplied.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2019 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 internal - -import ( - "fmt" - "math/rand" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type skipNonAppliedManager struct { - fieldManager Manager - objectCreater runtime.ObjectCreater - gvk schema.GroupVersionKind - beforeApplyManagerName string - probability float32 -} - -var _ Manager = &skipNonAppliedManager{} - -// NewSkipNonAppliedManager creates a new wrapped FieldManager that only starts tracking managers after the first apply. -func NewSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, gvk schema.GroupVersionKind) Manager { - return NewProbabilisticSkipNonAppliedManager(fieldManager, objectCreater, gvk, 0.0) -} - -// NewProbabilisticSkipNonAppliedManager creates a new wrapped FieldManager that starts tracking managers after the first apply, -// or starts tracking on create with p probability. -func NewProbabilisticSkipNonAppliedManager(fieldManager Manager, objectCreater runtime.ObjectCreater, gvk schema.GroupVersionKind, p float32) Manager { - return &skipNonAppliedManager{ - fieldManager: fieldManager, - objectCreater: objectCreater, - gvk: gvk, - beforeApplyManagerName: "before-first-apply", - probability: p, - } -} - -// Update implements Manager. -func (f *skipNonAppliedManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - accessor, err := meta.Accessor(liveObj) - if err != nil { - return newObj, managed, nil - } - - // If managed fields is empty, we need to determine whether to skip tracking managed fields. - if len(managed.Fields()) == 0 { - // Check if the operation is a create, by checking whether lastObj's UID is empty. - // If the operation is create, P(tracking managed fields) = f.probability - // If the operation is update, skip tracking managed fields, since we already know managed fields is empty. - if len(accessor.GetUID()) == 0 { - if f.probability <= rand.Float32() { - return newObj, managed, nil - } - } else { - return newObj, managed, nil - } - } - return f.fieldManager.Update(liveObj, newObj, managed, manager) -} - -// Apply implements Manager. -func (f *skipNonAppliedManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, fieldManager string, force bool) (runtime.Object, Managed, error) { - if len(managed.Fields()) == 0 { - emptyObj, err := f.objectCreater.New(f.gvk) - if err != nil { - return nil, nil, fmt.Errorf("failed to create empty object of type %v: %v", f.gvk, err) - } - liveObj, managed, err = f.fieldManager.Update(emptyObj, liveObj, managed, f.beforeApplyManagerName) - if err != nil { - return nil, nil, fmt.Errorf("failed to create manager for existing fields: %v", err) - } - } - return f.fieldManager.Apply(liveObj, appliedObj, managed, fieldManager, force) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/skipnonapplied_test.go b/pkg/endpoints/handlers/fieldmanager/internal/skipnonapplied_test.go deleted file mode 100644 index 0ba7b0845..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/skipnonapplied_test.go +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright 2019 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 internal_test - -import ( - "encoding/json" - "strings" - "testing" - - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - internaltesting "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal/testing" - "sigs.k8s.io/yaml" -) - -func TestNoUpdateBeforeFirstApply(t *testing.T) { - f := internaltesting.NewTestFieldManagerImpl(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod"), "", func(m internal.Manager) internal.Manager { - return internal.NewSkipNonAppliedManager( - m, - internaltesting.NewFakeObjectCreater(), - schema.FromAPIVersionAndKind("v1", "Pod"), - ) - }) - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "name": "pod", - "labels": {"app": "nginx"} - }, - "spec": { - "containers": [{ - "name": "nginx", - "image": "nginx:latest" - }] - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - if err := f.Apply(appliedObj, "fieldmanager_test_apply", false); err != nil { - t.Fatalf("failed to update object: %v", err) - } - - if e, a := 1, len(f.ManagedFields()); e != a { - t.Fatalf("exected %v entries in managedFields, but got %v: %#v", e, a, f.ManagedFields()) - } - - if e, a := "fieldmanager_test_apply", f.ManagedFields()[0].Manager; e != a { - t.Fatalf("exected manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } -} - -func TestUpdateBeforeFirstApply(t *testing.T) { - f := internaltesting.NewTestFieldManagerImpl(fakeTypeConverter, schema.FromAPIVersionAndKind("v1", "Pod"), "", func(m internal.Manager) internal.Manager { - return internal.NewSkipNonAppliedManager( - m, - internaltesting.NewFakeObjectCreater(), - schema.FromAPIVersionAndKind("v1", "Pod"), - ) - }) - - updatedObj := &unstructured.Unstructured{} - if err := json.Unmarshal([]byte(`{"kind": "Pod", "apiVersion": "v1", "metadata": {"labels": {"app": "my-nginx"}}}`), updatedObj); err != nil { - t.Fatalf("Failed to unmarshal object: %v", err) - } - - if err := f.Update(updatedObj, "fieldmanager_test_update"); err != nil { - t.Fatalf("failed to update object: %v", err) - } - - if m := f.ManagedFields(); len(m) != 0 { - t.Fatalf("managedFields were tracked on update only: %v", m) - } - - appliedObj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(`{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "name": "pod", - "labels": {"app": "nginx"} - }, - "spec": { - "containers": [{ - "name": "nginx", - "image": "nginx:latest" - }] - } - }`), &appliedObj.Object); err != nil { - t.Fatalf("error decoding YAML: %v", err) - } - - err := f.Apply(appliedObj, "fieldmanager_test_apply", false) - apiStatus, _ := err.(apierrors.APIStatus) - if err == nil || !apierrors.IsConflict(err) || len(apiStatus.Status().Details.Causes) != 1 { - t.Fatalf("Expecting to get one conflict but got %v", err) - } - - if e, a := ".metadata.labels.app", apiStatus.Status().Details.Causes[0].Field; e != a { - t.Fatalf("Expecting to conflict on field %q but conflicted on field %q: %v", e, a, err) - } - - if e, a := "before-first-apply", apiStatus.Status().Details.Causes[0].Message; !strings.Contains(a, e) { - t.Fatalf("Expecting conflict message to contain %q but got %q: %v", e, a, err) - } - - if err := f.Apply(appliedObj, "fieldmanager_test_apply", true); err != nil { - t.Fatalf("failed to update object: %v", err) - } - - if e, a := 2, len(f.ManagedFields()); e != a { - t.Fatalf("exected %v entries in managedFields, but got %v: %#v", e, a, f.ManagedFields()) - } - - if e, a := "fieldmanager_test_apply", f.ManagedFields()[0].Manager; e != a { - t.Fatalf("exected first manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } - - if e, a := "before-first-apply", f.ManagedFields()[1].Manager; e != a { - t.Fatalf("exected second manager name to be %v, but got %v: %#v", e, a, f.ManagedFields()) - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/stripmeta.go b/pkg/endpoints/handlers/fieldmanager/internal/stripmeta.go deleted file mode 100644 index 9b61f3a6f..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/stripmeta.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2019 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 internal - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -type stripMetaManager struct { - fieldManager Manager - - // stripSet is the list of fields that should never be part of a mangedFields. - stripSet *fieldpath.Set -} - -var _ Manager = &stripMetaManager{} - -// NewStripMetaManager creates a new Manager that strips metadata and typemeta fields from the manager's fieldset. -func NewStripMetaManager(fieldManager Manager) Manager { - return &stripMetaManager{ - fieldManager: fieldManager, - stripSet: fieldpath.NewSet( - fieldpath.MakePathOrDie("apiVersion"), - fieldpath.MakePathOrDie("kind"), - fieldpath.MakePathOrDie("metadata"), - fieldpath.MakePathOrDie("metadata", "name"), - fieldpath.MakePathOrDie("metadata", "namespace"), - fieldpath.MakePathOrDie("metadata", "creationTimestamp"), - fieldpath.MakePathOrDie("metadata", "selfLink"), - fieldpath.MakePathOrDie("metadata", "uid"), - fieldpath.MakePathOrDie("metadata", "clusterName"), - fieldpath.MakePathOrDie("metadata", "generation"), - fieldpath.MakePathOrDie("metadata", "managedFields"), - fieldpath.MakePathOrDie("metadata", "resourceVersion"), - ), - } -} - -// Update implements Manager. -func (f *stripMetaManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - newObj, managed, err := f.fieldManager.Update(liveObj, newObj, managed, manager) - if err != nil { - return nil, nil, err - } - f.stripFields(managed.Fields(), manager) - return newObj, managed, nil -} - -// Apply implements Manager. -func (f *stripMetaManager) Apply(liveObj, appliedObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { - newObj, managed, err := f.fieldManager.Apply(liveObj, appliedObj, managed, manager, force) - if err != nil { - return nil, nil, err - } - f.stripFields(managed.Fields(), manager) - return newObj, managed, nil -} - -// stripFields removes a predefined set of paths found in typed from managed -func (f *stripMetaManager) stripFields(managed fieldpath.ManagedFields, manager string) { - vs, ok := managed[manager] - if ok { - if vs == nil { - panic(fmt.Sprintf("Found unexpected nil manager which should never happen: %s", manager)) - } - newSet := vs.Set().Difference(f.stripSet) - if newSet.Empty() { - delete(managed, manager) - } else { - managed[manager] = fieldpath.NewVersionedSet(newSet, vs.APIVersion(), vs.Applied()) - } - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/structuredmerge.go b/pkg/endpoints/handlers/fieldmanager/internal/structuredmerge.go deleted file mode 100644 index eb5598ac3..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/structuredmerge.go +++ /dev/null @@ -1,183 +0,0 @@ -/* -Copyright 2019 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 internal - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" -) - -type structuredMergeManager struct { - typeConverter TypeConverter - objectConverter runtime.ObjectConvertor - objectDefaulter runtime.ObjectDefaulter - groupVersion schema.GroupVersion - hubVersion schema.GroupVersion - updater merge.Updater -} - -var _ Manager = &structuredMergeManager{} - -// NewStructuredMergeManager creates a new Manager that merges apply requests -// and update managed fields for other types of requests. -func NewStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (Manager, error) { - return &structuredMergeManager{ - typeConverter: typeConverter, - objectConverter: objectConverter, - objectDefaulter: objectDefaulter, - groupVersion: gv, - hubVersion: hub, - updater: merge.Updater{ - Converter: newVersionConverter(typeConverter, objectConverter, hub), // This is the converter provided to SMD from k8s - IgnoredFields: resetFields, - }, - }, nil -} - -// NewCRDStructuredMergeManager creates a new Manager specifically for -// CRDs. This allows for the possibility of fields which are not defined -// in models, as well as having no models defined at all. -func NewCRDStructuredMergeManager(typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectDefaulter runtime.ObjectDefaulter, gv schema.GroupVersion, hub schema.GroupVersion, resetFields map[fieldpath.APIVersion]*fieldpath.Set) (_ Manager, err error) { - return &structuredMergeManager{ - typeConverter: typeConverter, - objectConverter: objectConverter, - objectDefaulter: objectDefaulter, - groupVersion: gv, - hubVersion: hub, - updater: merge.Updater{ - Converter: newCRDVersionConverter(typeConverter, objectConverter, hub), - IgnoredFields: resetFields, - }, - }, nil -} - -func objectGVKNN(obj runtime.Object) string { - name := "" - namespace := "" - if accessor, err := meta.Accessor(obj); err == nil { - name = accessor.GetName() - namespace = accessor.GetNamespace() - } - - return fmt.Sprintf("%v/%v; %v", namespace, name, obj.GetObjectKind().GroupVersionKind()) -} - -// Update implements Manager. -func (f *structuredMergeManager) Update(liveObj, newObj runtime.Object, managed Managed, manager string) (runtime.Object, Managed, error) { - newObjVersioned, err := f.toVersioned(newObj) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert new object (%v) to proper version (%v): %v", objectGVKNN(newObj), f.groupVersion, err) - } - liveObjVersioned, err := f.toVersioned(liveObj) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert live object (%v) to proper version: %v", objectGVKNN(liveObj), err) - } - newObjTyped, err := f.typeConverter.ObjectToTyped(newObjVersioned) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert new object (%v) to smd typed: %v", objectGVKNN(newObjVersioned), err) - } - liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert live object (%v) to smd typed: %v", objectGVKNN(liveObjVersioned), err) - } - apiVersion := fieldpath.APIVersion(f.groupVersion.String()) - - // TODO(apelisse) use the first return value when unions are implemented - _, managedFields, err := f.updater.Update(liveObjTyped, newObjTyped, apiVersion, managed.Fields(), manager) - if err != nil { - return nil, nil, fmt.Errorf("failed to update ManagedFields (%v): %v", objectGVKNN(newObjVersioned), err) - } - managed = NewManaged(managedFields, managed.Times()) - - return newObj, managed, nil -} - -// Apply implements Manager. -func (f *structuredMergeManager) Apply(liveObj, patchObj runtime.Object, managed Managed, manager string, force bool) (runtime.Object, Managed, error) { - // Check that the patch object has the same version as the live object - if patchVersion := patchObj.GetObjectKind().GroupVersionKind().GroupVersion(); patchVersion != f.groupVersion { - return nil, nil, - errors.NewBadRequest( - fmt.Sprintf("Incorrect version specified in apply patch. "+ - "Specified patch version: %s, expected: %s", - patchVersion, f.groupVersion)) - } - - patchObjMeta, err := meta.Accessor(patchObj) - if err != nil { - return nil, nil, fmt.Errorf("couldn't get accessor: %v", err) - } - if patchObjMeta.GetManagedFields() != nil { - return nil, nil, errors.NewBadRequest("metadata.managedFields must be nil") - } - - liveObjVersioned, err := f.toVersioned(liveObj) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert live object (%v) to proper version: %v", objectGVKNN(liveObj), err) - } - - patchObjTyped, err := f.typeConverter.ObjectToTyped(patchObj) - if err != nil { - return nil, nil, fmt.Errorf("failed to create typed patch object (%v): %v", objectGVKNN(patchObj), err) - } - liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned) - if err != nil { - return nil, nil, fmt.Errorf("failed to create typed live object (%v): %v", objectGVKNN(liveObjVersioned), err) - } - - apiVersion := fieldpath.APIVersion(f.groupVersion.String()) - newObjTyped, managedFields, err := f.updater.Apply(liveObjTyped, patchObjTyped, apiVersion, managed.Fields(), manager, force) - if err != nil { - return nil, nil, err - } - managed = NewManaged(managedFields, managed.Times()) - - if newObjTyped == nil { - return nil, managed, nil - } - - newObj, err := f.typeConverter.TypedToObject(newObjTyped) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert new typed object (%v) to object: %v", objectGVKNN(patchObj), err) - } - - newObjVersioned, err := f.toVersioned(newObj) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert new object (%v) to proper version: %v", objectGVKNN(patchObj), err) - } - f.objectDefaulter.Default(newObjVersioned) - - newObjUnversioned, err := f.toUnversioned(newObjVersioned) - if err != nil { - return nil, nil, fmt.Errorf("failed to convert to unversioned (%v): %v", objectGVKNN(patchObj), err) - } - return newObjUnversioned, managed, nil -} - -func (f *structuredMergeManager) toVersioned(obj runtime.Object) (runtime.Object, error) { - return f.objectConverter.ConvertToVersion(obj, f.groupVersion) -} - -func (f *structuredMergeManager) toUnversioned(obj runtime.Object) (runtime.Object, error) { - return f.objectConverter.ConvertToVersion(obj, f.hubVersion) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/testdata/swagger.json b/pkg/endpoints/handlers/fieldmanager/internal/testdata/swagger.json deleted file mode 100644 index 232ccd102..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/testdata/swagger.json +++ /dev/null @@ -1,4195 +0,0 @@ -{ - "definitions": { - "io.k8s.api.apps.v1.Deployment": { - "description": "Deployment enables declarative updates for Pods and ReplicaSets.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object metadata." - }, - "spec": { - "$ref": "#/definitions/io.k8s.api.apps.v1.DeploymentSpec", - "description": "Specification of the desired behavior of the Deployment." - }, - "status": { - "$ref": "#/definitions/io.k8s.api.apps.v1.DeploymentStatus", - "description": "Most recently observed status of the Deployment." - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "apps", - "kind": "Deployment", - "version": "v1" - } - ] - }, - "io.k8s.api.apps.v1.DeploymentCondition": { - "description": "DeploymentCondition describes the state of a deployment at a certain point.", - "properties": { - "lastTransitionTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Last time the condition transitioned from one status to another." - }, - "lastUpdateTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "The last time this condition was updated." - }, - "message": { - "description": "A human readable message indicating details about the transition.", - "type": "string" - }, - "reason": { - "description": "The reason for the condition's last transition.", - "type": "string" - }, - "status": { - "description": "Status of the condition, one of True, False, Unknown.", - "type": "string" - }, - "type": { - "description": "Type of deployment condition.", - "type": "string" - } - }, - "required": [ - "type", - "status" - ], - "type": "object" - }, - "io.k8s.api.apps.v1.DeploymentSpec": { - "description": "DeploymentSpec is the specification of the desired behavior of the Deployment.", - "properties": { - "minReadySeconds": { - "description": "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - "format": "int32", - "type": "integer" - }, - "paused": { - "description": "Indicates that the deployment is paused.", - "type": "boolean" - }, - "progressDeadlineSeconds": { - "description": "The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.", - "format": "int32", - "type": "integer" - }, - "revisionHistoryLimit": { - "description": "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.", - "format": "int32", - "type": "integer" - }, - "selector": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector", - "description": "Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. It must match the pod template's labels." - }, - "strategy": { - "$ref": "#/definitions/io.k8s.api.apps.v1.DeploymentStrategy", - "description": "The deployment strategy to use to replace existing pods with new ones.", - "x-kubernetes-patch-strategy": "retainKeys" - }, - "template": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodTemplateSpec", - "description": "Template describes the pods that will be created." - } - }, - "required": [ - "selector", - "template" - ], - "type": "object" - }, - "io.k8s.api.apps.v1.DeploymentStatus": { - "description": "DeploymentStatus is the most recently observed status of the Deployment.", - "properties": { - "availableReplicas": { - "description": "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "collisionCount": { - "description": "Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.", - "format": "int32", - "type": "integer" - }, - "conditions": { - "description": "Represents the latest available observations of a deployment's current state.", - "items": { - "$ref": "#/definitions/io.k8s.api.apps.v1.DeploymentCondition" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - }, - "observedGeneration": { - "description": "The generation observed by the deployment controller.", - "format": "int64", - "type": "integer" - }, - "readyReplicas": { - "description": "Total number of ready pods targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", - "format": "int32", - "type": "integer" - }, - "unavailableReplicas": { - "description": "Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.", - "format": "int32", - "type": "integer" - }, - "updatedReplicas": { - "description": "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1.DeploymentStrategy": { - "description": "DeploymentStrategy describes how to replace existing pods with new ones.", - "properties": { - "rollingUpdate": { - "$ref": "#/definitions/io.k8s.api.apps.v1.RollingUpdateDeployment", - "description": "Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate." - }, - "type": { - "description": "Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1.RollingUpdateDeployment": { - "description": "Spec to control the desired behavior of rolling update.", - "properties": { - "maxSurge": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods." - }, - "maxUnavailable": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods." - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta1.Deployment": { - "description": "DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object metadata." - }, - "spec": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.DeploymentSpec", - "description": "Specification of the desired behavior of the Deployment." - }, - "status": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.DeploymentStatus", - "description": "Most recently observed status of the Deployment." - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "apps", - "kind": "Deployment", - "version": "v1beta1" - } - ] - }, - "io.k8s.api.apps.v1beta1.DeploymentCondition": { - "description": "DeploymentCondition describes the state of a deployment at a certain point.", - "properties": { - "lastTransitionTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Last time the condition transitioned from one status to another." - }, - "lastUpdateTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "The last time this condition was updated." - }, - "message": { - "description": "A human readable message indicating details about the transition.", - "type": "string" - }, - "reason": { - "description": "The reason for the condition's last transition.", - "type": "string" - }, - "status": { - "description": "Status of the condition, one of True, False, Unknown.", - "type": "string" - }, - "type": { - "description": "Type of deployment condition.", - "type": "string" - } - }, - "required": [ - "type", - "status" - ], - "type": "object" - }, - "io.k8s.api.apps.v1beta1.DeploymentRollback": { - "description": "DEPRECATED. DeploymentRollback stores the information required to rollback a deployment.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "name": { - "description": "Required: This must match the Name of a deployment.", - "type": "string" - }, - "rollbackTo": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.RollbackConfig", - "description": "The config of this deployment rollback." - }, - "updatedAnnotations": { - "additionalProperties": { - "type": "string" - }, - "description": "The annotations to be updated to a deployment", - "type": "object" - } - }, - "required": [ - "name", - "rollbackTo" - ], - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "apps", - "kind": "DeploymentRollback", - "version": "v1beta1" - } - ] - }, - "io.k8s.api.apps.v1beta1.DeploymentSpec": { - "description": "DeploymentSpec is the specification of the desired behavior of the Deployment.", - "properties": { - "minReadySeconds": { - "description": "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - "format": "int32", - "type": "integer" - }, - "paused": { - "description": "Indicates that the deployment is paused.", - "type": "boolean" - }, - "progressDeadlineSeconds": { - "description": "The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.", - "format": "int32", - "type": "integer" - }, - "revisionHistoryLimit": { - "description": "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.", - "format": "int32", - "type": "integer" - }, - "rollbackTo": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.RollbackConfig", - "description": "DEPRECATED. The config this deployment is rolling back to. Will be cleared after rollback is done." - }, - "selector": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector", - "description": "Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment." - }, - "strategy": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.DeploymentStrategy", - "description": "The deployment strategy to use to replace existing pods with new ones.", - "x-kubernetes-patch-strategy": "retainKeys" - }, - "template": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodTemplateSpec", - "description": "Template describes the pods that will be created." - } - }, - "required": [ - "template" - ], - "type": "object" - }, - "io.k8s.api.apps.v1beta1.DeploymentStatus": { - "description": "DeploymentStatus is the most recently observed status of the Deployment.", - "properties": { - "availableReplicas": { - "description": "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "collisionCount": { - "description": "Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.", - "format": "int32", - "type": "integer" - }, - "conditions": { - "description": "Represents the latest available observations of a deployment's current state.", - "items": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.DeploymentCondition" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - }, - "observedGeneration": { - "description": "The generation observed by the deployment controller.", - "format": "int64", - "type": "integer" - }, - "readyReplicas": { - "description": "Total number of ready pods targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", - "format": "int32", - "type": "integer" - }, - "unavailableReplicas": { - "description": "Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.", - "format": "int32", - "type": "integer" - }, - "updatedReplicas": { - "description": "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta1.DeploymentStrategy": { - "description": "DeploymentStrategy describes how to replace existing pods with new ones.", - "properties": { - "rollingUpdate": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta1.RollingUpdateDeployment", - "description": "Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate." - }, - "type": { - "description": "Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta1.RollbackConfig": { - "description": "DEPRECATED.", - "properties": { - "revision": { - "description": "The revision to rollback to. If set to 0, rollback to the last revision.", - "format": "int64", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta1.RollingUpdateDeployment": { - "description": "Spec to control the desired behavior of rolling update.", - "properties": { - "maxSurge": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods." - }, - "maxUnavailable": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods." - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta2.Deployment": { - "description": "DEPRECATED - This group version of Deployment is deprecated by apps/v1/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object metadata." - }, - "spec": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta2.DeploymentSpec", - "description": "Specification of the desired behavior of the Deployment." - }, - "status": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta2.DeploymentStatus", - "description": "Most recently observed status of the Deployment." - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "apps", - "kind": "Deployment", - "version": "v1beta2" - } - ] - }, - "io.k8s.api.apps.v1beta2.DeploymentCondition": { - "description": "DeploymentCondition describes the state of a deployment at a certain point.", - "properties": { - "lastTransitionTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Last time the condition transitioned from one status to another." - }, - "lastUpdateTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "The last time this condition was updated." - }, - "message": { - "description": "A human readable message indicating details about the transition.", - "type": "string" - }, - "reason": { - "description": "The reason for the condition's last transition.", - "type": "string" - }, - "status": { - "description": "Status of the condition, one of True, False, Unknown.", - "type": "string" - }, - "type": { - "description": "Type of deployment condition.", - "type": "string" - } - }, - "required": [ - "type", - "status" - ], - "type": "object" - }, - "io.k8s.api.apps.v1beta2.DeploymentSpec": { - "description": "DeploymentSpec is the specification of the desired behavior of the Deployment.", - "properties": { - "minReadySeconds": { - "description": "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - "format": "int32", - "type": "integer" - }, - "paused": { - "description": "Indicates that the deployment is paused.", - "type": "boolean" - }, - "progressDeadlineSeconds": { - "description": "The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.", - "format": "int32", - "type": "integer" - }, - "revisionHistoryLimit": { - "description": "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.", - "format": "int32", - "type": "integer" - }, - "selector": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector", - "description": "Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. It must match the pod template's labels." - }, - "strategy": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta2.DeploymentStrategy", - "description": "The deployment strategy to use to replace existing pods with new ones.", - "x-kubernetes-patch-strategy": "retainKeys" - }, - "template": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodTemplateSpec", - "description": "Template describes the pods that will be created." - } - }, - "required": [ - "selector", - "template" - ], - "type": "object" - }, - "io.k8s.api.apps.v1beta2.DeploymentStatus": { - "description": "DeploymentStatus is the most recently observed status of the Deployment.", - "properties": { - "availableReplicas": { - "description": "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "collisionCount": { - "description": "Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.", - "format": "int32", - "type": "integer" - }, - "conditions": { - "description": "Represents the latest available observations of a deployment's current state.", - "items": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta2.DeploymentCondition" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - }, - "observedGeneration": { - "description": "The generation observed by the deployment controller.", - "format": "int64", - "type": "integer" - }, - "readyReplicas": { - "description": "Total number of ready pods targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", - "format": "int32", - "type": "integer" - }, - "unavailableReplicas": { - "description": "Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.", - "format": "int32", - "type": "integer" - }, - "updatedReplicas": { - "description": "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta2.DeploymentStrategy": { - "description": "DeploymentStrategy describes how to replace existing pods with new ones.", - "properties": { - "rollingUpdate": { - "$ref": "#/definitions/io.k8s.api.apps.v1beta2.RollingUpdateDeployment", - "description": "Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate." - }, - "type": { - "description": "Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.apps.v1beta2.RollingUpdateDeployment": { - "description": "Spec to control the desired behavior of rolling update.", - "properties": { - "maxSurge": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods." - }, - "maxUnavailable": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.AWSElasticBlockStoreVolumeSource": { - "description": "Represents a Persistent Disk resource in AWS.\n\nAn AWS EBS disk must exist before mounting to a container. The disk must also be in the same AWS zone as the kubelet. An AWS EBS disk can only be mounted as read/write once. AWS EBS volumes support ownership management and SELinux relabeling.", - "properties": { - "fsType": { - "description": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - "type": "string" - }, - "partition": { - "description": "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).", - "format": "int32", - "type": "integer" - }, - "readOnly": { - "description": "Specify \"true\" to force and set the ReadOnly property in VolumeMounts to \"true\". If omitted, the default is \"false\". More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - "type": "boolean" - }, - "volumeID": { - "description": "Unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", - "type": "string" - } - }, - "required": [ - "volumeID" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Affinity": { - "description": "Affinity is a group of affinity scheduling rules.", - "properties": { - "nodeAffinity": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeAffinity", - "description": "Describes node affinity scheduling rules for the pod." - }, - "podAffinity": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodAffinity", - "description": "Describes pod affinity scheduling rules (e.g. co-locate this pod in the same node, zone, etc. as some other pod(s))." - }, - "podAntiAffinity": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodAntiAffinity", - "description": "Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod in the same node, zone, etc. as some other pod(s))." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.AttachedVolume": { - "description": "AttachedVolume describes a volume attached to a node", - "properties": { - "devicePath": { - "description": "DevicePath represents the device path where the volume should be available", - "type": "string" - }, - "name": { - "description": "Name of the attached volume", - "type": "string" - } - }, - "required": [ - "name", - "devicePath" - ], - "type": "object" - }, - "io.k8s.api.core.v1.AzureDiskVolumeSource": { - "description": "AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.", - "properties": { - "cachingMode": { - "description": "Host Caching mode: None, Read Only, Read Write.", - "type": "string" - }, - "diskName": { - "description": "The Name of the data disk in the blob storage", - "type": "string" - }, - "diskURI": { - "description": "The URI the data disk in the blob storage", - "type": "string" - }, - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - "type": "string" - }, - "kind": { - "description": "Expected values Shared: multiple blob disks per storage account Dedicated: single blob disk per storage account Managed: azure managed data disk (only in managed availability set). defaults to shared", - "type": "string" - }, - "readOnly": { - "description": "Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - } - }, - "required": [ - "diskName", - "diskURI" - ], - "type": "object" - }, - "io.k8s.api.core.v1.AzureFileVolumeSource": { - "description": "AzureFile represents an Azure File Service mount on the host and bind mount to the pod.", - "properties": { - "readOnly": { - "description": "Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - }, - "secretName": { - "description": "the name of secret that contains Azure Storage Account Name and Key", - "type": "string" - }, - "shareName": { - "description": "Share Name", - "type": "string" - } - }, - "required": [ - "secretName", - "shareName" - ], - "type": "object" - }, - "io.k8s.api.core.v1.CSIVolumeSource": { - "description": "Represents a source location of a volume to mount, managed by an external CSI driver", - "properties": { - "driver": { - "description": "Driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster.", - "type": "string" - }, - "fsType": { - "description": "Filesystem type to mount. Ex. \"ext4\", \"xfs\", \"ntfs\". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply.", - "type": "string" - }, - "nodePublishSecretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "NodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secret references are passed." - }, - "readOnly": { - "description": "Specifies a read-only configuration for the volume. Defaults to false (read/write).", - "type": "boolean" - }, - "volumeAttributes": { - "additionalProperties": { - "type": "string" - }, - "description": "VolumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values.", - "type": "object" - } - }, - "required": [ - "driver" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Capabilities": { - "description": "Adds and removes POSIX capabilities from running containers.", - "properties": { - "add": { - "description": "Added capabilities", - "items": { - "type": "string" - }, - "type": "array" - }, - "drop": { - "description": "Removed capabilities", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.CephFSVolumeSource": { - "description": "Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.", - "properties": { - "monitors": { - "description": "Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - "items": { - "type": "string" - }, - "type": "array" - }, - "path": { - "description": "Optional: Used as the mounted root, rather than the full Ceph tree, default is /", - "type": "string" - }, - "readOnly": { - "description": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - "type": "boolean" - }, - "secretFile": { - "description": "Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - "type": "string" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it" - }, - "user": { - "description": "Optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", - "type": "string" - } - }, - "required": [ - "monitors" - ], - "type": "object" - }, - "io.k8s.api.core.v1.CinderVolumeSource": { - "description": "Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.", - "properties": { - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - "type": "string" - }, - "readOnly": { - "description": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - "type": "boolean" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "Optional: points to a secret object containing parameters used to connect to OpenStack." - }, - "volumeID": { - "description": "volume id used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", - "type": "string" - } - }, - "required": [ - "volumeID" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ClientIPConfig": { - "description": "ClientIPConfig represents the configurations of Client IP based session affinity.", - "properties": { - "timeoutSeconds": { - "description": "timeoutSeconds specifies the seconds of ClientIP type session sticky time. The value must be >0 && <=86400(for 1 day) if ServiceAffinity == \"ClientIP\". Default value is 10800(for 3 hours).", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ComponentCondition": { - "description": "Information about the condition of a component.", - "properties": { - "error": { - "description": "Condition error code for a component. For example, a health check error code.", - "type": "string" - }, - "message": { - "description": "Message about the condition for a component. For example, information about a health check.", - "type": "string" - }, - "status": { - "description": "Status of the condition for a component. Valid values for \"Healthy\": \"True\", \"False\", or \"Unknown\".", - "type": "string" - }, - "type": { - "description": "Type of condition for a component. Valid value: \"Healthy\"", - "type": "string" - } - }, - "required": [ - "type", - "status" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ConfigMapEnvSource": { - "description": "ConfigMapEnvSource selects a ConfigMap to populate the environment variables with.\n\nThe contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables.", - "properties": { - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the ConfigMap must be defined", - "type": "boolean" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ConfigMapKeySelector": { - "description": "Selects a key from a ConfigMap.", - "properties": { - "key": { - "description": "The key to select.", - "type": "string" - }, - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the ConfigMap or its key must be defined", - "type": "boolean" - } - }, - "required": [ - "key" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ConfigMapNodeConfigSource": { - "description": "ConfigMapNodeConfigSource contains the information to reference a ConfigMap as a config source for the Node.", - "properties": { - "kubeletConfigKey": { - "description": "KubeletConfigKey declares which key of the referenced ConfigMap corresponds to the KubeletConfiguration structure This field is required in all cases.", - "type": "string" - }, - "name": { - "description": "Name is the metadata.name of the referenced ConfigMap. This field is required in all cases.", - "type": "string" - }, - "namespace": { - "description": "Namespace is the metadata.namespace of the referenced ConfigMap. This field is required in all cases.", - "type": "string" - }, - "resourceVersion": { - "description": "ResourceVersion is the metadata.ResourceVersion of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status.", - "type": "string" - }, - "uid": { - "description": "UID is the metadata.UID of the referenced ConfigMap. This field is forbidden in Node.Spec, and required in Node.Status.", - "type": "string" - } - }, - "required": [ - "namespace", - "name", - "kubeletConfigKey" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ConfigMapProjection": { - "description": "Adapts a ConfigMap into a projected volume.\n\nThe contents of the target ConfigMap's Data field will be presented in a projected volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. Note that this is identical to a configmap volume source without the default mode.", - "properties": { - "items": { - "description": "If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.KeyToPath" - }, - "type": "array" - }, - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the ConfigMap or its keys must be defined", - "type": "boolean" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ConfigMapVolumeSource": { - "description": "Adapts a ConfigMap into a volume.\n\nThe contents of the target ConfigMap's Data field will be presented in a volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. ConfigMap volumes support ownership management and SELinux relabeling.", - "properties": { - "defaultMode": { - "description": "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - "format": "int32", - "type": "integer" - }, - "items": { - "description": "If unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.KeyToPath" - }, - "type": "array" - }, - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the ConfigMap or its keys must be defined", - "type": "boolean" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.Container": { - "description": "A single application container that you want to run within a pod.", - "properties": { - "args": { - "description": "Arguments to the entrypoint. The container image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - "items": { - "type": "string" - }, - "type": "array" - }, - "command": { - "description": "Entrypoint array. Not executed within a shell. The container image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "description": "List of environment variables to set in the container. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.EnvVar" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" - }, - "envFrom": { - "description": "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.EnvFromSource" - }, - "type": "array" - }, - "image": { - "description": "Docker image name. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.", - "type": "string" - }, - "imagePullPolicy": { - "description": "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images", - "type": "string" - }, - "lifecycle": { - "$ref": "#/definitions/io.k8s.api.core.v1.Lifecycle", - "description": "Actions that the management system should take in response to container lifecycle events. Cannot be updated." - }, - "livenessProbe": { - "$ref": "#/definitions/io.k8s.api.core.v1.Probe", - "description": "Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes" - }, - "name": { - "description": "Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.", - "type": "string" - }, - "ports": { - "description": "List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerPort" - }, - "type": "array", - "x-kubernetes-list-map-keys": [ - "containerPort", - "protocol" - ], - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "containerPort", - "x-kubernetes-patch-strategy": "merge" - }, - "readinessProbe": { - "$ref": "#/definitions/io.k8s.api.core.v1.Probe", - "description": "Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes" - }, - "resources": { - "$ref": "#/definitions/io.k8s.api.core.v1.ResourceRequirements", - "description": "Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/" - }, - "securityContext": { - "$ref": "#/definitions/io.k8s.api.core.v1.SecurityContext", - "description": "Security options the pod should run with. More info: https://kubernetes.io/docs/concepts/policy/security-context/ More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/" - }, - "startupProbe": { - "$ref": "#/definitions/io.k8s.api.core.v1.Probe", - "description": "StartupProbe indicates that the Pod has successfully initialized. If specified, no other probes are executed until this completes successfully. If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, when it might take a long time to load data or warm a cache, than during steady-state operation. This cannot be updated. This is an alpha feature enabled by the StartupProbe feature flag. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes" - }, - "stdin": { - "description": "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - "type": "boolean" - }, - "stdinOnce": { - "description": "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - "type": "boolean" - }, - "terminationMessagePath": { - "description": "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - "type": "string" - }, - "terminationMessagePolicy": { - "description": "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.", - "type": "string" - }, - "tty": { - "description": "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - "type": "boolean" - }, - "volumeDevices": { - "description": "volumeDevices is the list of block devices to be used by the container. This is a beta feature.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.VolumeDevice" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge" - }, - "volumeMounts": { - "description": "Pod volumes to mount into the container's filesystem. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.VolumeMount" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge" - }, - "workingDir": { - "description": "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ContainerImage": { - "description": "Describe a container image", - "properties": { - "names": { - "description": "Names by which this image is known. e.g. [\"registry.k8s.io/hyperkube:v1.0.7\", \"dockerhub.io/google_containers/hyperkube:v1.0.7\"]", - "items": { - "type": "string" - }, - "type": "array" - }, - "sizeBytes": { - "description": "The size of the image in bytes.", - "format": "int64", - "type": "integer" - } - }, - "required": [ - "names" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ContainerPort": { - "description": "ContainerPort represents a network port in a single container.", - "properties": { - "containerPort": { - "description": "Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.", - "format": "int32", - "type": "integer" - }, - "hostIP": { - "description": "What host IP to bind the external port to.", - "type": "string" - }, - "hostPort": { - "description": "Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.", - "format": "int32", - "type": "integer" - }, - "name": { - "description": "If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services.", - "type": "string" - }, - "protocol": { - "description": "Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \"TCP\".", - "type": "string" - } - }, - "required": [ - "containerPort" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ContainerState": { - "description": "ContainerState holds a possible state of container. Only one of its members may be specified. If none of them is specified, the default one is ContainerStateWaiting.", - "properties": { - "running": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerStateRunning", - "description": "Details about a running container" - }, - "terminated": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerStateTerminated", - "description": "Details about a terminated container" - }, - "waiting": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerStateWaiting", - "description": "Details about a waiting container" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ContainerStateRunning": { - "description": "ContainerStateRunning is a running state of a container.", - "properties": { - "startedAt": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Time at which the container was last (re-)started" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ContainerStateTerminated": { - "description": "ContainerStateTerminated is a terminated state of a container.", - "properties": { - "containerID": { - "description": "Container's ID in the format 'docker://'", - "type": "string" - }, - "exitCode": { - "description": "Exit status from the last termination of the container", - "format": "int32", - "type": "integer" - }, - "finishedAt": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Time at which the container last terminated" - }, - "message": { - "description": "Message regarding the last termination of the container", - "type": "string" - }, - "reason": { - "description": "(brief) reason from the last termination of the container", - "type": "string" - }, - "signal": { - "description": "Signal from the last termination of the container", - "format": "int32", - "type": "integer" - }, - "startedAt": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Time at which previous execution of the container started" - } - }, - "required": [ - "exitCode" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ContainerStateWaiting": { - "description": "ContainerStateWaiting is a waiting state of a container.", - "properties": { - "message": { - "description": "Message regarding why the container is not yet running.", - "type": "string" - }, - "reason": { - "description": "(brief) reason the container is not yet running.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ContainerStatus": { - "description": "ContainerStatus contains details for the current status of this container.", - "properties": { - "containerID": { - "description": "Container's ID in the format 'docker://'.", - "type": "string" - }, - "image": { - "description": "The image the container is running. More info: https://kubernetes.io/docs/concepts/containers/images", - "type": "string" - }, - "imageID": { - "description": "ImageID of the container's image.", - "type": "string" - }, - "lastState": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerState", - "description": "Details about the container's last termination condition." - }, - "name": { - "description": "This must be a DNS_LABEL. Each container in a pod must have a unique name. Cannot be updated.", - "type": "string" - }, - "ready": { - "description": "Specifies whether the container has passed its readiness probe.", - "type": "boolean" - }, - "restartCount": { - "description": "The number of times the container has been restarted, currently based on the number of dead containers that have not yet been removed. Note that this is calculated from dead containers. But those containers are subject to garbage collection. This value will get capped at 5 by GC.", - "format": "int32", - "type": "integer" - }, - "started": { - "description": "Specifies whether the container has passed its startup probe. Initialized as false, becomes true after startupProbe is considered successful. Resets to false when the container is restarted, or if kubelet loses state temporarily. Is always true when no startupProbe is defined.", - "type": "boolean" - }, - "state": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerState", - "description": "Details about the container's current condition." - } - }, - "required": [ - "name", - "ready", - "restartCount", - "image", - "imageID" - ], - "type": "object" - }, - "io.k8s.api.core.v1.DownwardAPIProjection": { - "description": "Represents downward API info for projecting into a projected volume. Note that this is identical to a downwardAPI volume source without the default mode.", - "properties": { - "items": { - "description": "Items is a list of DownwardAPIVolume file", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.DownwardAPIVolumeFile" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.DownwardAPIVolumeFile": { - "description": "DownwardAPIVolumeFile represents information to create the file containing the pod field", - "properties": { - "fieldRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.ObjectFieldSelector", - "description": "Required: Selects a field of the pod: only annotations, labels, name and namespace are supported." - }, - "mode": { - "description": "Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - "format": "int32", - "type": "integer" - }, - "path": { - "description": "Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'", - "type": "string" - }, - "resourceFieldRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.ResourceFieldSelector", - "description": "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, requests.cpu and requests.memory) are currently supported." - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.DownwardAPIVolumeSource": { - "description": "DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling.", - "properties": { - "defaultMode": { - "description": "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - "format": "int32", - "type": "integer" - }, - "items": { - "description": "Items is a list of downward API volume file", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.DownwardAPIVolumeFile" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.EmptyDirVolumeSource": { - "description": "Represents an empty directory for a pod. Empty directory volumes support ownership management and SELinux relabeling.", - "properties": { - "medium": { - "description": "What type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir", - "type": "string" - }, - "sizeLimit": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.api.resource.Quantity", - "description": "Total amount of local storage required for this EmptyDir volume. The size limit is also applicable for memory medium. The maximum usage on memory medium EmptyDir would be the minimum value between the SizeLimit specified here and the sum of memory limits of all containers in a pod. The default is nil which means that the limit is undefined. More info: http://kubernetes.io/docs/user-guide/volumes#emptydir" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.EnvFromSource": { - "description": "EnvFromSource represents the source of a set of ConfigMaps", - "properties": { - "configMapRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.ConfigMapEnvSource", - "description": "The ConfigMap to select from" - }, - "prefix": { - "description": "An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.", - "type": "string" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.SecretEnvSource", - "description": "The Secret to select from" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.EnvVar": { - "description": "EnvVar represents an environment variable present in a Container.", - "properties": { - "name": { - "description": "Name of the environment variable. Must be a C_IDENTIFIER.", - "type": "string" - }, - "value": { - "description": "Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to \"\".", - "type": "string" - }, - "valueFrom": { - "$ref": "#/definitions/io.k8s.api.core.v1.EnvVarSource", - "description": "Source for the environment variable's value. Cannot be used if value is not empty." - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "io.k8s.api.core.v1.EnvVarSource": { - "description": "EnvVarSource represents a source for the value of an EnvVar.", - "properties": { - "configMapKeyRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.ConfigMapKeySelector", - "description": "Selects a key of a ConfigMap." - }, - "fieldRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.ObjectFieldSelector", - "description": "Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP, status.podIPs." - }, - "resourceFieldRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.ResourceFieldSelector", - "description": "Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported." - }, - "secretKeyRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.SecretKeySelector", - "description": "Selects a key of a secret in the pod's namespace" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.EphemeralContainer": { - "description": "An EphemeralContainer is a container that may be added temporarily to an existing pod for user-initiated activities such as debugging. Ephemeral containers have no resource or scheduling guarantees, and they will not be restarted when they exit or when a pod is removed or restarted. If an ephemeral container causes a pod to exceed its resource allocation, the pod may be evicted. Ephemeral containers may not be added by directly updating the pod spec. They must be added via the pod's ephemeralcontainers subresource, and they will appear in the pod spec once added.", - "properties": { - "args": { - "description": "Arguments to the entrypoint. The container image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - "items": { - "type": "string" - }, - "type": "array" - }, - "command": { - "description": "Entrypoint array. Not executed within a shell. The container image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell", - "items": { - "type": "string" - }, - "type": "array" - }, - "env": { - "description": "List of environment variables to set in the container. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.EnvVar" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" - }, - "envFrom": { - "description": "List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.EnvFromSource" - }, - "type": "array" - }, - "image": { - "description": "Docker image name. More info: https://kubernetes.io/docs/concepts/containers/images", - "type": "string" - }, - "imagePullPolicy": { - "description": "Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images", - "type": "string" - }, - "lifecycle": { - "$ref": "#/definitions/io.k8s.api.core.v1.Lifecycle", - "description": "Lifecycle is not allowed for ephemeral containers." - }, - "livenessProbe": { - "$ref": "#/definitions/io.k8s.api.core.v1.Probe", - "description": "Probes are not allowed for ephemeral containers." - }, - "name": { - "description": "Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.", - "type": "string" - }, - "ports": { - "description": "Ports are not allowed for ephemeral containers.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerPort" - }, - "type": "array" - }, - "readinessProbe": { - "$ref": "#/definitions/io.k8s.api.core.v1.Probe", - "description": "Probes are not allowed for ephemeral containers." - }, - "resources": { - "$ref": "#/definitions/io.k8s.api.core.v1.ResourceRequirements", - "description": "Resources are not allowed for ephemeral containers. Ephemeral containers use spare resources already allocated to the pod." - }, - "securityContext": { - "$ref": "#/definitions/io.k8s.api.core.v1.SecurityContext", - "description": "SecurityContext is not allowed for ephemeral containers." - }, - "startupProbe": { - "$ref": "#/definitions/io.k8s.api.core.v1.Probe", - "description": "Probes are not allowed for ephemeral containers." - }, - "stdin": { - "description": "Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.", - "type": "boolean" - }, - "stdinOnce": { - "description": "Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", - "type": "boolean" - }, - "targetContainerName": { - "description": "If set, the name of the container from PodSpec that this ephemeral container targets. The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. If not set then the ephemeral container is run in whatever namespaces are shared for the pod. Note that the container runtime must support this feature.", - "type": "string" - }, - "terminationMessagePath": { - "description": "Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", - "type": "string" - }, - "terminationMessagePolicy": { - "description": "Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.", - "type": "string" - }, - "tty": { - "description": "Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.", - "type": "boolean" - }, - "volumeDevices": { - "description": "volumeDevices is the list of block devices to be used by the container. This is a beta feature.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.VolumeDevice" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "devicePath", - "x-kubernetes-patch-strategy": "merge" - }, - "volumeMounts": { - "description": "Pod volumes to mount into the container's filesystem. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.VolumeMount" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "mountPath", - "x-kubernetes-patch-strategy": "merge" - }, - "workingDir": { - "description": "Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ExecAction": { - "description": "ExecAction describes a \"run in container\" action.", - "properties": { - "command": { - "description": "Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.FCVolumeSource": { - "description": "Represents a Fibre Channel volume. Fibre Channel volumes can only be mounted as read/write once. Fibre Channel volumes support ownership management and SELinux relabeling.", - "properties": { - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - "type": "string" - }, - "lun": { - "description": "Optional: FC target lun number", - "format": "int32", - "type": "integer" - }, - "readOnly": { - "description": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - }, - "targetWWNs": { - "description": "Optional: FC target worldwide names (WWNs)", - "items": { - "type": "string" - }, - "type": "array" - }, - "wwids": { - "description": "Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.FlexVolumeSource": { - "description": "FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin.", - "properties": { - "driver": { - "description": "Driver is the name of the driver to use for this volume.", - "type": "string" - }, - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", - "type": "string" - }, - "options": { - "additionalProperties": { - "type": "string" - }, - "description": "Optional: Extra command options if any.", - "type": "object" - }, - "readOnly": { - "description": "Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "Optional: SecretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts." - } - }, - "required": [ - "driver" - ], - "type": "object" - }, - "io.k8s.api.core.v1.FlockerVolumeSource": { - "description": "Represents a Flocker volume mounted by the Flocker agent. One and only one of datasetName and datasetUUID should be set. Flocker volumes do not support ownership management or SELinux relabeling.", - "properties": { - "datasetName": { - "description": "Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated", - "type": "string" - }, - "datasetUUID": { - "description": "UUID of the dataset. This is unique identifier of a Flocker dataset", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.GCEPersistentDiskVolumeSource": { - "description": "Represents a Persistent Disk resource in Google Compute Engine.\n\nA GCE PD must exist before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once or read-only many times. GCE PDs support ownership management and SELinux relabeling.", - "properties": { - "fsType": { - "description": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - "type": "string" - }, - "partition": { - "description": "The partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - "format": "int32", - "type": "integer" - }, - "pdName": { - "description": "Unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - "type": "string" - }, - "readOnly": { - "description": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", - "type": "boolean" - } - }, - "required": [ - "pdName" - ], - "type": "object" - }, - "io.k8s.api.core.v1.GitRepoVolumeSource": { - "description": "Represents a volume that is populated with the contents of a git repository. Git repo volumes do not support ownership management. Git repo volumes support SELinux relabeling.\n\nDEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container.", - "properties": { - "directory": { - "description": "Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.", - "type": "string" - }, - "repository": { - "description": "Repository URL", - "type": "string" - }, - "revision": { - "description": "Commit hash for the specified revision.", - "type": "string" - } - }, - "required": [ - "repository" - ], - "type": "object" - }, - "io.k8s.api.core.v1.GlusterfsVolumeSource": { - "description": "Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.", - "properties": { - "endpoints": { - "description": "EndpointsName is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - "type": "string" - }, - "path": { - "description": "Path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - "type": "string" - }, - "readOnly": { - "description": "ReadOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", - "type": "boolean" - } - }, - "required": [ - "endpoints", - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.HTTPGetAction": { - "description": "HTTPGetAction describes an action based on HTTP Get requests.", - "properties": { - "host": { - "description": "Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead.", - "type": "string" - }, - "httpHeaders": { - "description": "Custom headers to set in the request. HTTP allows repeated headers.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.HTTPHeader" - }, - "type": "array" - }, - "path": { - "description": "Path to access on the HTTP server.", - "type": "string" - }, - "port": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "Name or number of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME." - }, - "scheme": { - "description": "Scheme to use for connecting to the host. Defaults to HTTP.", - "type": "string" - } - }, - "required": [ - "port" - ], - "type": "object" - }, - "io.k8s.api.core.v1.HTTPHeader": { - "description": "HTTPHeader describes a custom header to be used in HTTP probes", - "properties": { - "name": { - "description": "The header field name", - "type": "string" - }, - "value": { - "description": "The header field value", - "type": "string" - } - }, - "required": [ - "name", - "value" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Handler": { - "description": "Handler defines a specific action that should be taken", - "properties": { - "exec": { - "$ref": "#/definitions/io.k8s.api.core.v1.ExecAction", - "description": "One and only one of the following should be specified. Exec specifies the action to take." - }, - "httpGet": { - "$ref": "#/definitions/io.k8s.api.core.v1.HTTPGetAction", - "description": "HTTPGet specifies the http request to perform." - }, - "tcpSocket": { - "$ref": "#/definitions/io.k8s.api.core.v1.TCPSocketAction", - "description": "TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.HostAlias": { - "description": "HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the pod's hosts file.", - "properties": { - "hostnames": { - "description": "Hostnames for the above IP address.", - "items": { - "type": "string" - }, - "type": "array" - }, - "ip": { - "description": "IP address of the host file entry.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.HostPathVolumeSource": { - "description": "Represents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling.", - "properties": { - "path": { - "description": "Path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - "type": "string" - }, - "type": { - "description": "Type for HostPath Volume Defaults to \"\" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath", - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ISCSIVolumeSource": { - "description": "Represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.", - "properties": { - "chapAuthDiscovery": { - "description": "whether support iSCSI Discovery CHAP authentication", - "type": "boolean" - }, - "chapAuthSession": { - "description": "whether support iSCSI Session CHAP authentication", - "type": "boolean" - }, - "fsType": { - "description": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi", - "type": "string" - }, - "initiatorName": { - "description": "Custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface : will be created for the connection.", - "type": "string" - }, - "iqn": { - "description": "Target iSCSI Qualified Name.", - "type": "string" - }, - "iscsiInterface": { - "description": "iSCSI Interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).", - "type": "string" - }, - "lun": { - "description": "iSCSI Target Lun number.", - "format": "int32", - "type": "integer" - }, - "portals": { - "description": "iSCSI Target Portal List. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - "items": { - "type": "string" - }, - "type": "array" - }, - "readOnly": { - "description": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", - "type": "boolean" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "CHAP Secret for iSCSI target and initiator authentication" - }, - "targetPortal": { - "description": "iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", - "type": "string" - } - }, - "required": [ - "targetPortal", - "iqn", - "lun" - ], - "type": "object" - }, - "io.k8s.api.core.v1.KeyToPath": { - "description": "Maps a string key to a path within a volume.", - "properties": { - "key": { - "description": "The key to project.", - "type": "string" - }, - "mode": { - "description": "Optional: mode bits to use on this file, must be a value between 0 and 0777. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - "format": "int32", - "type": "integer" - }, - "path": { - "description": "The relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.", - "type": "string" - } - }, - "required": [ - "key", - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Lifecycle": { - "description": "Lifecycle describes actions that the management system should take in response to container lifecycle events. For the PostStart and PreStop lifecycle handlers, management of the container blocks until the action is complete, unless the container process fails, in which case the handler is aborted.", - "properties": { - "postStart": { - "$ref": "#/definitions/io.k8s.api.core.v1.Handler", - "description": "PostStart is called immediately after a container is created. If the handler fails, the container is terminated and restarted according to its restart policy. Other management of the container blocks until the hook completes. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks" - }, - "preStop": { - "$ref": "#/definitions/io.k8s.api.core.v1.Handler", - "description": "PreStop is called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. The handler is not called if the container crashes or exits. The reason for termination is passed to the handler. The Pod's termination grace period countdown begins before the PreStop hooked is executed. Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period. Other management of the container blocks until the hook completes or until the termination grace period is reached. More info: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.LocalObjectReference": { - "description": "LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.", - "properties": { - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.LocalVolumeSource": { - "description": "Local represents directly-attached storage with node affinity (Beta feature)", - "properties": { - "fsType": { - "description": "Filesystem type to mount. It applies only when the Path is a block device. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default value is to auto-select a fileystem if unspecified.", - "type": "string" - }, - "path": { - "description": "The full path to the volume on the node. It can be either a directory or block device (disk, partition, ...).", - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.NFSVolumeSource": { - "description": "Represents an NFS mount that lasts the lifetime of a pod. NFS volumes do not support ownership management or SELinux relabeling.", - "properties": { - "path": { - "description": "Path that is exported by the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - "type": "string" - }, - "readOnly": { - "description": "ReadOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - "type": "boolean" - }, - "server": { - "description": "Server is the hostname or IP address of the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", - "type": "string" - } - }, - "required": [ - "server", - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.NodeAffinity": { - "description": "Node affinity is a group of node affinity scheduling rules.", - "properties": { - "preferredDuringSchedulingIgnoredDuringExecution": { - "description": "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PreferredSchedulingTerm" - }, - "type": "array" - }, - "requiredDuringSchedulingIgnoredDuringExecution": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelector", - "description": "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.NodeSelector": { - "description": "A node selector represents the union of the results of one or more label queries over a set of nodes; that is, it represents the OR of the selectors represented by the node selector terms.", - "properties": { - "nodeSelectorTerms": { - "description": "Required. A list of node selector terms. The terms are ORed.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelectorTerm" - }, - "type": "array" - } - }, - "required": [ - "nodeSelectorTerms" - ], - "type": "object" - }, - "io.k8s.api.core.v1.NodeSelectorRequirement": { - "description": "A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", - "properties": { - "key": { - "description": "The label key that the selector applies to.", - "type": "string" - }, - "operator": { - "description": "Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.", - "type": "string" - }, - "values": { - "description": "An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "key", - "operator" - ], - "type": "object" - }, - "io.k8s.api.core.v1.NodeSelectorTerm": { - "description": "A null or empty node selector term matches no objects. The requirements of them are ANDed. The TopologySelectorTerm type implements a subset of the NodeSelectorTerm.", - "properties": { - "matchExpressions": { - "description": "A list of node selector requirements by node's labels.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelectorRequirement" - }, - "type": "array" - }, - "matchFields": { - "description": "A list of node selector requirements by node's fields.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelectorRequirement" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ObjectFieldSelector": { - "description": "ObjectFieldSelector selects an APIVersioned field of an object.", - "properties": { - "apiVersion": { - "description": "Version of the schema the FieldPath is written in terms of, defaults to \"v1\".", - "type": "string" - }, - "fieldPath": { - "description": "Path of the field to select in the specified API version.", - "type": "string" - } - }, - "required": [ - "fieldPath" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ObjectReference": { - "description": "ObjectReference contains enough information to let you inspect or modify the referred object.", - "properties": { - "apiVersion": { - "description": "API version of the referent.", - "type": "string" - }, - "fieldPath": { - "description": "If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: \"spec.containers{name}\" (where \"name\" refers to the name of the container that triggered the event) or if no container name is specified \"spec.containers[2]\" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object.", - "type": "string" - }, - "kind": { - "description": "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "namespace": { - "description": "Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/", - "type": "string" - }, - "resourceVersion": { - "description": "Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - "type": "string" - }, - "uid": { - "description": "UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PersistentVolumeClaimVolumeSource": { - "description": "PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace. This volume finds the bound PV and mounts that volume for the pod. A PersistentVolumeClaimVolumeSource is, essentially, a wrapper around another type of volume that is owned by someone else (the system).", - "properties": { - "claimName": { - "description": "ClaimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", - "type": "string" - }, - "readOnly": { - "description": "Will force the ReadOnly setting in VolumeMounts. Default false.", - "type": "boolean" - } - }, - "required": [ - "claimName" - ], - "type": "object" - }, - "io.k8s.api.core.v1.PhotonPersistentDiskVolumeSource": { - "description": "Represents a Photon Controller persistent disk resource.", - "properties": { - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - "type": "string" - }, - "pdID": { - "description": "ID that identifies Photon Controller persistent disk", - "type": "string" - } - }, - "required": [ - "pdID" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Pod": { - "description": "Pod is a collection of containers that can run on a host. This resource is created by clients and scheduled onto hosts.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "spec": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodSpec", - "description": "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - }, - "status": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodStatus", - "description": "Most recently observed status of the pod. This data may not be up to date. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "", - "kind": "Pod", - "version": "v1" - } - ] - }, - "io.k8s.api.core.v1.PodAffinity": { - "description": "Pod affinity is a group of inter pod affinity scheduling rules.", - "properties": { - "preferredDuringSchedulingIgnoredDuringExecution": { - "description": "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.WeightedPodAffinityTerm" - }, - "type": "array" - }, - "requiredDuringSchedulingIgnoredDuringExecution": { - "description": "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodAffinityTerm" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodAffinityTerm": { - "description": "Defines a set of pods (namely those matching the labelSelector relative to the given namespace(s)) that this pod should be co-located (affinity) or not co-located (anti-affinity) with, where co-located is defined as running on a node whose value of the label with key matches that of any node on which a pod of the set of pods is running", - "properties": { - "labelSelector": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector", - "description": "A label query over a set of resources, in this case pods." - }, - "namespaces": { - "description": "namespaces specifies which namespaces the labelSelector applies to (matches against); null or empty list means \"this pod's namespace\"", - "items": { - "type": "string" - }, - "type": "array" - }, - "topologyKey": { - "description": "This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed.", - "type": "string" - } - }, - "required": [ - "topologyKey" - ], - "type": "object" - }, - "io.k8s.api.core.v1.PodAntiAffinity": { - "description": "Pod anti affinity is a group of inter pod anti affinity scheduling rules.", - "properties": { - "preferredDuringSchedulingIgnoredDuringExecution": { - "description": "The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.WeightedPodAffinityTerm" - }, - "type": "array" - }, - "requiredDuringSchedulingIgnoredDuringExecution": { - "description": "If the anti-affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the anti-affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodAffinityTerm" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodCondition": { - "description": "PodCondition contains details for the current condition of this pod.", - "properties": { - "lastProbeTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Last time we probed the condition." - }, - "lastTransitionTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Last time the condition transitioned from one status to another." - }, - "message": { - "description": "Human-readable message indicating details about last transition.", - "type": "string" - }, - "reason": { - "description": "Unique, one-word, CamelCase reason for the condition's last transition.", - "type": "string" - }, - "status": { - "description": "Status is the status of the condition. Can be True, False, Unknown. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - "type": "string" - }, - "type": { - "description": "Type is the type of the condition. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - "type": "string" - } - }, - "required": [ - "type", - "status" - ], - "type": "object" - }, - "io.k8s.api.core.v1.PodDNSConfig": { - "description": "PodDNSConfig defines the DNS parameters of a pod in addition to those generated from DNSPolicy.", - "properties": { - "nameservers": { - "description": "A list of DNS name server IP addresses. This will be appended to the base nameservers generated from DNSPolicy. Duplicated nameservers will be removed.", - "items": { - "type": "string" - }, - "type": "array" - }, - "options": { - "description": "A list of DNS resolver options. This will be merged with the base options generated from DNSPolicy. Duplicated entries will be removed. Resolution options given in Options will override those that appear in the base DNSPolicy.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodDNSConfigOption" - }, - "type": "array" - }, - "searches": { - "description": "A list of DNS search domains for host-name lookup. This will be appended to the base search paths generated from DNSPolicy. Duplicated search paths will be removed.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodDNSConfigOption": { - "description": "PodDNSConfigOption defines DNS resolver options of a pod.", - "properties": { - "name": { - "description": "Required.", - "type": "string" - }, - "value": { - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodIP": { - "description": "IP address information for entries in the (plural) PodIPs field. Each entry includes:\n IP: An IP address allocated to the pod. Routable at least within the cluster.", - "properties": { - "ip": { - "description": "ip is an IP address (IPv4 or IPv6) assigned to the pod", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodReadinessGate": { - "description": "PodReadinessGate contains the reference to a pod condition", - "properties": { - "conditionType": { - "description": "ConditionType refers to a condition in the pod's condition list with matching type.", - "type": "string" - } - }, - "required": [ - "conditionType" - ], - "type": "object" - }, - "io.k8s.api.core.v1.PodSecurityContext": { - "description": "PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext. Field values of container.securityContext take precedence over field values of PodSecurityContext.", - "properties": { - "fsGroup": { - "description": "A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:\n\n1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw----\n\nIf unset, the Kubelet will not modify the ownership and permissions of any volume.", - "format": "int64", - "type": "integer" - }, - "runAsGroup": { - "description": "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.", - "format": "int64", - "type": "integer" - }, - "runAsNonRoot": { - "description": "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - "type": "boolean" - }, - "runAsUser": { - "description": "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.", - "format": "int64", - "type": "integer" - }, - "seLinuxOptions": { - "$ref": "#/definitions/io.k8s.api.core.v1.SELinuxOptions", - "description": "The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container." - }, - "supplementalGroups": { - "description": "A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.", - "items": { - "format": "int64", - "type": "integer" - }, - "type": "array" - }, - "sysctls": { - "description": "Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.Sysctl" - }, - "type": "array" - }, - "windowsOptions": { - "$ref": "#/definitions/io.k8s.api.core.v1.WindowsSecurityContextOptions", - "description": "The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodSpec": { - "description": "PodSpec is a description of a pod.", - "properties": { - "activeDeadlineSeconds": { - "description": "Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", - "format": "int64", - "type": "integer" - }, - "affinity": { - "$ref": "#/definitions/io.k8s.api.core.v1.Affinity", - "description": "If specified, the pod's scheduling constraints" - }, - "automountServiceAccountToken": { - "description": "AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.", - "type": "boolean" - }, - "containers": { - "description": "List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.Container" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" - }, - "dnsConfig": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodDNSConfig", - "description": "Specifies the DNS parameters of a pod. Parameters specified here will be merged to the generated DNS configuration based on DNSPolicy." - }, - "dnsPolicy": { - "description": "Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'.", - "type": "string" - }, - "enableServiceLinks": { - "description": "EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.", - "type": "boolean" - }, - "ephemeralContainers": { - "description": "List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.EphemeralContainer" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" - }, - "hostAliases": { - "description": "HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.HostAlias" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge" - }, - "hostIPC": { - "description": "Use the host's ipc namespace. Optional: Default to false.", - "type": "boolean" - }, - "hostNetwork": { - "description": "Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", - "type": "boolean" - }, - "hostPID": { - "description": "Use the host's pid namespace. Optional: Default to false.", - "type": "boolean" - }, - "hostname": { - "description": "Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.", - "type": "string" - }, - "imagePullSecrets": { - "description": "ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" - }, - "initContainers": { - "description": "List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.Container" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge" - }, - "nodeName": { - "description": "NodeName is a request to schedule this pod onto a specific node. If it is non-empty, the scheduler simply schedules this pod onto that node, assuming that it fits resource requirements.", - "type": "string" - }, - "nodeSelector": { - "additionalProperties": { - "type": "string" - }, - "description": "NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/", - "type": "object" - }, - "overhead": { - "additionalProperties": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.api.resource.Quantity" - }, - "description": "Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead This field is alpha-level as of Kubernetes v1.16, and is only honored by servers that enable the PodOverhead feature.", - "type": "object" - }, - "preemptionPolicy": { - "description": "PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset. This field is alpha-level and is only honored by servers that enable the NonPreemptingPriority feature.", - "type": "string" - }, - "priority": { - "description": "The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority.", - "format": "int32", - "type": "integer" - }, - "priorityClassName": { - "description": "If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.", - "type": "string" - }, - "readinessGates": { - "description": "If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodReadinessGate" - }, - "type": "array" - }, - "restartPolicy": { - "description": "Restart policy for all containers within the pod. One of Always, OnFailure, Never. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy", - "type": "string" - }, - "runtimeClassName": { - "description": "RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class This is a beta feature as of Kubernetes v1.14.", - "type": "string" - }, - "schedulerName": { - "description": "If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler.", - "type": "string" - }, - "securityContext": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodSecurityContext", - "description": "SecurityContext holds pod-level security attributes and common container settings. Optional: Defaults to empty. See type description for default values of each field." - }, - "serviceAccount": { - "description": "DeprecatedServiceAccount is a depreciated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead.", - "type": "string" - }, - "serviceAccountName": { - "description": "ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", - "type": "string" - }, - "shareProcessNamespace": { - "description": "Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false.", - "type": "boolean" - }, - "subdomain": { - "description": "If specified, the fully qualified Pod hostname will be \"...svc.\". If not specified, the pod will not have a domainname at all.", - "type": "string" - }, - "terminationGracePeriodSeconds": { - "description": "Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.", - "format": "int64", - "type": "integer" - }, - "tolerations": { - "description": "If specified, the pod's tolerations.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.Toleration" - }, - "type": "array" - }, - "topologySpreadConstraints": { - "description": "TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.TopologySpreadConstraint" - }, - "type": "array", - "x-kubernetes-list-map-keys": [ - "topologyKey", - "whenUnsatisfiable" - ], - "x-kubernetes-list-type": "map", - "x-kubernetes-patch-merge-key": "topologyKey", - "x-kubernetes-patch-strategy": "merge" - }, - "volumes": { - "description": "List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.Volume" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "name", - "x-kubernetes-patch-strategy": "merge,retainKeys" - } - }, - "required": [ - "containers" - ], - "type": "object" - }, - "io.k8s.api.core.v1.PodStatus": { - "description": "PodStatus represents information about the status of a pod. Status may trail the actual state of a system, especially if the node that hosts the pod cannot contact the control plane.", - "properties": { - "conditions": { - "description": "Current service state of pod. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-conditions", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodCondition" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - }, - "containerStatuses": { - "description": "The list has one entry per container in the manifest. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerStatus" - }, - "type": "array" - }, - "ephemeralContainerStatuses": { - "description": "Status for any ephemeral containers that have run in this pod.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerStatus" - }, - "type": "array" - }, - "hostIP": { - "description": "IP address of the host to which the pod is assigned. Empty if not yet scheduled.", - "type": "string" - }, - "initContainerStatuses": { - "description": "The list has one entry per init container in the manifest. The most recent successful init container will have ready = true, the most recently started container will have startTime set. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-and-container-status", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.ContainerStatus" - }, - "type": "array" - }, - "message": { - "description": "A human readable message indicating details about why the pod is in this condition.", - "type": "string" - }, - "nominatedNodeName": { - "description": "nominatedNodeName is set only when this pod preempts other pods on the node, but it cannot be scheduled right away as preemption victims receive their graceful termination periods. This field does not guarantee that the pod will be scheduled on this node. Scheduler may decide to place the pod elsewhere if other nodes become available sooner. Scheduler may also decide to give the resources on this node to a higher priority pod that is created after preemption. As a result, this field may be different than PodSpec.nodeName when the pod is scheduled.", - "type": "string" - }, - "phase": { - "description": "The phase of a Pod is a simple, high-level summary of where the Pod is in its lifecycle. The conditions array, the reason and message fields, and the individual container status arrays contain more detail about the pod's status. There are five possible phase values:\n\nPending: The pod has been accepted by the Kubernetes system, but one or more of the container images has not been created. This includes time before being scheduled as well as time spent downloading images over the network, which could take a while. Running: The pod has been bound to a node, and all of the containers have been created. At least one container is still running, or is in the process of starting or restarting. Succeeded: All containers in the pod have terminated in success, and will not be restarted. Failed: All containers in the pod have terminated, and at least one container has terminated in failure. The container either exited with non-zero status or was terminated by the system. Unknown: For some reason the state of the pod could not be obtained, typically due to an error in communicating with the host of the pod.\n\nMore info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#pod-phase", - "type": "string" - }, - "podIP": { - "description": "IP address allocated to the pod. Routable at least within the cluster. Empty if not yet allocated.", - "type": "string" - }, - "podIPs": { - "description": "podIPs holds the IP addresses allocated to the pod. If this field is specified, the 0th entry must match the podIP field. Pods may be allocated at most 1 value for each of IPv4 and IPv6. This list is empty if no IPs have been allocated yet.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodIP" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "ip", - "x-kubernetes-patch-strategy": "merge" - }, - "qosClass": { - "description": "The Quality of Service (QOS) classification assigned to the pod based on resource requirements See PodQOSClass type for available QOS classes More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/#quality-of-service-classes", - "type": "string" - }, - "reason": { - "description": "A brief CamelCase message indicating details about why the pod is in this state. e.g. 'Evicted'", - "type": "string" - }, - "startTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "RFC 3339 date and time at which the object was acknowledged by the Kubelet. This is before the Kubelet pulled the container image(s) for the pod." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PodTemplate": { - "description": "PodTemplate describes a template for creating copies of a predefined pod.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "template": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodTemplateSpec", - "description": "Template defines the pods that will be created from this pod template. https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "", - "kind": "PodTemplate", - "version": "v1" - } - ] - }, - "io.k8s.api.core.v1.PodTemplateSpec": { - "description": "PodTemplateSpec describes the data a pod should have when created from a template", - "properties": { - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "spec": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodSpec", - "description": "Specification of the desired behavior of the pod. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.PortworxVolumeSource": { - "description": "PortworxVolumeSource represents a Portworx volume resource.", - "properties": { - "fsType": { - "description": "FSType represents the filesystem type to mount Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\". Implicitly inferred to be \"ext4\" if unspecified.", - "type": "string" - }, - "readOnly": { - "description": "Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - }, - "volumeID": { - "description": "VolumeID uniquely identifies a Portworx volume", - "type": "string" - } - }, - "required": [ - "volumeID" - ], - "type": "object" - }, - "io.k8s.api.core.v1.PreferredSchedulingTerm": { - "description": "An empty preferred scheduling term matches all objects with implicit weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op).", - "properties": { - "preference": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelectorTerm", - "description": "A node selector term, associated with the corresponding weight." - }, - "weight": { - "description": "Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100.", - "format": "int32", - "type": "integer" - } - }, - "required": [ - "weight", - "preference" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Probe": { - "description": "Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic.", - "properties": { - "exec": { - "$ref": "#/definitions/io.k8s.api.core.v1.ExecAction", - "description": "One and only one of the following should be specified. Exec specifies the action to take." - }, - "failureThreshold": { - "description": "Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.", - "format": "int32", - "type": "integer" - }, - "httpGet": { - "$ref": "#/definitions/io.k8s.api.core.v1.HTTPGetAction", - "description": "HTTPGet specifies the http request to perform." - }, - "initialDelaySeconds": { - "description": "Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - "format": "int32", - "type": "integer" - }, - "periodSeconds": { - "description": "How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.", - "format": "int32", - "type": "integer" - }, - "successThreshold": { - "description": "Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.", - "format": "int32", - "type": "integer" - }, - "tcpSocket": { - "$ref": "#/definitions/io.k8s.api.core.v1.TCPSocketAction", - "description": "TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported" - }, - "timeoutSeconds": { - "description": "Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ProjectedVolumeSource": { - "description": "Represents a projected volume source", - "properties": { - "defaultMode": { - "description": "Mode bits to use on created files by default. Must be a value between 0 and 0777. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - "format": "int32", - "type": "integer" - }, - "sources": { - "description": "list of volume projections", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.VolumeProjection" - }, - "type": "array" - } - }, - "required": [ - "sources" - ], - "type": "object" - }, - "io.k8s.api.core.v1.QuobyteVolumeSource": { - "description": "Represents a Quobyte mount that lasts the lifetime of a pod. Quobyte volumes do not support ownership management or SELinux relabeling.", - "properties": { - "group": { - "description": "Group to map volume access to Default is no group", - "type": "string" - }, - "readOnly": { - "description": "ReadOnly here will force the Quobyte volume to be mounted with read-only permissions. Defaults to false.", - "type": "boolean" - }, - "registry": { - "description": "Registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes", - "type": "string" - }, - "tenant": { - "description": "Tenant owning the given Quobyte volume in the Backend Used with dynamically provisioned Quobyte volumes, value is set by the plugin", - "type": "string" - }, - "user": { - "description": "User to map volume access to Defaults to serivceaccount user", - "type": "string" - }, - "volume": { - "description": "Volume is a string that references an already created Quobyte volume by name.", - "type": "string" - } - }, - "required": [ - "registry", - "volume" - ], - "type": "object" - }, - "io.k8s.api.core.v1.RBDVolumeSource": { - "description": "Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.", - "properties": { - "fsType": { - "description": "Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd", - "type": "string" - }, - "image": { - "description": "The rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - "type": "string" - }, - "keyring": { - "description": "Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - "type": "string" - }, - "monitors": { - "description": "A collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - "items": { - "type": "string" - }, - "type": "array" - }, - "pool": { - "description": "The rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - "type": "string" - }, - "readOnly": { - "description": "ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - "type": "boolean" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it" - }, - "user": { - "description": "The rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", - "type": "string" - } - }, - "required": [ - "monitors", - "image" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ResourceFieldSelector": { - "description": "ResourceFieldSelector represents container resources (cpu, memory) and their output format", - "properties": { - "containerName": { - "description": "Container name: required for volumes, optional for env vars", - "type": "string" - }, - "divisor": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.api.resource.Quantity", - "description": "Specifies the output format of the exposed resources, defaults to \"1\"" - }, - "resource": { - "description": "Required: resource to select", - "type": "string" - } - }, - "required": [ - "resource" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ResourceRequirements": { - "description": "ResourceRequirements describes the compute resource requirements.", - "properties": { - "limits": { - "additionalProperties": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.api.resource.Quantity" - }, - "description": "Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/", - "type": "object" - }, - "requests": { - "additionalProperties": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.api.resource.Quantity" - }, - "description": "Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/", - "type": "object" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.SELinuxOptions": { - "description": "SELinuxOptions are the labels to be applied to the container", - "properties": { - "level": { - "description": "Level is SELinux level label that applies to the container.", - "type": "string" - }, - "role": { - "description": "Role is a SELinux role label that applies to the container.", - "type": "string" - }, - "type": { - "description": "Type is a SELinux type label that applies to the container.", - "type": "string" - }, - "user": { - "description": "User is a SELinux user label that applies to the container.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ScaleIOVolumeSource": { - "description": "ScaleIOVolumeSource represents a persistent ScaleIO volume", - "properties": { - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Default is \"xfs\".", - "type": "string" - }, - "gateway": { - "description": "The host address of the ScaleIO API Gateway.", - "type": "string" - }, - "protectionDomain": { - "description": "The name of the ScaleIO Protection Domain for the configured storage.", - "type": "string" - }, - "readOnly": { - "description": "Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "SecretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail." - }, - "sslEnabled": { - "description": "Flag to enable/disable SSL communication with Gateway, default false", - "type": "boolean" - }, - "storageMode": { - "description": "Indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.", - "type": "string" - }, - "storagePool": { - "description": "The ScaleIO Storage Pool associated with the protection domain.", - "type": "string" - }, - "system": { - "description": "The name of the storage system as configured in ScaleIO.", - "type": "string" - }, - "volumeName": { - "description": "The name of a volume already created in the ScaleIO system that is associated with this volume source.", - "type": "string" - } - }, - "required": [ - "gateway", - "system", - "secretRef" - ], - "type": "object" - }, - "io.k8s.api.core.v1.ScopeSelector": { - "description": "A scope selector represents the AND of the selectors represented by the scoped-resource selector requirements.", - "properties": { - "matchExpressions": { - "description": "A list of scope selector requirements by scope of the resources.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.ScopedResourceSelectorRequirement" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ScopedResourceSelectorRequirement": { - "description": "A scoped-resource selector requirement is a selector that contains values, a scope name, and an operator that relates the scope name and values.", - "properties": { - "operator": { - "description": "Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist.", - "type": "string" - }, - "scopeName": { - "description": "The name of the scope that the selector applies to.", - "type": "string" - }, - "values": { - "description": "An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "scopeName", - "operator" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Secret": { - "description": "Secret holds secret data of a certain type. The total bytes of the values in the Data field must be less than MaxSecretSize bytes.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "data": { - "additionalProperties": { - "format": "byte", - "type": "string" - }, - "description": "Data contains the secret data. Each key must consist of alphanumeric characters, '-', '_' or '.'. The serialized form of the secret data is a base64 encoded string, representing the arbitrary (possibly non-string) data value here. Described in https://tools.ietf.org/html/rfc4648#section-4", - "type": "object" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "stringData": { - "additionalProperties": { - "type": "string" - }, - "description": "stringData allows specifying non-binary secret data in string form. It is provided as a write-only input field for convenience. All keys and values are merged into the data field on write, overwriting any existing values. The stringData field is never output when reading from the API.", - "type": "object" - }, - "type": { - "description": "Used to facilitate programmatic handling of secret data.", - "type": "string" - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "", - "kind": "Secret", - "version": "v1" - } - ] - }, - "io.k8s.api.core.v1.SecretEnvSource": { - "description": "SecretEnvSource selects a Secret to populate the environment variables with.\n\nThe contents of the target Secret's Data field will represent the key-value pairs as environment variables.", - "properties": { - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the Secret must be defined", - "type": "boolean" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.SecretKeySelector": { - "description": "SecretKeySelector selects a key of a Secret.", - "properties": { - "key": { - "description": "The key of the secret to select from. Must be a valid secret key.", - "type": "string" - }, - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the Secret or its key must be defined", - "type": "boolean" - } - }, - "required": [ - "key" - ], - "type": "object" - }, - "io.k8s.api.core.v1.SecretProjection": { - "description": "Adapts a secret into a projected volume.\n\nThe contents of the target Secret's Data field will be presented in a projected volume as files using the keys in the Data field as the file names. Note that this is identical to a secret volume source without the default mode.", - "properties": { - "items": { - "description": "If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.KeyToPath" - }, - "type": "array" - }, - "name": { - "description": "Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "optional": { - "description": "Specify whether the Secret or its key must be defined", - "type": "boolean" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.SecretReference": { - "description": "SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace", - "properties": { - "name": { - "description": "Name is unique within a namespace to reference a secret resource.", - "type": "string" - }, - "namespace": { - "description": "Namespace defines the space within which the secret name must be unique.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.SecretVolumeSource": { - "description": "Adapts a Secret into a volume.\n\nThe contents of the target Secret's Data field will be presented in a volume as files using the keys in the Data field as the file names. Secret volumes support ownership management and SELinux relabeling.", - "properties": { - "defaultMode": { - "description": "Optional: mode bits to use on created files by default. Must be a value between 0 and 0777. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", - "format": "int32", - "type": "integer" - }, - "items": { - "description": "If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.KeyToPath" - }, - "type": "array" - }, - "optional": { - "description": "Specify whether the Secret or its keys must be defined", - "type": "boolean" - }, - "secretName": { - "description": "Name of the secret in the pod's namespace to use. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.SecurityContext": { - "description": "SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext. When both are set, the values in SecurityContext take precedence.", - "properties": { - "allowPrivilegeEscalation": { - "description": "AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN", - "type": "boolean" - }, - "capabilities": { - "$ref": "#/definitions/io.k8s.api.core.v1.Capabilities", - "description": "The capabilities to add/drop when running containers. Defaults to the default set of capabilities granted by the container runtime." - }, - "privileged": { - "description": "Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false.", - "type": "boolean" - }, - "procMount": { - "description": "procMount denotes the type of proc mount to use for the containers. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled.", - "type": "string" - }, - "readOnlyRootFilesystem": { - "description": "Whether this container has a read-only root filesystem. Default is false.", - "type": "boolean" - }, - "runAsGroup": { - "description": "The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - "format": "int64", - "type": "integer" - }, - "runAsNonRoot": { - "description": "Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - "type": "boolean" - }, - "runAsUser": { - "description": "The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", - "format": "int64", - "type": "integer" - }, - "seLinuxOptions": { - "$ref": "#/definitions/io.k8s.api.core.v1.SELinuxOptions", - "description": "The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence." - }, - "windowsOptions": { - "$ref": "#/definitions/io.k8s.api.core.v1.WindowsSecurityContextOptions", - "description": "The Windows specific settings applied to all containers. If unspecified, the options from the PodSecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.ServiceAccountTokenProjection": { - "description": "ServiceAccountTokenProjection represents a projected service account token volume. This projection can be used to insert a service account token into the pods runtime filesystem for use against APIs (Kubernetes API Server or otherwise).", - "properties": { - "audience": { - "description": "Audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.", - "type": "string" - }, - "expirationSeconds": { - "description": "ExpirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.", - "format": "int64", - "type": "integer" - }, - "path": { - "description": "Path is the path relative to the mount point of the file to project the token into.", - "type": "string" - } - }, - "required": [ - "path" - ], - "type": "object" - }, - "io.k8s.api.core.v1.SessionAffinityConfig": { - "description": "SessionAffinityConfig represents the configurations of session affinity.", - "properties": { - "clientIP": { - "$ref": "#/definitions/io.k8s.api.core.v1.ClientIPConfig", - "description": "clientIP contains the configurations of Client IP based session affinity." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.StorageOSVolumeSource": { - "description": "Represents a StorageOS persistent volume resource.", - "properties": { - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - "type": "string" - }, - "readOnly": { - "description": "Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", - "type": "boolean" - }, - "secretRef": { - "$ref": "#/definitions/io.k8s.api.core.v1.LocalObjectReference", - "description": "SecretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted." - }, - "volumeName": { - "description": "VolumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.", - "type": "string" - }, - "volumeNamespace": { - "description": "VolumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.Sysctl": { - "description": "Sysctl defines a kernel parameter to be set", - "properties": { - "name": { - "description": "Name of a property to set", - "type": "string" - }, - "value": { - "description": "Value of a property to set", - "type": "string" - } - }, - "required": [ - "name", - "value" - ], - "type": "object" - }, - "io.k8s.api.core.v1.TCPSocketAction": { - "description": "TCPSocketAction describes an action based on opening a socket", - "properties": { - "host": { - "description": "Optional: Host name to connect to, defaults to the pod IP.", - "type": "string" - }, - "port": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "Number or name of the port to access on the container. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME." - } - }, - "required": [ - "port" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Toleration": { - "description": "The pod this Toleration is attached to tolerates any taint that matches the triple using the matching operator .", - "properties": { - "effect": { - "description": "Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.", - "type": "string" - }, - "key": { - "description": "Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys.", - "type": "string" - }, - "operator": { - "description": "Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.", - "type": "string" - }, - "tolerationSeconds": { - "description": "TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system.", - "format": "int64", - "type": "integer" - }, - "value": { - "description": "Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.TopologySelectorLabelRequirement": { - "description": "A topology selector requirement is a selector that matches given label. This is an alpha feature and may change in the future.", - "properties": { - "key": { - "description": "The label key that the selector applies to.", - "type": "string" - }, - "values": { - "description": "An array of string values. One value must match the label to be selected. Each entry in Values is ORed.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "key", - "values" - ], - "type": "object" - }, - "io.k8s.api.core.v1.TopologySelectorTerm": { - "description": "A topology selector term represents the result of label queries. A null or empty topology selector term matches no objects. The requirements of them are ANDed. It provides a subset of functionality as NodeSelectorTerm. This is an alpha feature and may change in the future.", - "properties": { - "matchLabelExpressions": { - "description": "A list of topology selector requirements by labels.", - "items": { - "$ref": "#/definitions/io.k8s.api.core.v1.TopologySelectorLabelRequirement" - }, - "type": "array" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.TopologySpreadConstraint": { - "description": "TopologySpreadConstraint specifies how to spread matching pods among the given topology.", - "properties": { - "labelSelector": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector", - "description": "LabelSelector is used to find matching pods. Pods that match this label selector are counted to determine the number of pods in their corresponding topology domain." - }, - "maxSkew": { - "description": "MaxSkew describes the degree to which pods may be unevenly distributed. It's the maximum permitted difference between the number of matching pods in any two topology domains of a given topology type. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 1/1/0: | zone1 | zone2 | zone3 | | P | P | | - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 1/1/1; scheduling it onto zone1(zone2) would make the ActualSkew(2-0) on zone1(zone2) violate MaxSkew(1). - if MaxSkew is 2, incoming pod can be scheduled onto any zone. It's a required field. Default value is 1 and 0 is not allowed.", - "format": "int32", - "type": "integer" - }, - "topologyKey": { - "description": "TopologyKey is the key of node labels. Nodes that have a label with this key and identical values are considered to be in the same topology. We consider each as a \"bucket\", and try to put balanced number of pods into each bucket. It's a required field.", - "type": "string" - }, - "whenUnsatisfiable": { - "description": "WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it - ScheduleAnyway tells the scheduler to still schedule it It's considered as \"Unsatisfiable\" if and only if placing incoming pod on any topology violates \"MaxSkew\". For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field.", - "type": "string" - } - }, - "required": [ - "maxSkew", - "topologyKey", - "whenUnsatisfiable" - ], - "type": "object" - }, - "io.k8s.api.core.v1.Volume": { - "description": "Volume represents a named volume in a pod that may be accessed by any container in the pod.", - "properties": { - "awsElasticBlockStore": { - "$ref": "#/definitions/io.k8s.api.core.v1.AWSElasticBlockStoreVolumeSource", - "description": "AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore" - }, - "azureDisk": { - "$ref": "#/definitions/io.k8s.api.core.v1.AzureDiskVolumeSource", - "description": "AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod." - }, - "azureFile": { - "$ref": "#/definitions/io.k8s.api.core.v1.AzureFileVolumeSource", - "description": "AzureFile represents an Azure File Service mount on the host and bind mount to the pod." - }, - "cephfs": { - "$ref": "#/definitions/io.k8s.api.core.v1.CephFSVolumeSource", - "description": "CephFS represents a Ceph FS mount on the host that shares a pod's lifetime" - }, - "cinder": { - "$ref": "#/definitions/io.k8s.api.core.v1.CinderVolumeSource", - "description": "Cinder represents a cinder volume attached and mounted on kubelets host machine. More info: https://examples.k8s.io/mysql-cinder-pd/README.md" - }, - "configMap": { - "$ref": "#/definitions/io.k8s.api.core.v1.ConfigMapVolumeSource", - "description": "ConfigMap represents a configMap that should populate this volume" - }, - "csi": { - "$ref": "#/definitions/io.k8s.api.core.v1.CSIVolumeSource", - "description": "CSI (Container Storage Interface) represents storage that is handled by an external CSI driver (Alpha feature)." - }, - "downwardAPI": { - "$ref": "#/definitions/io.k8s.api.core.v1.DownwardAPIVolumeSource", - "description": "DownwardAPI represents downward API about the pod that should populate this volume" - }, - "emptyDir": { - "$ref": "#/definitions/io.k8s.api.core.v1.EmptyDirVolumeSource", - "description": "EmptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir" - }, - "fc": { - "$ref": "#/definitions/io.k8s.api.core.v1.FCVolumeSource", - "description": "FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod." - }, - "flexVolume": { - "$ref": "#/definitions/io.k8s.api.core.v1.FlexVolumeSource", - "description": "FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin." - }, - "flocker": { - "$ref": "#/definitions/io.k8s.api.core.v1.FlockerVolumeSource", - "description": "Flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running" - }, - "gcePersistentDisk": { - "$ref": "#/definitions/io.k8s.api.core.v1.GCEPersistentDiskVolumeSource", - "description": "GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk" - }, - "gitRepo": { - "$ref": "#/definitions/io.k8s.api.core.v1.GitRepoVolumeSource", - "description": "GitRepo represents a git repository at a particular revision. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container." - }, - "glusterfs": { - "$ref": "#/definitions/io.k8s.api.core.v1.GlusterfsVolumeSource", - "description": "Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/glusterfs/README.md" - }, - "hostPath": { - "$ref": "#/definitions/io.k8s.api.core.v1.HostPathVolumeSource", - "description": "HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath" - }, - "iscsi": { - "$ref": "#/definitions/io.k8s.api.core.v1.ISCSIVolumeSource", - "description": "ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://examples.k8s.io/volumes/iscsi/README.md" - }, - "name": { - "description": "Volume's name. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names", - "type": "string" - }, - "nfs": { - "$ref": "#/definitions/io.k8s.api.core.v1.NFSVolumeSource", - "description": "NFS represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs" - }, - "persistentVolumeClaim": { - "$ref": "#/definitions/io.k8s.api.core.v1.PersistentVolumeClaimVolumeSource", - "description": "PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims" - }, - "photonPersistentDisk": { - "$ref": "#/definitions/io.k8s.api.core.v1.PhotonPersistentDiskVolumeSource", - "description": "PhotonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine" - }, - "portworxVolume": { - "$ref": "#/definitions/io.k8s.api.core.v1.PortworxVolumeSource", - "description": "PortworxVolume represents a portworx volume attached and mounted on kubelets host machine" - }, - "projected": { - "$ref": "#/definitions/io.k8s.api.core.v1.ProjectedVolumeSource", - "description": "Items for all in one resources secrets, configmaps, and downward API" - }, - "quobyte": { - "$ref": "#/definitions/io.k8s.api.core.v1.QuobyteVolumeSource", - "description": "Quobyte represents a Quobyte mount on the host that shares a pod's lifetime" - }, - "rbd": { - "$ref": "#/definitions/io.k8s.api.core.v1.RBDVolumeSource", - "description": "RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://examples.k8s.io/volumes/rbd/README.md" - }, - "scaleIO": { - "$ref": "#/definitions/io.k8s.api.core.v1.ScaleIOVolumeSource", - "description": "ScaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes." - }, - "secret": { - "$ref": "#/definitions/io.k8s.api.core.v1.SecretVolumeSource", - "description": "Secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret" - }, - "storageos": { - "$ref": "#/definitions/io.k8s.api.core.v1.StorageOSVolumeSource", - "description": "StorageOS represents a StorageOS volume attached and mounted on Kubernetes nodes." - }, - "vsphereVolume": { - "$ref": "#/definitions/io.k8s.api.core.v1.VsphereVirtualDiskVolumeSource", - "description": "VsphereVolume represents a vSphere volume attached and mounted on kubelets host machine" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "io.k8s.api.core.v1.VolumeDevice": { - "description": "volumeDevice describes a mapping of a raw block device within a container.", - "properties": { - "devicePath": { - "description": "devicePath is the path inside of the container that the device will be mapped to.", - "type": "string" - }, - "name": { - "description": "name must match the name of a persistentVolumeClaim in the pod", - "type": "string" - } - }, - "required": [ - "name", - "devicePath" - ], - "type": "object" - }, - "io.k8s.api.core.v1.VolumeMount": { - "description": "VolumeMount describes a mounting of a Volume within a container.", - "properties": { - "mountPath": { - "description": "Path within the container at which the volume should be mounted. Must not contain ':'.", - "type": "string" - }, - "mountPropagation": { - "description": "mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10.", - "type": "string" - }, - "name": { - "description": "This must match the Name of a Volume.", - "type": "string" - }, - "readOnly": { - "description": "Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", - "type": "boolean" - }, - "subPath": { - "description": "Path within the volume from which the container's volume should be mounted. Defaults to \"\" (volume's root).", - "type": "string" - }, - "subPathExpr": { - "description": "Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to \"\" (volume's root). SubPathExpr and SubPath are mutually exclusive.", - "type": "string" - } - }, - "required": [ - "name", - "mountPath" - ], - "type": "object" - }, - "io.k8s.api.core.v1.VolumeNodeAffinity": { - "description": "VolumeNodeAffinity defines constraints that limit what nodes this volume can be accessed from.", - "properties": { - "required": { - "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelector", - "description": "Required specifies hard node constraints that must be met." - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.VolumeProjection": { - "description": "Projection that may be projected along with other supported volume types", - "properties": { - "configMap": { - "$ref": "#/definitions/io.k8s.api.core.v1.ConfigMapProjection", - "description": "information about the configMap data to project" - }, - "downwardAPI": { - "$ref": "#/definitions/io.k8s.api.core.v1.DownwardAPIProjection", - "description": "information about the downwardAPI data to project" - }, - "secret": { - "$ref": "#/definitions/io.k8s.api.core.v1.SecretProjection", - "description": "information about the secret data to project" - }, - "serviceAccountToken": { - "$ref": "#/definitions/io.k8s.api.core.v1.ServiceAccountTokenProjection", - "description": "information about the serviceAccountToken data to project" - } - }, - "type": "object" - }, - "io.k8s.api.core.v1.VsphereVirtualDiskVolumeSource": { - "description": "Represents a vSphere volume resource.", - "properties": { - "fsType": { - "description": "Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", - "type": "string" - }, - "storagePolicyID": { - "description": "Storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName.", - "type": "string" - }, - "storagePolicyName": { - "description": "Storage Policy Based Management (SPBM) profile name.", - "type": "string" - }, - "volumePath": { - "description": "Path that identifies vSphere volume vmdk", - "type": "string" - } - }, - "required": [ - "volumePath" - ], - "type": "object" - }, - "io.k8s.api.core.v1.WeightedPodAffinityTerm": { - "description": "The weights of all of the matched WeightedPodAffinityTerm fields are added per-node to find the most preferred node(s)", - "properties": { - "podAffinityTerm": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodAffinityTerm", - "description": "Required. A pod affinity term, associated with the corresponding weight." - }, - "weight": { - "description": "weight associated with matching the corresponding podAffinityTerm, in the range 1-100.", - "format": "int32", - "type": "integer" - } - }, - "required": [ - "weight", - "podAffinityTerm" - ], - "type": "object" - }, - "io.k8s.api.core.v1.WindowsSecurityContextOptions": { - "description": "WindowsSecurityContextOptions contain Windows-specific options and credentials.", - "properties": { - "gmsaCredentialSpec": { - "description": "GMSACredentialSpec is where the GMSA admission webhook (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field. This field is alpha-level and is only honored by servers that enable the WindowsGMSA feature flag.", - "type": "string" - }, - "gmsaCredentialSpecName": { - "description": "GMSACredentialSpecName is the name of the GMSA credential spec to use. This field is alpha-level and is only honored by servers that enable the WindowsGMSA feature flag.", - "type": "string" - }, - "runAsUserName": { - "description": "The UserName in Windows to run the entrypoint of the container process. Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. This field is beta-level and may be disabled with the WindowsRunAsUserName feature flag.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.extensions.v1beta1.Deployment": { - "description": "DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "metadata": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta", - "description": "Standard object metadata." - }, - "spec": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.DeploymentSpec", - "description": "Specification of the desired behavior of the Deployment." - }, - "status": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.DeploymentStatus", - "description": "Most recently observed status of the Deployment." - } - }, - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "extensions", - "kind": "Deployment", - "version": "v1beta1" - } - ] - }, - "io.k8s.api.extensions.v1beta1.DeploymentCondition": { - "description": "DeploymentCondition describes the state of a deployment at a certain point.", - "properties": { - "lastTransitionTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Last time the condition transitioned from one status to another." - }, - "lastUpdateTime": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "The last time this condition was updated." - }, - "message": { - "description": "A human readable message indicating details about the transition.", - "type": "string" - }, - "reason": { - "description": "The reason for the condition's last transition.", - "type": "string" - }, - "status": { - "description": "Status of the condition, one of True, False, Unknown.", - "type": "string" - }, - "type": { - "description": "Type of deployment condition.", - "type": "string" - } - }, - "required": [ - "type", - "status" - ], - "type": "object" - }, - "io.k8s.api.extensions.v1beta1.DeploymentRollback": { - "description": "DEPRECATED. DeploymentRollback stores the information required to rollback a deployment.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", - "type": "string" - }, - "kind": { - "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "name": { - "description": "Required: This must match the Name of a deployment.", - "type": "string" - }, - "rollbackTo": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.RollbackConfig", - "description": "The config of this deployment rollback." - }, - "updatedAnnotations": { - "additionalProperties": { - "type": "string" - }, - "description": "The annotations to be updated to a deployment", - "type": "object" - } - }, - "required": [ - "name", - "rollbackTo" - ], - "type": "object", - "x-kubernetes-group-version-kind": [ - { - "group": "extensions", - "kind": "DeploymentRollback", - "version": "v1beta1" - } - ] - }, - "io.k8s.api.extensions.v1beta1.DeploymentSpec": { - "description": "DeploymentSpec is the specification of the desired behavior of the Deployment.", - "properties": { - "minReadySeconds": { - "description": "Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)", - "format": "int32", - "type": "integer" - }, - "paused": { - "description": "Indicates that the deployment is paused and will not be processed by the deployment controller.", - "type": "boolean" - }, - "progressDeadlineSeconds": { - "description": "The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. This is set to the max value of int32 (i.e. 2147483647) by default, which means \"no deadline\".", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.", - "format": "int32", - "type": "integer" - }, - "revisionHistoryLimit": { - "description": "The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. This is set to the max value of int32 (i.e. 2147483647) by default, which means \"retaining all old ReplicaSets\".", - "format": "int32", - "type": "integer" - }, - "rollbackTo": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.RollbackConfig", - "description": "DEPRECATED. The config this deployment is rolling back to. Will be cleared after rollback is done." - }, - "selector": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector", - "description": "Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment." - }, - "strategy": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.DeploymentStrategy", - "description": "The deployment strategy to use to replace existing pods with new ones.", - "x-kubernetes-patch-strategy": "retainKeys" - }, - "template": { - "$ref": "#/definitions/io.k8s.api.core.v1.PodTemplateSpec", - "description": "Template describes the pods that will be created." - } - }, - "required": [ - "template" - ], - "type": "object" - }, - "io.k8s.api.extensions.v1beta1.DeploymentStatus": { - "description": "DeploymentStatus is the most recently observed status of the Deployment.", - "properties": { - "availableReplicas": { - "description": "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "collisionCount": { - "description": "Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.", - "format": "int32", - "type": "integer" - }, - "conditions": { - "description": "Represents the latest available observations of a deployment's current state.", - "items": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.DeploymentCondition" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge" - }, - "observedGeneration": { - "description": "The generation observed by the deployment controller.", - "format": "int64", - "type": "integer" - }, - "readyReplicas": { - "description": "Total number of ready pods targeted by this deployment.", - "format": "int32", - "type": "integer" - }, - "replicas": { - "description": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).", - "format": "int32", - "type": "integer" - }, - "unavailableReplicas": { - "description": "Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.", - "format": "int32", - "type": "integer" - }, - "updatedReplicas": { - "description": "Total number of non-terminated pods targeted by this deployment that have the desired template spec.", - "format": "int32", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.extensions.v1beta1.DeploymentStrategy": { - "description": "DeploymentStrategy describes how to replace existing pods with new ones.", - "properties": { - "rollingUpdate": { - "$ref": "#/definitions/io.k8s.api.extensions.v1beta1.RollingUpdateDeployment", - "description": "Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate." - }, - "type": { - "description": "Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.api.extensions.v1beta1.RollbackConfig": { - "description": "DEPRECATED.", - "properties": { - "revision": { - "description": "The revision to rollback to. If set to 0, rollback to the last revision.", - "format": "int64", - "type": "integer" - } - }, - "type": "object" - }, - "io.k8s.api.extensions.v1beta1.RollingUpdateDeployment": { - "description": "Spec to control the desired behavior of rolling update.", - "properties": { - "maxSurge": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. By default, a value of 1 is used. Example: when this is set to 30%, the new RC can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods." - }, - "maxUnavailable": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString", - "description": "The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. By default, a fixed value of 1 is used. Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods." - } - }, - "type": "object" - }, - "io.k8s.apimachinery.pkg.api.resource.Quantity": { - "description": "Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors.\n\nThe serialization format is:\n\n ::= \n (Note that may be empty, from the \"\" case in .)\n ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei\n (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)\n ::= m | \"\" | k | M | G | T | P | E\n (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)\n ::= \"e\" | \"E\" \n\nNo matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.\n\nWhen a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.\n\nBefore serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:\n a. No precision is lost\n b. No fractional digits will be emitted\n c. The exponent (or suffix) is as large as possible.\nThe sign will be omitted unless the number is negative.\n\nExamples:\n 1.5 will be serialized as \"1500m\"\n 1.5Gi will be serialized as \"1536Mi\"\n\nNote that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise.\n\nNon-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)\n\nThis format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", - "type": "string" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1": { - "description": "FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format.\n\nEach key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:', where is the name of a field in a struct, or key in a map 'v:', where is the exact json formatted value of a list item 'i:', where is position of a item in a list 'k:', where is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set.\n\nThe exact format is defined in sigs.k8s.io/structured-merge-diff", - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector": { - "description": "A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects.", - "properties": { - "matchExpressions": { - "description": "matchExpressions is a list of label selector requirements. The requirements are ANDed.", - "items": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelectorRequirement" - }, - "type": "array" - }, - "matchLabels": { - "additionalProperties": { - "type": "string" - }, - "description": "matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", - "type": "object" - } - }, - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelectorRequirement": { - "description": "A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.", - "properties": { - "key": { - "description": "key is the label key that the selector applies to.", - "type": "string", - "x-kubernetes-patch-merge-key": "key", - "x-kubernetes-patch-strategy": "merge" - }, - "operator": { - "description": "operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.", - "type": "string" - }, - "values": { - "description": "values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.", - "items": { - "type": "string" - }, - "type": "array" - } - }, - "required": [ - "key", - "operator" - ], - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta": { - "description": "ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.", - "properties": { - "continue": { - "description": "continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.", - "type": "string" - }, - "remainingItemCount": { - "description": "remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.", - "format": "int64", - "type": "integer" - }, - "resourceVersion": { - "description": "String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - "type": "string" - }, - "selfLink": { - "description": "selfLink is a URL representing this object. Populated by the system. Read-only.\n\nDEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.ManagedFieldsEntry": { - "description": "ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource that the fieldset applies to.", - "properties": { - "apiVersion": { - "description": "APIVersion defines the version of this resource that this field set applies to. The format is \"group/version\" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted.", - "type": "string" - }, - "fieldsType": { - "description": "FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: \"FieldsV1\"", - "type": "string" - }, - "fieldsV1": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1", - "description": "FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type." - }, - "manager": { - "description": "Manager is an identifier of the workflow managing these fields.", - "type": "string" - }, - "operation": { - "description": "Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'.", - "type": "string" - }, - "time": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "Time is timestamp of when these fields were set. It should always be empty if Operation is 'Apply'" - } - }, - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta": { - "description": "ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create.", - "properties": { - "annotations": { - "additionalProperties": { - "type": "string" - }, - "description": "Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations", - "type": "object" - }, - "clusterName": { - "description": "The name of the cluster which the object belongs to. This is used to distinguish resources with same name and namespace in different clusters. This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.", - "type": "string" - }, - "creationTimestamp": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC.\n\nPopulated by the system. Read-only. Null for lists. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "deletionGracePeriodSeconds": { - "description": "Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.", - "format": "int64", - "type": "integer" - }, - "deletionTimestamp": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Time", - "description": "DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field is set by the server when a graceful deletion is requested by the user, and is not directly settable by a client. The resource is expected to be deleted (no longer visible from resource lists, and not reachable by name) after the time in this field, once the finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. Once the deletionTimestamp is set, this value may not be unset or be set further into the future, although it may be shortened or the resource may be deleted prior to this time. For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the pod from the API. In the presence of network partitions, this object may still exist after this timestamp, until an administrator or automated process can determine the resource is fully terminated. If not set, graceful deletion of the object has not been requested.\n\nPopulated by the system when a graceful deletion is requested. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata" - }, - "finalizers": { - "description": "Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.", - "items": { - "type": "string" - }, - "type": "array", - "x-kubernetes-patch-strategy": "merge" - }, - "generateName": { - "description": "GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.\n\nIf this field is specified and the generated name exists, the server will return a 409.\n\nApplied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency", - "type": "string" - }, - "generation": { - "description": "A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.", - "format": "int64", - "type": "integer" - }, - "labels": { - "additionalProperties": { - "type": "string" - }, - "description": "Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels", - "type": "object" - }, - "managedFields": { - "description": "ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like \"ci-cd\". The set of fields is always in the version that the workflow used when modifying the object.", - "items": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ManagedFieldsEntry" - }, - "type": "array" - }, - "name": { - "description": "Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - "type": "string" - }, - "namespace": { - "description": "Namespace defines the space within each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.\n\nMust be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces", - "type": "string" - }, - "ownerReferences": { - "description": "List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.", - "items": { - "$ref": "#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.OwnerReference" - }, - "type": "array", - "x-kubernetes-patch-merge-key": "uid", - "x-kubernetes-patch-strategy": "merge" - }, - "resourceVersion": { - "description": "An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.\n\nPopulated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", - "type": "string" - }, - "selfLink": { - "description": "SelfLink is a URL representing this object. Populated by the system. Read-only.\n\nDEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.", - "type": "string" - }, - "uid": { - "description": "UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.\n\nPopulated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids", - "type": "string" - } - }, - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.OwnerReference": { - "description": "OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field.", - "properties": { - "apiVersion": { - "description": "API version of the referent.", - "type": "string" - }, - "blockOwnerDeletion": { - "description": "If true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. Defaults to false. To set this field, a user needs \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned.", - "type": "boolean" - }, - "controller": { - "description": "If true, this reference points to the managing controller.", - "type": "boolean" - }, - "kind": { - "description": "Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", - "type": "string" - }, - "name": { - "description": "Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names", - "type": "string" - }, - "uid": { - "description": "UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids", - "type": "string" - } - }, - "required": [ - "apiVersion", - "kind", - "name", - "uid" - ], - "type": "object" - }, - "io.k8s.apimachinery.pkg.apis.meta.v1.Time": { - "description": "Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", - "format": "date-time", - "type": "string" - }, - "io.k8s.apimachinery.pkg.util.intstr.IntOrString": { - "description": "IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", - "format": "int-or-string", - "type": "string" - } - }, - "info": { - "title": "Kubernetes", - "version": "test" - }, - "paths": { - }, - "swagger": "2.0" -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/testing/testfieldmanager.go b/pkg/endpoints/handlers/fieldmanager/internal/testing/testfieldmanager.go deleted file mode 100644 index 5e9f04971..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/testing/testfieldmanager.go +++ /dev/null @@ -1,182 +0,0 @@ -/* -Copyright 2022 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 testing - -import ( - "errors" - "fmt" - - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" - "sigs.k8s.io/structured-merge-diff/v4/typed" -) - -// NewFakeObjectCreater implements ObjectCreater, it can create empty -// objects (unstructured) of the given GVK. -func NewFakeObjectCreater() runtime.ObjectCreater { - return &fakeObjectCreater{} -} - -type fakeObjectCreater struct{} - -func (f *fakeObjectCreater) New(gvk schema.GroupVersionKind) (runtime.Object, error) { - u := unstructured.Unstructured{Object: map[string]interface{}{}} - u.SetAPIVersion(gvk.GroupVersion().String()) - u.SetKind(gvk.Kind) - return &u, nil -} - -type fakeObjectConvertor struct { - converter merge.Converter - apiVersion fieldpath.APIVersion -} - -//nolint:staticcheck,ineffassign // SA4009 backwards compatibility -func (c *fakeObjectConvertor) Convert(in, out, context interface{}) error { - if typedValue, ok := in.(*typed.TypedValue); ok { - var err error - out, err = c.converter.Convert(typedValue, c.apiVersion) - return err - } - return nil -} - -func (c *fakeObjectConvertor) ConvertToVersion(in runtime.Object, _ runtime.GroupVersioner) (runtime.Object, error) { - return in, nil -} - -func (c *fakeObjectConvertor) ConvertFieldLabel(_ schema.GroupVersionKind, _, _ string) (string, string, error) { - return "", "", errors.New("not implemented") -} - -type fakeObjectDefaulter struct{} - -func (d *fakeObjectDefaulter) Default(in runtime.Object) {} - -type sameVersionConverter struct{} - -func (sameVersionConverter) Convert(object *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error) { - return object, nil -} - -func (sameVersionConverter) IsMissingVersionError(error) bool { - return false -} - -type TestFieldManagerImpl struct { - fieldManager *internal.FieldManager - apiVersion string - emptyObj runtime.Object - liveObj runtime.Object -} - -// APIVersion of the object that we're tracking. -func (f *TestFieldManagerImpl) APIVersion() string { - return f.apiVersion -} - -// Reset resets the state of the liveObject by resetting it to an empty object. -func (f *TestFieldManagerImpl) Reset() { - f.liveObj = f.emptyObj.DeepCopyObject() -} - -// Live returns a copy of the current liveObject. -func (f *TestFieldManagerImpl) Live() runtime.Object { - return f.liveObj.DeepCopyObject() -} - -// Apply applies the given object on top of the current liveObj, for the -// given manager and force flag. -func (f *TestFieldManagerImpl) Apply(obj runtime.Object, manager string, force bool) error { - out, err := f.fieldManager.Apply(f.liveObj, obj, manager, force) - if err == nil { - f.liveObj = out - } - return err -} - -// Update will updates the managed fields in the liveObj based on the -// changes performed by the update. -func (f *TestFieldManagerImpl) Update(obj runtime.Object, manager string) error { - out, err := f.fieldManager.Update(f.liveObj, obj, manager) - if err == nil { - f.liveObj = out - } - return err -} - -// ManagedFields returns the list of existing managed fields for the -// liveObj. -func (f *TestFieldManagerImpl) ManagedFields() []metav1.ManagedFieldsEntry { - accessor, err := meta.Accessor(f.liveObj) - if err != nil { - panic(fmt.Errorf("couldn't get accessor: %v", err)) - } - - return accessor.GetManagedFields() -} - -// NewTestFieldManager creates a new manager for the given GVK. -func NewTestFieldManagerImpl(typeConverter fieldmanager.TypeConverter, gvk schema.GroupVersionKind, subresource string, chainFieldManager func(internal.Manager) internal.Manager) *TestFieldManagerImpl { - apiVersion := fieldpath.APIVersion(gvk.GroupVersion().String()) - objectConverter := &fakeObjectConvertor{sameVersionConverter{}, apiVersion} - f, err := internal.NewStructuredMergeManager( - typeConverter, - objectConverter, - &fakeObjectDefaulter{}, - gvk.GroupVersion(), - gvk.GroupVersion(), - nil, - ) - if err != nil { - panic(err) - } - live := &unstructured.Unstructured{} - live.SetKind(gvk.Kind) - live.SetAPIVersion(gvk.GroupVersion().String()) - // This is different from `internal.NewDefaultFieldManager` because: - // 1. We don't want to create a `internal.FieldManager` - // 2. We don't want to use the CapManager that is tested separately with - // a smaller than the default cap. - f = internal.NewLastAppliedUpdater( - internal.NewLastAppliedManager( - internal.NewProbabilisticSkipNonAppliedManager( - internal.NewBuildManagerInfoManager( - internal.NewManagedFieldsUpdater( - internal.NewStripMetaManager(f), - ), gvk.GroupVersion(), subresource, - ), NewFakeObjectCreater(), gvk, internal.DefaultTrackOnCreateProbability, - ), typeConverter, objectConverter, gvk.GroupVersion(), - ), - ) - if chainFieldManager != nil { - f = chainFieldManager(f) - } - return &TestFieldManagerImpl{ - fieldManager: internal.NewFieldManager(f, subresource), - apiVersion: gvk.GroupVersion().String(), - emptyObj: live, - liveObj: live.DeepCopyObject(), - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/typeconverter.go b/pkg/endpoints/handlers/fieldmanager/internal/typeconverter.go deleted file mode 100644 index 1ac96d7f7..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/typeconverter.go +++ /dev/null @@ -1,193 +0,0 @@ -/* -Copyright 2022 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 internal - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/kube-openapi/pkg/schemaconv" - "k8s.io/kube-openapi/pkg/validation/spec" - smdschema "sigs.k8s.io/structured-merge-diff/v4/schema" - "sigs.k8s.io/structured-merge-diff/v4/typed" - "sigs.k8s.io/structured-merge-diff/v4/value" -) - -// TypeConverter allows you to convert from runtime.Object to -// typed.TypedValue and the other way around. -type TypeConverter interface { - ObjectToTyped(runtime.Object) (*typed.TypedValue, error) - TypedToObject(*typed.TypedValue) (runtime.Object, error) -} - -type typeConverter struct { - parser map[schema.GroupVersionKind]*typed.ParseableType -} - -var _ TypeConverter = &typeConverter{} - -func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error) { - typeSchema, err := schemaconv.ToSchemaFromOpenAPI(openapiSpec, preserveUnknownFields) - if err != nil { - return nil, fmt.Errorf("failed to convert models to schema: %v", err) - } - - typeParser := typed.Parser{Schema: smdschema.Schema{Types: typeSchema.Types}} - tr := indexModels(&typeParser, openapiSpec) - - return &typeConverter{parser: tr}, nil -} - -func (c *typeConverter) ObjectToTyped(obj runtime.Object) (*typed.TypedValue, error) { - gvk := obj.GetObjectKind().GroupVersionKind() - t := c.parser[gvk] - if t == nil { - return nil, NewNoCorrespondingTypeError(gvk) - } - switch o := obj.(type) { - case *unstructured.Unstructured: - return t.FromUnstructured(o.UnstructuredContent()) - default: - return t.FromStructured(obj) - } -} - -func (c *typeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error) { - return valueToObject(value.AsValue()) -} - -type deducedTypeConverter struct{} - -// DeducedTypeConverter is a TypeConverter for CRDs that don't have a -// schema. It does implement the same interface though (and create the -// same types of objects), so that everything can still work the same. -// CRDs are merged with all their fields being "atomic" (lists -// included). -func NewDeducedTypeConverter() TypeConverter { - return deducedTypeConverter{} -} - -// ObjectToTyped converts an object into a TypedValue with a "deduced type". -func (deducedTypeConverter) ObjectToTyped(obj runtime.Object) (*typed.TypedValue, error) { - switch o := obj.(type) { - case *unstructured.Unstructured: - return typed.DeducedParseableType.FromUnstructured(o.UnstructuredContent()) - default: - return typed.DeducedParseableType.FromStructured(obj) - } -} - -// TypedToObject transforms the typed value into a runtime.Object. That -// is not specific to deduced type. -func (deducedTypeConverter) TypedToObject(value *typed.TypedValue) (runtime.Object, error) { - return valueToObject(value.AsValue()) -} - -func valueToObject(val value.Value) (runtime.Object, error) { - vu := val.Unstructured() - switch o := vu.(type) { - case map[string]interface{}: - return &unstructured.Unstructured{Object: o}, nil - default: - return nil, fmt.Errorf("failed to convert value to unstructured for type %T", vu) - } -} - -func indexModels( - typeParser *typed.Parser, - openAPISchemas map[string]*spec.Schema, -) map[schema.GroupVersionKind]*typed.ParseableType { - tr := map[schema.GroupVersionKind]*typed.ParseableType{} - for modelName, model := range openAPISchemas { - gvkList := parseGroupVersionKind(model.Extensions) - if len(gvkList) == 0 { - continue - } - - parsedType := typeParser.Type(modelName) - for _, gvk := range gvkList { - if len(gvk.Kind) > 0 { - tr[schema.GroupVersionKind(gvk)] = &parsedType - } - } - } - return tr -} - -// Get and parse GroupVersionKind from the extension. Returns empty if it doesn't have one. -func parseGroupVersionKind(extensions map[string]interface{}) []schema.GroupVersionKind { - gvkListResult := []schema.GroupVersionKind{} - - // Get the extensions - gvkExtension, ok := extensions["x-kubernetes-group-version-kind"] - if !ok { - return []schema.GroupVersionKind{} - } - - // gvk extension must be a list of at least 1 element. - gvkList, ok := gvkExtension.([]interface{}) - if !ok { - return []schema.GroupVersionKind{} - } - - for _, gvk := range gvkList { - var group, version, kind string - - // gvk extension list must be a map with group, version, and - // kind fields - if gvkMap, ok := gvk.(map[interface{}]interface{}); ok { - group, ok = gvkMap["group"].(string) - if !ok { - continue - } - version, ok = gvkMap["version"].(string) - if !ok { - continue - } - kind, ok = gvkMap["kind"].(string) - if !ok { - continue - } - - } else if gvkMap, ok := gvk.(map[string]interface{}); ok { - group, ok = gvkMap["group"].(string) - if !ok { - continue - } - version, ok = gvkMap["version"].(string) - if !ok { - continue - } - kind, ok = gvkMap["kind"].(string) - if !ok { - continue - } - } else { - continue - } - - gvkListResult = append(gvkListResult, schema.GroupVersionKind{ - Group: group, - Version: version, - Kind: kind, - }) - } - - return gvkListResult -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/typeconverter_test.go b/pkg/endpoints/handlers/fieldmanager/internal/typeconverter_test.go deleted file mode 100644 index f396a2b2f..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/typeconverter_test.go +++ /dev/null @@ -1,317 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "fmt" - "reflect" - "testing" - - "github.com/stretchr/testify/require" - smdschema "sigs.k8s.io/structured-merge-diff/v4/schema" - "sigs.k8s.io/structured-merge-diff/v4/typed" - "sigs.k8s.io/yaml" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/kube-openapi/pkg/validation/spec" -) - -func TestTypeConverter(t *testing.T) { - dtc := NewDeducedTypeConverter() - - testCases := []struct { - name string - yaml string - }{ - { - name: "apps/v1.Deployment", - yaml: ` -apiVersion: apps/v1 -kind: Deployment -metadata: - name: nginx-deployment - labels: - app: nginx -spec: - selector: - matchLabels: - app: nginx - template: - metadata: - labels: - app: nginx - spec: - containers: - - name: nginx - image: nginx:1.15.4 -`, - }, { - name: "extensions/v1beta1.Deployment", - yaml: ` -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: nginx-deployment - labels: - app: nginx -spec: - selector: - matchLabels: - app: nginx - template: - metadata: - labels: - app: nginx - spec: - containers: - - name: nginx - image: nginx:1.15.4 -`, - }, { - name: "v1.Pod", - yaml: ` -apiVersion: v1 -kind: Pod -metadata: - name: nginx-pod - labels: - app: nginx -spec: - containers: - - name: nginx - image: nginx:1.15.4 -`, - }, - } - - for _, testCase := range testCases { - t.Run(fmt.Sprintf("%v ObjectToTyped with TypeConverter", testCase.name), func(t *testing.T) { - testObjectToTyped(t, testTypeConverter, testCase.yaml) - }) - t.Run(fmt.Sprintf("%v ObjectToTyped with DeducedTypeConverter", testCase.name), func(t *testing.T) { - testObjectToTyped(t, dtc, testCase.yaml) - }) - } -} - -func testObjectToTyped(t *testing.T, tc TypeConverter, y string) { - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(y), &obj.Object); err != nil { - t.Fatalf("Failed to parse yaml object: %v", err) - } - typed, err := tc.ObjectToTyped(obj) - if err != nil { - t.Fatalf("Failed to convert object to typed: %v", err) - } - newObj, err := tc.TypedToObject(typed) - if err != nil { - t.Fatalf("Failed to convert typed to object: %v", err) - } - if !reflect.DeepEqual(obj, newObj) { - t.Errorf(`Round-trip failed: -Original object: -%#v -Final object: -%#v`, obj, newObj) - } -} - -var result typed.TypedValue - -func BenchmarkObjectToTyped(b *testing.B) { - y := ` -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: nginx-deployment - labels: - app: nginx -spec: - selector: - matchLabels: - app: nginx - template: - metadata: - labels: - app: nginx - spec: - containers: - - name: nginx - image: nginx:1.15.4 -` - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := yaml.Unmarshal([]byte(y), &obj.Object); err != nil { - b.Fatalf("Failed to parse yaml object: %v", err) - } - - b.ResetTimer() - b.ReportAllocs() - - var r *typed.TypedValue - for i := 0; i < b.N; i++ { - var err error - r, err = testTypeConverter.ObjectToTyped(obj) - if err != nil { - b.Fatalf("Failed to convert object to typed: %v", err) - } - } - result = *r -} - -func TestIndexModels(t *testing.T) { - myDefs := map[string]*spec.Schema{ - // Show empty GVK extension is ignored - "def0": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-group-version-kind": []interface{}{}, - }, - }, - }, - // Show nil GVK is ignored - "def0.0": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-group-version-kind": nil, - }, - }, - }, - // Show this is ignored - "def0.1": {}, - // Show allows binding a single GVK - "def1": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-group-version-kind": []interface{}{ - map[string]interface{}{ - "group": "mygroup", - "version": "v1", - "kind": "MyKind", - }, - }, - }, - }, - }, - // Show allows bindings with two versions - "def2": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-group-version-kind": []interface{}{ - map[string]interface{}{ - "group": "mygroup", - "version": "v1", - "kind": "MyOtherKind", - }, - map[string]interface{}{ - "group": "mygroup", - "version": "v2", - "kind": "MyOtherKind", - }, - }, - }, - }, - }, - // Show that we can mix and match GVKs from other definitions, and - // that both map[interface{}]interface{} and map[string]interface{} - // are allowed - "def3": { - VendorExtensible: spec.VendorExtensible{ - Extensions: spec.Extensions{ - "x-kubernetes-group-version-kind": []interface{}{ - map[string]interface{}{ - "group": "mygroup", - "version": "v3", - "kind": "MyKind", - }, - map[interface{}]interface{}{ - "group": "mygroup", - "version": "v3", - "kind": "MyOtherKind", - }, - }, - }, - }, - }, - } - - myTypes := []smdschema.TypeDef{ - { - Name: "def0", - Atom: smdschema.Atom{}, - }, - { - Name: "def0.1", - Atom: smdschema.Atom{}, - }, - { - Name: "def0.2", - Atom: smdschema.Atom{}, - }, - { - Name: "def1", - Atom: smdschema.Atom{}, - }, - { - Name: "def2", - Atom: smdschema.Atom{}, - }, - { - Name: "def3", - Atom: smdschema.Atom{}, - }, - } - - parser := typed.Parser{Schema: smdschema.Schema{Types: myTypes}} - gvkIndex := indexModels(&parser, myDefs) - - require.Len(t, gvkIndex, 5) - - resultNames := map[schema.GroupVersionKind]string{} - for k, v := range gvkIndex { - require.NotNil(t, v.TypeRef.NamedType) - resultNames[k] = *v.TypeRef.NamedType - } - - require.Equal(t, resultNames, map[schema.GroupVersionKind]string{ - { - Group: "mygroup", - Version: "v1", - Kind: "MyKind", - }: "def1", - { - Group: "mygroup", - Version: "v1", - Kind: "MyOtherKind", - }: "def2", - { - Group: "mygroup", - Version: "v2", - Kind: "MyOtherKind", - }: "def2", - { - Group: "mygroup", - Version: "v3", - Kind: "MyKind", - }: "def3", - { - Group: "mygroup", - Version: "v3", - Kind: "MyOtherKind", - }: "def3", - }) -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/versionconverter.go b/pkg/endpoints/handlers/fieldmanager/internal/versionconverter.go deleted file mode 100644 index 45855fa4c..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/versionconverter.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" - "sigs.k8s.io/structured-merge-diff/v4/merge" - "sigs.k8s.io/structured-merge-diff/v4/typed" -) - -// versionConverter is an implementation of -// sigs.k8s.io/structured-merge-diff/merge.Converter -type versionConverter struct { - typeConverter TypeConverter - objectConvertor runtime.ObjectConvertor - hubGetter func(from schema.GroupVersion) schema.GroupVersion -} - -var _ merge.Converter = &versionConverter{} - -// NewVersionConverter builds a VersionConverter from a TypeConverter and an ObjectConvertor. -func newVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter { - return &versionConverter{ - typeConverter: t, - objectConvertor: o, - hubGetter: func(from schema.GroupVersion) schema.GroupVersion { - return schema.GroupVersion{ - Group: from.Group, - Version: h.Version, - } - }, - } -} - -// NewCRDVersionConverter builds a VersionConverter for CRDs from a TypeConverter and an ObjectConvertor. -func newCRDVersionConverter(t TypeConverter, o runtime.ObjectConvertor, h schema.GroupVersion) merge.Converter { - return &versionConverter{ - typeConverter: t, - objectConvertor: o, - hubGetter: func(from schema.GroupVersion) schema.GroupVersion { - return h - }, - } -} - -// Convert implements sigs.k8s.io/structured-merge-diff/merge.Converter -func (v *versionConverter) Convert(object *typed.TypedValue, version fieldpath.APIVersion) (*typed.TypedValue, error) { - // Convert the smd typed value to a kubernetes object. - objectToConvert, err := v.typeConverter.TypedToObject(object) - if err != nil { - return object, err - } - - // Parse the target groupVersion. - groupVersion, err := schema.ParseGroupVersion(string(version)) - if err != nil { - return object, err - } - - // If attempting to convert to the same version as we already have, just return it. - fromVersion := objectToConvert.GetObjectKind().GroupVersionKind().GroupVersion() - if fromVersion == groupVersion { - return object, nil - } - - // Convert to internal - internalObject, err := v.objectConvertor.ConvertToVersion(objectToConvert, v.hubGetter(fromVersion)) - if err != nil { - return object, err - } - - // Convert the object into the target version - convertedObject, err := v.objectConvertor.ConvertToVersion(internalObject, groupVersion) - if err != nil { - return object, err - } - - // Convert the object back to a smd typed value and return it. - return v.typeConverter.ObjectToTyped(convertedObject) -} - -// IsMissingVersionError -func (v *versionConverter) IsMissingVersionError(err error) bool { - return runtime.IsNotRegisteredError(err) || isNoCorrespondingTypeError(err) -} - -type noCorrespondingTypeErr struct { - gvk schema.GroupVersionKind -} - -func NewNoCorrespondingTypeError(gvk schema.GroupVersionKind) error { - return &noCorrespondingTypeErr{gvk: gvk} -} - -func (k *noCorrespondingTypeErr) Error() string { - return fmt.Sprintf("no corresponding type for %v", k.gvk) -} - -func isNoCorrespondingTypeError(err error) bool { - if err == nil { - return false - } - _, ok := err.(*noCorrespondingTypeErr) - return ok -} diff --git a/pkg/endpoints/handlers/fieldmanager/internal/versionconverter_test.go b/pkg/endpoints/handlers/fieldmanager/internal/versionconverter_test.go deleted file mode 100644 index 32f8edb34..000000000 --- a/pkg/endpoints/handlers/fieldmanager/internal/versionconverter_test.go +++ /dev/null @@ -1,119 +0,0 @@ -/* -Copyright 2018 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 internal - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "path/filepath" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/kube-openapi/pkg/validation/spec" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -var testTypeConverter = func() TypeConverter { - data, err := ioutil.ReadFile(filepath.Join("testdata", "swagger.json")) - if err != nil { - panic(err) - } - swag := spec.Swagger{} - if err := json.Unmarshal(data, &swag); err != nil { - panic(err) - } - - convertedDefs := map[string]*spec.Schema{} - for k, v := range swag.Definitions { - vCopy := v - convertedDefs[k] = &vCopy - } - typeConverter, err := NewTypeConverter(convertedDefs, false) - if err != nil { - panic(err) - } - return typeConverter -}() - -// TestVersionConverter tests the version converter -func TestVersionConverter(t *testing.T) { - oc := fakeObjectConvertorForTestSchema{ - gvkForVersion("v1beta1"): objForGroupVersion("apps/v1beta1"), - gvkForVersion("v1"): objForGroupVersion("apps/v1"), - } - vc := newVersionConverter(testTypeConverter, oc, schema.GroupVersion{Group: "apps", Version: runtime.APIVersionInternal}) - - input, err := testTypeConverter.ObjectToTyped(objForGroupVersion("apps/v1beta1")) - if err != nil { - t.Fatalf("error creating converting input object to a typed value: %v", err) - } - expected := objForGroupVersion("apps/v1") - output, err := vc.Convert(input, fieldpath.APIVersion("apps/v1")) - if err != nil { - t.Fatalf("expected err to be nil but got %v", err) - } - actual, err := testTypeConverter.TypedToObject(output) - if err != nil { - t.Fatalf("error converting output typed value to an object %v", err) - } - - if !reflect.DeepEqual(expected, actual) { - t.Fatalf("expected to get %v but got %v", expected, actual) - } -} - -func gvkForVersion(v string) schema.GroupVersionKind { - return schema.GroupVersionKind{ - Group: "apps", - Version: v, - Kind: "Deployment", - } -} - -func objForGroupVersion(gv string) runtime.Object { - return &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": gv, - "kind": "Deployment", - }, - } -} - -type fakeObjectConvertorForTestSchema map[schema.GroupVersionKind]runtime.Object - -var _ runtime.ObjectConvertor = fakeObjectConvertorForTestSchema{} - -func (c fakeObjectConvertorForTestSchema) ConvertToVersion(_ runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error) { - allKinds := make([]schema.GroupVersionKind, 0) - for kind := range c { - allKinds = append(allKinds, kind) - } - gvk, _ := gv.KindForGroupVersionKinds(allKinds) - return c[gvk], nil -} - -func (fakeObjectConvertorForTestSchema) Convert(_, _, _ interface{}) error { - return fmt.Errorf("function not implemented") -} - -func (fakeObjectConvertorForTestSchema) ConvertFieldLabel(_ schema.GroupVersionKind, _, _ string) (string, string, error) { - return "", "", fmt.Errorf("function not implemented") -} diff --git a/pkg/endpoints/handlers/fieldmanager/scalehandler.go b/pkg/endpoints/handlers/fieldmanager/scalehandler.go deleted file mode 100644 index 655bf91d1..000000000 --- a/pkg/endpoints/handlers/fieldmanager/scalehandler.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2021 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 fieldmanager - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -var ( - scaleGroupVersion = schema.GroupVersion{Group: "autoscaling", Version: "v1"} - replicasPathInScale = fieldpath.MakePathOrDie("spec", "replicas") -) - -// ResourcePathMappings maps a group/version to its replicas path. The -// assumption is that all the paths correspond to leaf fields. -type ResourcePathMappings map[string]fieldpath.Path - -// ScaleHandler manages the conversion of managed fields between a main -// resource and the scale subresource -type ScaleHandler struct { - parentEntries []metav1.ManagedFieldsEntry - groupVersion schema.GroupVersion - mappings ResourcePathMappings -} - -// NewScaleHandler creates a new ScaleHandler -func NewScaleHandler(parentEntries []metav1.ManagedFieldsEntry, groupVersion schema.GroupVersion, mappings ResourcePathMappings) *ScaleHandler { - return &ScaleHandler{ - parentEntries: parentEntries, - groupVersion: groupVersion, - mappings: mappings, - } -} - -// ToSubresource filter the managed fields of the main resource and convert -// them so that they can be handled by scale. -// For the managed fields that have a replicas path it performs two changes: -// 1. APIVersion is changed to the APIVersion of the scale subresource -// 2. Replicas path of the main resource is transformed to the replicas path of -// the scale subresource -func (h *ScaleHandler) ToSubresource() ([]metav1.ManagedFieldsEntry, error) { - managed, err := internal.DecodeManagedFields(h.parentEntries) - if err != nil { - return nil, err - } - - f := fieldpath.ManagedFields{} - t := map[string]*metav1.Time{} - for manager, versionedSet := range managed.Fields() { - path, ok := h.mappings[string(versionedSet.APIVersion())] - // Skip the entry if the APIVersion is unknown - if !ok || path == nil { - continue - } - - if versionedSet.Set().Has(path) { - newVersionedSet := fieldpath.NewVersionedSet( - fieldpath.NewSet(replicasPathInScale), - fieldpath.APIVersion(scaleGroupVersion.String()), - versionedSet.Applied(), - ) - - f[manager] = newVersionedSet - t[manager] = managed.Times()[manager] - } - } - - return managedFieldsEntries(internal.NewManaged(f, t)) -} - -// ToParent merges `scaleEntries` with the entries of the main resource and -// transforms them accordingly -func (h *ScaleHandler) ToParent(scaleEntries []metav1.ManagedFieldsEntry) ([]metav1.ManagedFieldsEntry, error) { - decodedParentEntries, err := internal.DecodeManagedFields(h.parentEntries) - if err != nil { - return nil, err - } - parentFields := decodedParentEntries.Fields() - - decodedScaleEntries, err := internal.DecodeManagedFields(scaleEntries) - if err != nil { - return nil, err - } - scaleFields := decodedScaleEntries.Fields() - - f := fieldpath.ManagedFields{} - t := map[string]*metav1.Time{} - - for manager, versionedSet := range parentFields { - // Get the main resource "replicas" path - path, ok := h.mappings[string(versionedSet.APIVersion())] - // Drop the entry if the APIVersion is unknown. - if !ok { - continue - } - - // If the parent entry does not have the replicas path or it is nil, just - // keep it as it is. The path is nil for Custom Resources without scale - // subresource. - if path == nil || !versionedSet.Set().Has(path) { - f[manager] = versionedSet - t[manager] = decodedParentEntries.Times()[manager] - continue - } - - if _, ok := scaleFields[manager]; !ok { - // "Steal" the replicas path from the main resource entry - newSet := versionedSet.Set().Difference(fieldpath.NewSet(path)) - - if !newSet.Empty() { - newVersionedSet := fieldpath.NewVersionedSet( - newSet, - versionedSet.APIVersion(), - versionedSet.Applied(), - ) - f[manager] = newVersionedSet - t[manager] = decodedParentEntries.Times()[manager] - } - } else { - // Field wasn't stolen, let's keep the entry as it is. - f[manager] = versionedSet - t[manager] = decodedParentEntries.Times()[manager] - delete(scaleFields, manager) - } - } - - for manager, versionedSet := range scaleFields { - if !versionedSet.Set().Has(replicasPathInScale) { - continue - } - newVersionedSet := fieldpath.NewVersionedSet( - fieldpath.NewSet(h.mappings[h.groupVersion.String()]), - fieldpath.APIVersion(h.groupVersion.String()), - versionedSet.Applied(), - ) - f[manager] = newVersionedSet - t[manager] = decodedParentEntries.Times()[manager] - } - - return managedFieldsEntries(internal.NewManaged(f, t)) -} - -func managedFieldsEntries(entries internal.ManagedInterface) ([]metav1.ManagedFieldsEntry, error) { - obj := &unstructured.Unstructured{Object: map[string]interface{}{}} - if err := internal.EncodeObjectManagedFields(obj, entries); err != nil { - return nil, err - } - accessor, err := meta.Accessor(obj) - if err != nil { - panic(fmt.Sprintf("couldn't get accessor: %v", err)) - } - return accessor.GetManagedFields(), nil -} diff --git a/pkg/endpoints/handlers/fieldmanager/scalehandler_test.go b/pkg/endpoints/handlers/fieldmanager/scalehandler_test.go deleted file mode 100644 index 5d86dd64a..000000000 --- a/pkg/endpoints/handlers/fieldmanager/scalehandler_test.go +++ /dev/null @@ -1,785 +0,0 @@ -/* -Copyright 2021 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 fieldmanager - -import ( - "reflect" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/structured-merge-diff/v4/fieldpath" -) - -func TestTransformManagedFieldsToSubresource(t *testing.T) { - testTime, _ := time.ParseInLocation("2006-Jan-02", "2013-Feb-03", time.Local) - managedFieldTime := metav1.NewTime(testTime) - - tests := []struct { - desc string - input []metav1.ManagedFieldsEntry - expected []metav1.ManagedFieldsEntry - }{ - { - desc: "filter one entry and transform it into a subresource entry", - input: []metav1.ManagedFieldsEntry{ - { - Manager: "manager-1", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:another-field":{}}}`)}, - }, - { - Manager: "manager-2", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Time: &managedFieldTime, - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "manager-2", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Time: &managedFieldTime, - }, - }, - }, - { - desc: "transform all entries", - input: []metav1.ManagedFieldsEntry{ - { - Manager: "manager-1", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - { - Manager: "manager-2", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - { - Manager: "manager-3", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "manager-1", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - { - Manager: "manager-2", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - { - Manager: "manager-3", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "drops fields if the api version is unknown", - input: []metav1.ManagedFieldsEntry{ - { - Manager: "manager-1", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v10", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - }, - expected: nil, - }, - } - - for _, test := range tests { - handler := NewScaleHandler( - test.input, - schema.GroupVersion{Group: "apps", Version: "v1"}, - defaultMappings(), - ) - subresourceEntries, err := handler.ToSubresource() - if err != nil { - t.Fatalf("test %q - expected no error but got %v", test.desc, err) - } - - if !reflect.DeepEqual(subresourceEntries, test.expected) { - t.Fatalf("test %q - expected output to be:\n%v\n\nbut got:\n%v", test.desc, test.expected, subresourceEntries) - } - } -} - -func TestTransformingManagedFieldsToParent(t *testing.T) { - tests := []struct { - desc string - parent []metav1.ManagedFieldsEntry - subresource []metav1.ManagedFieldsEntry - expected []metav1.ManagedFieldsEntry - }{ - { - desc: "different-managers: apply -> update", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "different-managers: apply -> apply", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - }, - { - desc: "different-managers: update -> update", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - }, - { - desc: "different-managers: update -> apply", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - }, - { - desc: "same manager: apply -> apply", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "same manager: update -> update", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "same manager: update -> apply", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - }, - { - desc: "same manager: apply -> update", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "subresource doesn't own the path anymore", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:status":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - }, - { - desc: "Subresource steals all the fields of the parent resource", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "apply without stealing", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{},"f:selector":{}}}`)}, - }, - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "drops the entry if the api version is unknown", - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - { - Manager: "another-manager", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v10", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.desc, func(t *testing.T) { - handler := NewScaleHandler( - test.parent, - schema.GroupVersion{Group: "apps", Version: "v1"}, - defaultMappings(), - ) - parentEntries, err := handler.ToParent(test.subresource) - if err != nil { - t.Fatalf("test: %q - expected no error but got %v", test.desc, err) - } - if !reflect.DeepEqual(parentEntries, test.expected) { - t.Fatalf("test: %q - expected output to be:\n%v\n\nbut got:\n%v", test.desc, test.expected, parentEntries) - } - }) - } -} - -func TestTransformingManagedFieldsToParentMultiVersion(t *testing.T) { - tests := []struct { - desc string - groupVersion schema.GroupVersion - mappings ResourcePathMappings - parent []metav1.ManagedFieldsEntry - subresource []metav1.ManagedFieldsEntry - expected []metav1.ManagedFieldsEntry - }{ - { - desc: "multi-version", - groupVersion: schema.GroupVersion{Group: "apps", Version: "v1"}, - mappings: ResourcePathMappings{ - "apps/v1": fieldpath.MakePathOrDie("spec", "the-replicas"), - "apps/v2": fieldpath.MakePathOrDie("spec", "not-the-replicas"), - }, - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:the-replicas":{},"f:selector":{}}}`)}, - }, - { - Manager: "test-other", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v2", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:not-the-replicas":{},"f:selector":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "test-other", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "apps/v2", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "apps/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:the-replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - { - desc: "Custom resource without scale subresource, scaling a version with `scale`", - groupVersion: schema.GroupVersion{Group: "mygroup", Version: "v1"}, - mappings: ResourcePathMappings{ - "mygroup/v1": fieldpath.MakePathOrDie("spec", "the-replicas"), - "mygroup/v2": nil, - }, - parent: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "mygroup/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:the-replicas":{},"f:selector":{}}}`)}, - }, - { - Manager: "test-other", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "mygroup/v2", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:test-other":{}}}`)}, - }, - }, - subresource: []metav1.ManagedFieldsEntry{ - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "autoscaling/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:replicas":{}}}`)}, - Subresource: "scale", - }, - }, - expected: []metav1.ManagedFieldsEntry{ - { - Manager: "test", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "mygroup/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:selector":{}}}`)}, - }, - { - Manager: "test-other", - Operation: metav1.ManagedFieldsOperationApply, - APIVersion: "mygroup/v2", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:test-other":{}}}`)}, - }, - { - Manager: "scale", - Operation: metav1.ManagedFieldsOperationUpdate, - APIVersion: "mygroup/v1", - FieldsType: "FieldsV1", - FieldsV1: &metav1.FieldsV1{Raw: []byte(`{"f:spec":{"f:the-replicas":{}}}`)}, - Subresource: "scale", - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.desc, func(t *testing.T) { - handler := NewScaleHandler( - test.parent, - test.groupVersion, - test.mappings, - ) - parentEntries, err := handler.ToParent(test.subresource) - if err != nil { - t.Fatalf("test: %q - expected no error but got %v", test.desc, err) - } - if !reflect.DeepEqual(parentEntries, test.expected) { - t.Fatalf("test: %q - expected output to be:\n%v\n\nbut got:\n%v", test.desc, test.expected, parentEntries) - } - }) - } -} - -func defaultMappings() ResourcePathMappings { - return ResourcePathMappings{ - "apps/v1": fieldpath.MakePathOrDie("spec", "replicas"), - } -} diff --git a/pkg/endpoints/handlers/fieldmanager/typeconverter.go b/pkg/endpoints/handlers/fieldmanager/typeconverter.go deleted file mode 100644 index 8772a3076..000000000 --- a/pkg/endpoints/handlers/fieldmanager/typeconverter.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2018 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 fieldmanager - -import ( - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager/internal" - "k8s.io/kube-openapi/pkg/validation/spec" -) - -// TypeConverter allows you to convert from runtime.Object to -// typed.TypedValue and the other way around. -type TypeConverter = internal.TypeConverter - -// NewDeducedTypeConverter creates a TypeConverter for CRDs that don't -// have a schema. It does implement the same interface though (and -// create the same types of objects), so that everything can still work -// the same. CRDs are merged with all their fields being "atomic" (lists -// included). -func NewDeducedTypeConverter() TypeConverter { - return internal.NewDeducedTypeConverter() -} - -// NewTypeConverter builds a TypeConverter from a map of OpenAPIV3 schemas. -// This will automatically find the proper version of the object, and the -// corresponding schema information. -// The keys to the map must be consistent with the names -// used by Refs within the schemas. -// The schemas should conform to the Kubernetes Structural Schema OpenAPI -// restrictions found in docs: -// https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema -func NewTypeConverter(openapiSpec map[string]*spec.Schema, preserveUnknownFields bool) (TypeConverter, error) { - return internal.NewTypeConverter(openapiSpec, preserveUnknownFields) -} diff --git a/pkg/endpoints/handlers/patch.go b/pkg/endpoints/handlers/patch.go index 8f396b057..4f5533f34 100644 --- a/pkg/endpoints/handlers/patch.go +++ b/pkg/endpoints/handlers/patch.go @@ -36,6 +36,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/managedfields" "k8s.io/apimachinery/pkg/util/mergepatch" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/strategicpatch" @@ -297,7 +298,7 @@ type patchMechanism interface { type jsonPatcher struct { *patcher - fieldManager *fieldmanager.FieldManager + fieldManager *managedfields.FieldManager } func (p *jsonPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error) { @@ -417,7 +418,7 @@ type smpPatcher struct { // Schema schemaReferenceObj runtime.Object - fieldManager *fieldmanager.FieldManager + fieldManager *managedfields.FieldManager } func (p *smpPatcher) applyPatchToCurrentObject(requestContext context.Context, currentObject runtime.Object) (runtime.Object, error) { @@ -455,7 +456,7 @@ type applyPatcher struct { options *metav1.PatchOptions creater runtime.ObjectCreater kind schema.GroupVersionKind - fieldManager *fieldmanager.FieldManager + fieldManager *managedfields.FieldManager userAgent string validationDirective string } diff --git a/pkg/endpoints/handlers/rest.go b/pkg/endpoints/handlers/rest.go index 1a9f77919..7f6756e78 100644 --- a/pkg/endpoints/handlers/rest.go +++ b/pkg/endpoints/handlers/rest.go @@ -38,9 +38,9 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/managedfields" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/authorization/authorizer" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" requestmetrics "k8s.io/apiserver/pkg/endpoints/handlers/metrics" "k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" "k8s.io/apiserver/pkg/endpoints/metrics" @@ -89,7 +89,7 @@ type RequestScope struct { EquivalentResourceMapper runtime.EquivalentResourceMapper TableConvertor rest.TableConvertor - FieldManager *fieldmanager.FieldManager + FieldManager *managedfields.FieldManager Resource schema.GroupVersionResource Kind schema.GroupVersionKind diff --git a/pkg/endpoints/installer.go b/pkg/endpoints/installer.go index 3fd5f4371..3f8b6807e 100644 --- a/pkg/endpoints/installer.go +++ b/pkg/endpoints/installer.go @@ -32,12 +32,12 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/managedfields" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/endpoints/deprecation" "k8s.io/apiserver/pkg/endpoints/discovery" "k8s.io/apiserver/pkg/endpoints/handlers" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" "k8s.io/apiserver/pkg/endpoints/handlers/negotiation" "k8s.io/apiserver/pkg/endpoints/metrics" utilwarning "k8s.io/apiserver/pkg/endpoints/warning" @@ -683,7 +683,7 @@ func (a *APIInstaller) registerResourceHandlers(path string, storage rest.Storag resetFields = resetFieldsStrategy.GetResetFields() } - reqScope.FieldManager, err = fieldmanager.NewDefaultFieldManager( + reqScope.FieldManager, err = managedfields.NewDefaultFieldManager( a.group.TypeConverter, a.group.UnsafeConvertor, a.group.Defaulter, diff --git a/pkg/server/genericapiserver.go b/pkg/server/genericapiserver.go index 8a6c40e5d..4a2756c18 100644 --- a/pkg/server/genericapiserver.go +++ b/pkg/server/genericapiserver.go @@ -34,6 +34,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/apimachinery/pkg/util/managedfields" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/sets" utilwaitgroup "k8s.io/apimachinery/pkg/util/waitgroup" @@ -44,7 +45,6 @@ import ( genericapi "k8s.io/apiserver/pkg/endpoints" "k8s.io/apiserver/pkg/endpoints/discovery" discoveryendpoint "k8s.io/apiserver/pkg/endpoints/discovery/aggregated" - "k8s.io/apiserver/pkg/endpoints/handlers/fieldmanager" "k8s.io/apiserver/pkg/features" "k8s.io/apiserver/pkg/registry/rest" "k8s.io/apiserver/pkg/server/healthz" @@ -737,11 +737,11 @@ func (s preparedGenericAPIServer) NonBlockingRun(stopCh <-chan struct{}, shutdow // installAPIResources is a private method for installing the REST storage backing each api groupversionresource func (s *GenericAPIServer) installAPIResources(apiPrefix string, apiGroupInfo *APIGroupInfo, openAPIModels map[string]*spec.Schema) error { - var typeConverter fieldmanager.TypeConverter + var typeConverter managedfields.TypeConverter if len(openAPIModels) > 0 { var err error - typeConverter, err = fieldmanager.NewTypeConverter(openAPIModels, false) + typeConverter, err = managedfields.NewTypeConverter(openAPIModels, false) if err != nil { return err }