func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) { scheme := runtime.NewScheme() scheme.AddKnownTypeWithName("", "Type", &internalType{}) scheme.AddKnownTypeWithName("unlikelyversion", "Type", &externalType{}) //This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name. scheme.AddKnownTypeWithName(testapi.Version(), "Type", &ExternalType2{}) codec := runtime.CodecFor(scheme, "unlikelyversion") validVersion := testapi.Version() mapper := meta.NewDefaultRESTMapper("apitest", []string{"unlikelyversion", validVersion}, func(version string) (*meta.VersionInterfaces, error) { return &meta.VersionInterfaces{ Codec: runtime.CodecFor(scheme, version), ObjectConvertor: scheme, MetadataAccessor: meta.NewAccessor(), }, versionErrIfFalse(version == validVersion || version == "unlikelyversion") }) for _, version := range []string{"unlikelyversion", validVersion} { for kind := range scheme.KnownTypes(version) { mixedCase := false scope := meta.RESTScopeNamespace mapper.Add(scope, kind, version, mixedCase) } } return scheme, mapper, codec }
func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) { scheme := runtime.NewScheme() scheme.AddInternalGroupVersion(internalGV) scheme.AddKnownTypeWithName(internalGV.WithKind("Type"), &internalType{}) scheme.AddKnownTypeWithName(unlikelyGV.WithKind("Type"), &externalType{}) //This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name. scheme.AddKnownTypeWithName(validVersionGV.WithKind("Type"), &ExternalType2{}) codec := runtime.CodecFor(scheme, unlikelyGV) mapper := meta.NewDefaultRESTMapper([]unversioned.GroupVersion{unlikelyGV, validVersionGV}, func(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) { return &meta.VersionInterfaces{ Codec: runtime.CodecFor(scheme, version), ObjectConvertor: scheme, MetadataAccessor: meta.NewAccessor(), }, versionErrIfFalse(version == validVersionGV || version == unlikelyGV) }) for _, gv := range []unversioned.GroupVersion{unlikelyGV, validVersionGV} { for kind := range scheme.KnownTypes(gv) { gvk := gv.WithKind(kind) mixedCase := false scope := meta.RESTScopeNamespace mapper.Add(gvk, scope, mixedCase) } } return scheme, mapper, codec }
func TestTypes(t *testing.T) { for kind, reflectType := range api.Scheme.KnownTypes("") { if !strings.Contains(reflectType.PkgPath(), "/origin/") { continue } t.Logf("About to test %v", reflectType) // Try a few times, since runTest uses random values. for i := 0; i < fuzzIters; i++ { item, err := api.Scheme.New("", kind) if err != nil { t.Errorf("Couldn't make a %v? %v", kind, err) continue } if _, err := meta.TypeAccessor(item); err != nil { t.Fatalf("%q is not a TypeMeta and cannot be tested - add it to nonRoundTrippableTypes: %v", kind, err) } seed := rand.Int63() if versions, ok := skipStandardVersions[kind]; ok { for _, v := range versions { fuzzInternalObject(t, "", item, seed) roundTrip(t, runtime.CodecFor(api.Scheme, v), item) } continue } fuzzInternalObject(t, "", item, seed) roundTrip(t, osapi.Codec, item) fuzzInternalObject(t, "v1beta3", item, seed) roundTrip(t, v1beta3.Codec, item) fuzzInternalObject(t, "v1", item, seed) roundTrip(t, v1.Codec, item) } } }
func init() { externalVersions := []unversioned.GroupVersion{} for _, allowedVersion := range registered.GroupVersionsForGroup(componentconfig.GroupName) { for _, externalVersion := range availableVersions { if externalVersion == allowedVersion { externalVersions = append(externalVersions, externalVersion) } } } if len(externalVersions) == 0 { glog.V(4).Infof("No version is registered for group %v", componentconfig.GroupName) return } preferredExternalVersion := externalVersions[0] groupMeta := latest.GroupMeta{ GroupVersion: preferredExternalVersion, GroupVersions: externalVersions, Codec: runtime.CodecFor(api.Scheme, preferredExternalVersion), RESTMapper: newRESTMapper(externalVersions), SelfLinker: runtime.SelfLinker(accessor), InterfacesFor: interfacesFor, } if err := latest.RegisterGroup(groupMeta); err != nil { glog.V(4).Infof("%v", err) return } api.RegisterRESTMapper(groupMeta.RESTMapper) }
func TestEncode(t *testing.T) { internalGV := unversioned.GroupVersion{Group: "test.group", Version: ""} externalGV := unversioned.GroupVersion{Group: "test.group", Version: "testExternal"} scheme := runtime.NewScheme() scheme.AddInternalGroupVersion(internalGV) scheme.AddKnownTypeWithName(internalGV.WithKind("Simple"), &InternalSimple{}) scheme.AddKnownTypeWithName(externalGV.WithKind("Simple"), &ExternalSimple{}) codec := runtime.CodecFor(scheme, externalGV.String()) test := &InternalSimple{ TestString: "I'm the same", } obj := runtime.Object(test) data, err := runtime.Encode(codec, obj) obj2, err2 := runtime.Decode(codec, data) if err != nil || err2 != nil { t.Fatalf("Failure: '%v' '%v'", err, err2) } if _, ok := obj2.(*InternalSimple); !ok { t.Fatalf("Got wrong type") } if !reflect.DeepEqual(obj2, test) { t.Errorf("Expected:\n %#v,\n Got:\n %#v", &test, obj2) } }
func init() { groupMeta, err := latest.RegisterGroup("metrics") if err != nil { glog.V(4).Infof("%v", err) return } registeredGroupVersions := registered.GroupVersionsForGroup("metrics") groupVersion := registeredGroupVersions[0] *groupMeta = latest.GroupMeta{ GroupVersion: groupVersion, Codec: runtime.CodecFor(api.Scheme, groupVersion.String()), } worstToBestGroupVersions := []unversioned.GroupVersion{} for i := len(registeredGroupVersions) - 1; i >= 0; i-- { worstToBestGroupVersions = append(worstToBestGroupVersions, registeredGroupVersions[i]) } groupMeta.GroupVersions = registeredGroupVersions groupMeta.SelfLinker = runtime.SelfLinker(accessor) // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope rootScoped := sets.NewString() ignoredKinds := sets.NewString() groupMeta.RESTMapper = api.NewDefaultRESTMapper(worstToBestGroupVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped) api.RegisterRESTMapper(groupMeta.RESTMapper) groupMeta.InterfacesFor = interfacesFor }
func TestExperimentalEncodeDecodeStatus(t *testing.T) { // TODO: caesarxuchao: use the testapi.Extensions.Codec() once the PR that // moves experimental from v1 to v1beta1 got merged. expCodec := runtime.CodecFor(api.Scheme, v1beta1.SchemeGroupVersion) encoded, err := expCodec.Encode(status) if err != nil { t.Errorf("unexpected error: %v", err) } typeMeta := unversioned.TypeMeta{} if err := json.Unmarshal(encoded, &typeMeta); err != nil { t.Errorf("unexpected error: %v", err) } if typeMeta.Kind != "Status" { t.Errorf("Kind is not set to \"Status\". Got %s", encoded) } if typeMeta.APIVersion != "" { t.Errorf("APIVersion is not set to \"\". Got %s", encoded) } decoded, err := runtime.Decode(expCodec, encoded) if err != nil { t.Errorf("unexpected error: %v", err) } if !reflect.DeepEqual(status, decoded) { t.Errorf("expected: %v, got: %v", status, decoded) } }
func init() { groupMeta, err := latest.RegisterGroup("experimental") if err != nil { glog.V(4).Infof("%v", err) return } registeredGroupVersions := registered.GroupVersionsForGroup("experimental") groupVersion := registeredGroupVersions[0] *groupMeta = latest.GroupMeta{ GroupVersion: groupVersion, Group: apiutil.GetGroup(groupVersion), Version: apiutil.GetVersion(groupVersion), Codec: runtime.CodecFor(api.Scheme, groupVersion), } var versions []string var groupVersions []string for i := len(registeredGroupVersions) - 1; i >= 0; i-- { versions = append(versions, apiutil.GetVersion(registeredGroupVersions[i])) groupVersions = append(groupVersions, registeredGroupVersions[i]) } groupMeta.Versions = versions groupMeta.GroupVersions = groupVersions groupMeta.SelfLinker = runtime.SelfLinker(accessor) // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope rootScoped := sets.NewString() ignoredKinds := sets.NewString() groupMeta.RESTMapper = api.NewDefaultRESTMapper("experimental", groupVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped) api.RegisterRESTMapper(groupMeta.RESTMapper) groupMeta.InterfacesFor = interfacesFor }
func init() { // Use the first API version in the list of registered versions as the latest. Version = registered.RegisteredVersions[0] OldestVersion = registered.RegisteredVersions[len(registered.RegisteredVersions)-1] Codec = runtime.CodecFor(api.Scheme, Version) // Put the registered versions in Versions in reverse order. versions := registered.RegisteredVersions Versions = []string{} for i := len(versions) - 1; i >= 0; i-- { Versions = append(Versions, versions[i]) } mapper := meta.NewDefaultRESTMapper( versions, func(version string) (*meta.VersionInterfaces, bool) { interfaces, err := InterfacesFor(version) if err != nil { return nil, false } return interfaces, true }, ) // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope kindToRootScope := map[string]bool{ "Node": true, "Minion": true, "Namespace": true, "PersistentVolume": true, } // setup aliases for groups of resources mapper.AddResourceAlias("all", userResources...) // these kinds should be excluded from the list of resources ignoredKinds := util.NewStringSet( "ListOptions", "DeleteOptions", "Status", "PodLogOptions", "PodExecOptions", "PodProxyOptions") // enumerate all supported versions, get the kinds, and register with the mapper how to address our resources. for _, version := range versions { for kind := range api.Scheme.KnownTypes(version) { if ignoredKinds.Has(kind) { continue } scope := meta.RESTScopeNamespace if kindToRootScope[kind] { scope = meta.RESTScopeRoot } mapper.Add(scope, kind, version, false) } } RESTMapper = mapper }
func init() { groupMeta, err := latest.RegisterGroup("") if err != nil { glog.V(4).Infof("%v", err) return } worstToBestGroupVersions := []unversioned.GroupVersion{} // Use the first API version in the list of registered versions as the latest. registeredGroupVersions := registered.GroupVersionsForGroup("") groupVersion := registeredGroupVersions[0] *groupMeta = latest.GroupMeta{ GroupVersion: groupVersion.String(), Group: groupVersion.Group, Version: groupVersion.Version, Codec: runtime.CodecFor(api.Scheme, groupVersion.String()), } var versions []string var groupVersions []string for i := len(registeredGroupVersions) - 1; i >= 0; i-- { versions = append(versions, registeredGroupVersions[i].Version) groupVersions = append(groupVersions, registeredGroupVersions[i].String()) worstToBestGroupVersions = append(worstToBestGroupVersions, registeredGroupVersions[i]) } groupMeta.Versions = versions groupMeta.GroupVersions = groupVersions groupMeta.SelfLinker = runtime.SelfLinker(accessor) // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope rootScoped := sets.NewString( "Node", "Namespace", "PersistentVolume", "ComponentStatus", ) // these kinds should be excluded from the list of resources ignoredKinds := sets.NewString( "ListOptions", "DeleteOptions", "Status", "PodLogOptions", "PodExecOptions", "PodAttachOptions", "PodProxyOptions", "ThirdPartyResource", "ThirdPartyResourceData", "ThirdPartyResourceList") mapper := api.NewDefaultRESTMapper(worstToBestGroupVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped) // setup aliases for groups of resources mapper.AddResourceAlias("all", userResources...) groupMeta.RESTMapper = mapper api.RegisterRESTMapper(groupMeta.RESTMapper) groupMeta.InterfacesFor = interfacesFor }
func init() { scheme = runtime.NewScheme() scheme.AddKnownTypes("", &storagetesting.TestResource{}) scheme.AddKnownTypes(testapi.Default.Version(), &storagetesting.TestResource{}) codec = runtime.CodecFor(scheme, testapi.Default.Version()) scheme.AddConversionFuncs( func(in *storagetesting.TestResource, out *storagetesting.TestResource, s conversion.Scope) error { *out = *in return nil }, ) }
func serviceErrorHandler(requestResolver *APIRequestInfoResolver, apiVersions []string, serviceErr restful.ServiceError, request *restful.Request, response *restful.Response) { requestInfo, err := requestResolver.GetAPIRequestInfo(request.Request) codec := latest.GroupOrDie("").Codec if err == nil && requestInfo.APIVersion != "" { // check if the api version is valid. for _, version := range apiVersions { if requestInfo.APIVersion == version { // valid api version. codec = runtime.CodecFor(api.Scheme, requestInfo.APIVersion) break } } } errorJSON(apierrors.NewGenericServerResponse(serviceErr.Code, "", "", "", "", 0, false), codec, response.ResponseWriter) }
func init() { // hardcode these values to be correct for now. The next rebase completely changes how these are registered Version = "v1" Versions = []string{"v1"} Codec = runtime.CodecFor(api.Scheme, Version) // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope rootScoped := sets.NewString() ignoredKinds := sets.NewString() RESTMapper = api.NewDefaultRESTMapper("experimental", Versions, InterfacesFor, importPrefix, ignoredKinds, rootScoped) api.RegisterRESTMapper(RESTMapper) }
func init() { Version = registered.RegisteredVersions[0] Codec = runtime.CodecFor(api.Scheme, Version) // Put the registered versions in Versions in reverse order. for i := len(registered.RegisteredVersions) - 1; i >= 0; i-- { Versions = append(Versions, registered.RegisteredVersions[i]) } // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope rootScoped := util.NewStringSet() ignoredKinds := util.NewStringSet() RESTMapper = api.NewDefaultRESTMapper(Versions, InterfacesFor, importPrefix, ignoredKinds, rootScoped) api.RegisterRESTMapper(RESTMapper) }
// TODO: enableVersions should be centralized rather than spread in each API // group. func enableVersions(externalVersions []unversioned.GroupVersion) error { addVersionsToScheme(externalVersions...) preferredExternalVersion := externalVersions[0] groupMeta := latest.GroupMeta{ GroupVersion: preferredExternalVersion, GroupVersions: externalVersions, Codec: runtime.CodecFor(api.Scheme, preferredExternalVersion), RESTMapper: newRESTMapper(externalVersions), SelfLinker: runtime.SelfLinker(accessor), InterfacesFor: interfacesFor, } if err := latest.RegisterGroup(groupMeta); err != nil { return err } api.RegisterRESTMapper(groupMeta.RESTMapper) return nil }
func testCompatibility( t *testing.T, version string, input []byte, validator func(obj runtime.Object) fielderrors.ValidationErrorList, serialized map[string]string, ) { // Decode codec := runtime.CodecFor(api.Scheme, version) obj, err := codec.Decode(input) if err != nil { t.Fatalf("Unexpected error: %v", err) } // Validate errs := validator(obj) if len(errs) != 0 { t.Fatalf("Unexpected errors: %v", errs) } // Encode output, err := codec.Encode(obj) if err != nil { t.Fatalf("Unexpected error: %v", err) } // Validate old and new fields are encoded generic := map[string]interface{}{} if err := json.Unmarshal(output, &generic); err != nil { t.Fatalf("Unexpected error: %v", err) } for k, expectedValue := range serialized { keys := strings.Split(k, ".") if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok { t.Errorf("Unexpected error for %s: %v", k, err) } else if !reflect.DeepEqual(expectedValue, actualValue) { t.Errorf("Expected %v, got %v", expectedValue, actualValue) } } }
func init() { // Use the first API version in the list of registered versions as the latest. Version = registered.RegisteredVersions[0] OldestVersion = registered.RegisteredVersions[len(registered.RegisteredVersions)-1] Codec = runtime.CodecFor(api.Scheme, Version) // Put the registered versions in Versions in reverse order. versions := registered.RegisteredVersions Versions = []string{} for i := len(versions) - 1; i >= 0; i-- { Versions = append(Versions, versions[i]) } // the list of kinds that are scoped at the root of the api hierarchy // if a kind is not enumerated here, it is assumed to have a namespace scope rootScoped := sets.NewString( "Node", "Minion", "Namespace", "PersistentVolume", "SecurityContextConstraints", ) // these kinds should be excluded from the list of resources ignoredKinds := sets.NewString( "ListOptions", "DeleteOptions", "Status", "PodLogOptions", "PodExecOptions", "PodAttachOptions", "PodProxyOptions", "ThirdPartyResource", "ThirdPartyResourceData", "ThirdPartyResourceList") mapper := api.NewDefaultRESTMapper("api", versions, InterfacesFor, importPrefix, ignoredKinds, rootScoped) // setup aliases for groups of resources mapper.AddResourceAlias("all", userResources...) RESTMapper = mapper api.RegisterRESTMapper(RESTMapper) }
func TestEncode(t *testing.T) { scheme := runtime.NewScheme() scheme.AddKnownTypeWithName("", "Simple", &InternalSimple{}) scheme.AddKnownTypeWithName("externalVersion", "Simple", &ExternalSimple{}) codec := runtime.CodecFor(scheme, "externalVersion") test := &InternalSimple{ TestString: "I'm the same", } obj := runtime.Object(test) data, err := codec.Encode(obj) obj2, err2 := codec.Decode(data) if err != nil || err2 != nil { t.Fatalf("Failure: '%v' '%v'", err, err2) } if _, ok := obj2.(*InternalSimple); !ok { t.Fatalf("Got wrong type") } if !reflect.DeepEqual(obj2, test) { t.Errorf("Expected:\n %#v,\n Got:\n %#v", &test, obj2) } }
func init() { externalVersions := availableVersions preferredExternalVersion := externalVersions[0] addVersionsToScheme(externalVersions...) groupMeta := latest.GroupMeta{ GroupVersion: preferredExternalVersion, GroupVersions: externalVersions, Codec: runtime.CodecFor(api.Scheme, preferredExternalVersion), RESTMapper: newRESTMapper(externalVersions), SelfLinker: runtime.SelfLinker(accessor), InterfacesFor: interfacesFor, } if err := latest.RegisterGroup(groupMeta); err != nil { glog.V(4).Infof("%v", err) return } api.RegisterRESTMapper(groupMeta.RESTMapper) }
// TestTypes will try to roundtrip all OpenShift and Kubernetes stable api types func TestTypes(t *testing.T) { for kind, reflectType := range kapi.Scheme.KnownTypes(osapi.SchemeGroupVersion) { if !strings.Contains(reflectType.PkgPath(), "/origin/") && reflectType.PkgPath() != "k8s.io/kubernetes/pkg/api" { continue } if nonInternalRoundTrippableTypes.Has(kind) { continue } // Try a few times, since runTest uses random values. for i := 0; i < fuzzIters; i++ { item, err := kapi.Scheme.New(osapi.SchemeGroupVersion.WithKind(kind)) if err != nil { t.Errorf("Couldn't make a %v? %v", kind, err) continue } if _, err := meta.TypeAccessor(item); err != nil { t.Fatalf("%q is not a TypeMeta and cannot be tested - add it to nonRoundTrippableTypes: %v", kind, err) } seed := rand.Int63() if versions, ok := skipStandardVersions[kind]; ok { for _, v := range versions { t.Logf("About to test %v with %q", kind, v) fuzzInternalObject(t, v, item, seed) roundTrip(t, runtime.CodecFor(kapi.Scheme, v), item) } continue } t.Logf(`About to test %v with ""`, kind) fuzzInternalObject(t, "", item, seed) roundTrip(t, osapi.Codec, item) t.Logf(`About to test %v with "v1beta3"`, kind) fuzzInternalObject(t, "v1beta3", item, seed) roundTrip(t, v1beta3.Codec, item) t.Logf(`About to test %v with "v1"`, kind) fuzzInternalObject(t, "v1", item, seed) roundTrip(t, v1.Codec, item) } } }
*/ package api import ( "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" ) // Codec is the identity codec for this package - it can only convert itself // to itself. var Codec = runtime.CodecFor(Scheme, unversioned.GroupVersion{}) func init() { Scheme.AddDefaultingFuncs( func(obj *ListOptions) { if obj.LabelSelector == nil { obj.LabelSelector = labels.Everything() } if obj.FieldSelector == nil { obj.FieldSelector = fields.Everything() } }, ) Scheme.AddConversionFuncs( func(in *unversioned.Time, out *unversioned.Time, s conversion.Scope) error { // Cannot deep copy these, because time.Time has unexported fields.
package api import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/runtime" _ "github.com/openshift/origin/pkg/authorization/api" _ "github.com/openshift/origin/pkg/build/api" _ "github.com/openshift/origin/pkg/deploy/api" _ "github.com/openshift/origin/pkg/image/api" _ "github.com/openshift/origin/pkg/oauth/api" _ "github.com/openshift/origin/pkg/project/api" _ "github.com/openshift/origin/pkg/route/api" _ "github.com/openshift/origin/pkg/sdn/api" _ "github.com/openshift/origin/pkg/template/api" _ "github.com/openshift/origin/pkg/user/api" ) // Codec is the identity codec for this package - it can only convert itself // to itself. var Codec = runtime.CodecFor(api.Scheme, "") func init() { api.Scheme.AddKnownTypes("") }
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 v0 import ( "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apis/abac" "k8s.io/kubernetes/pkg/runtime" ) // GroupVersion is the API group and version for abac v0 var GroupVersion = unversioned.GroupVersion{Group: api.Group, Version: "v0"} // Codec encodes internal objects to the v0 version for the abac group var Codec = runtime.CodecFor(api.Scheme, GroupVersion.String()) func init() { api.Scheme.AddKnownTypes(GroupVersion, &Policy{}, ) } func (*Policy) IsAnAPIObject() {}
*/ package api import ( "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/conversion" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/runtime" ) // Codec is the identity codec for this package - it can only convert itself // to itself. var Codec = runtime.CodecFor(Scheme, "") func init() { Scheme.AddDefaultingFuncs( func(obj *ListOptions) { if obj.LabelSelector == nil { obj.LabelSelector = labels.Everything() } if obj.FieldSelector == nil { obj.FieldSelector = fields.Everything() } }, func(obj *unversioned.ListOptions) { if obj.LabelSelector.Selector == nil { obj.LabelSelector = unversioned.LabelSelector{labels.Everything()} }
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 v1alpha1 import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/runtime" ) var Codec = runtime.CodecFor(api.Scheme, "metrics/v1alpha1") func init() { // Register the API. addKnownTypes() } // Adds the list of known types to api.Scheme. func addKnownTypes() { api.Scheme.AddKnownTypes("metrics/v1alpha1", &RawNode{}, &RawPod{}, ) } func (*RawNode) IsAnAPIObject() {}
// Based on: https://github.com/openshift/origin/blob/master/pkg/api/compatibility_test.go // // TestCompatibility reencodes the input using the codec for the given // version and checks for the presence of the expected keys and absent // keys in the resulting JSON. func TestCompatibility( t *testing.T, version unversioned.GroupVersion, input []byte, validator func(obj runtime.Object) field.ErrorList, expectedKeys map[string]string, absentKeys []string, ) { // Decode codec := runtime.CodecFor(api.Scheme, version) obj, err := runtime.Decode(codec, input) if err != nil { t.Fatalf("Unexpected error: %v", err) } // Validate errs := validator(obj) if len(errs) != 0 { t.Fatalf("Unexpected validation errors: %v", errs) } // Encode output, err := runtime.Encode(codec, obj) if err != nil { t.Fatalf("Unexpected error: %v", err) } // Validate old and new fields are encoded generic := map[string]interface{}{} if err := json.Unmarshal(output, &generic); err != nil { t.Fatalf("Unexpected error: %v", err) } hasError := false for k, expectedValue := range expectedKeys { keys := strings.Split(k, ".") if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok { t.Errorf("Unexpected error for %s: %v", k, err) hasError = true } else if !reflect.DeepEqual(expectedValue, fmt.Sprintf("%v", actualValue)) { hasError = true t.Errorf("Unexpected value for %v: expected %v, got %v", k, expectedValue, actualValue) } } for _, absentKey := range absentKeys { keys := strings.Split(absentKey, ".") actualValue, ok, err := getJSONValue(generic, keys...) if err == nil || ok { t.Errorf("Unexpected value found for for key %s: %v", absentKey, actualValue) hasError = true } } if hasError { printer := new(kubectl.JSONPrinter) printer.PrintObj(obj, os.Stdout) t.Logf("2: Encoded value: %#v", string(output)) } }
// Verifies that schemas that are not in the master tree of Kubernetes can be retrieved via Get. // Because api.List is part of the Kube API, resource.Builder has to perform a conversion on // api.Scheme, which may not have access to all objects, and not all objects are at the same // internal versioning scheme. This test verifies that two isolated schemes (Test, and api.Scheme) // can be conjoined into a single output object. // // The expected behavior of the `kubectl get` command is: // 1. objects using unrecognized schemes will always be returned using that scheme/version, "unlikelyversion" in this test; // 2. if the specified output-version is a recognized, valid Scheme, then the list should use that scheme, and otherwise it will default to the client version, latest.Version in this test; // 3a. if the specified output-version is a recognized, valid Scheme, in which the requested object (replicationcontroller) can be represented, then the object should be returned using that version; // 3b. otherwise if the specified output-version is unrecognized, but the requested object (replicationcontroller) is recognized by the client's codec, then it will be converted to the client version, latest.Version in this test. func TestGetUnknownSchemaObjectListGeneric(t *testing.T) { testCases := map[string]struct { outputVersion string listVersion string testtypeVersion string rcVersion string }{ "handles specific version": { outputVersion: latest.Version, listVersion: latest.Version, testtypeVersion: "unlikelyversion", rcVersion: latest.Version, }, "handles second specific version": { outputVersion: "unlikelyversion", listVersion: latest.Version, testtypeVersion: "unlikelyversion", rcVersion: latest.Version, // see expected behavior 3b }, "handles common version": { outputVersion: testapi.Version(), listVersion: testapi.Version(), testtypeVersion: "unlikelyversion", rcVersion: testapi.Version(), }, } for k, test := range testCases { apiCodec := runtime.CodecFor(api.Scheme, testapi.Version()) regularClient := &client.FakeRESTClient{ Codec: apiCodec, Client: client.HTTPClientFunc(func(req *http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: objBody(apiCodec, &api.ReplicationController{ObjectMeta: api.ObjectMeta{Name: "foo"}})}, nil }), } f, tf, codec := NewMixedFactory(regularClient) tf.Printer = &testPrinter{} tf.Client = &client.FakeRESTClient{ Codec: codec, Client: client.HTTPClientFunc(func(req *http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: objBody(codec, &internalType{Name: "foo"})}, nil }), } tf.Namespace = "test" tf.ClientConfig = &client.Config{Version: latest.Version} buf := bytes.NewBuffer([]byte{}) cmd := NewCmdGet(f, buf) cmd.SetOutput(buf) cmd.Flags().Set("output", "json") cmd.Flags().Set("output-version", test.outputVersion) err := RunGet(f, buf, cmd, []string{"type/foo", "replicationcontrollers/foo"}, &GetOptions{}) if err != nil { t.Errorf("%s: unexpected error: %v", k, err) continue } out := make(map[string]interface{}) if err := encjson.Unmarshal(buf.Bytes(), &out); err != nil { t.Errorf("%s: unexpected error: %v\n%s", k, err, buf.String()) continue } if out["apiVersion"] != test.listVersion { t.Errorf("%s: unexpected list: %#v", k, out) } arr := out["items"].([]interface{}) if arr[0].(map[string]interface{})["apiVersion"] != test.testtypeVersion { t.Errorf("%s: unexpected list: %#v", k, out) } if arr[1].(map[string]interface{})["apiVersion"] != test.rcVersion { t.Errorf("%s: unexpected list: %#v", k, out) } } }
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 v1beta1 import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/runtime" ) var Codec = runtime.CodecFor(api.Scheme, "extensions/v1beta1") func init() { addKnownTypes() addDefaultingFuncs() addConversionFuncs() } // Adds the list of known types to api.Scheme. func addKnownTypes() { api.Scheme.AddKnownTypes("extensions/v1beta1", &ClusterAutoscaler{}, &ClusterAutoscalerList{}, &Deployment{}, &DeploymentList{}, &HorizontalPodAutoscaler{},
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 v1 import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" ) var SchemeGroupVersion = unversioned.GroupVersion{Group: "testgroup", Version: "v1"} var Codec = runtime.CodecFor(api.Scheme, SchemeGroupVersion) func init() { // Register the API. addKnownTypes() } // Adds the list of known types to api.Scheme. func addKnownTypes() { api.Scheme.AddKnownTypes(SchemeGroupVersion, &TestType{}, &TestTypeList{}, ) api.Scheme.AddKnownTypes(SchemeGroupVersion, &unversioned.ListOptions{})
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 v1beta3 import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/registered" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" ) // Codec encodes internal objects to the v1beta3 scheme var Codec = runtime.CodecFor(api.Scheme, "v1beta3") func init() { // Check if v1beta3 is in the list of supported API versions. if !registered.IsRegisteredAPIVersion("v1beta3") { return } // Register the API. addKnownTypes() addConversionFuncs() addDefaultingFuncs() } // Adds the list of known types to api.Scheme. func addKnownTypes() {