Exemple #1
0
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.Default.Version(), "Type", &ExternalType2{})

	codec := runtime.CodecFor(scheme, "unlikelyversion")
	validVersion := testapi.Default.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
}
Exemple #2
0
func init() {
	groupMeta, err := latest.RegisterGroup("extensions")
	if err != nil {
		glog.V(4).Infof("%v", err)
		return
	}
	registeredGroupVersions := registered.GroupVersionsForGroup("extensions")
	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("extensions", groupVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped)
	api.RegisterRESTMapper(groupMeta.RESTMapper)
	groupMeta.InterfacesFor = interfacesFor
}
Exemple #3
0
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 := testapi.Extensions.Codec()
	expCodec := runtime.CodecFor(api.Scheme, "extensions/v1beta1")
	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 := expCodec.Decode(encoded)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if !reflect.DeepEqual(status, decoded) {
		t.Errorf("expected: %v, got: %v", status, decoded)
	}
}
Exemple #4
0
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
}
Exemple #5
0
func init() {
	groupMeta, err := latest.RegisterGroup("")
	if err != nil {
		glog.V(4).Infof("%v", err)
		return
	}
	// 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,
		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
	// 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",
	)

	// 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("", versions, interfacesFor, importPrefix, ignoredKinds, rootScoped)
	// setup aliases for groups of resources
	mapper.AddResourceAlias("all", userResources...)
	groupMeta.RESTMapper = mapper
	api.RegisterRESTMapper(groupMeta.RESTMapper)
	groupMeta.InterfacesFor = interfacesFor
}
Exemple #6
0
func init() {
	scheme = runtime.NewScheme()
	scheme.AddKnownTypes("", &TestResource{})
	scheme.AddKnownTypes(testapi.Default.Version(), &TestResource{})
	codec = runtime.CodecFor(scheme, testapi.Default.Version())
	scheme.AddConversionFuncs(
		func(in *TestResource, out *TestResource, s conversion.Scope) error {
			*out = *in
			return nil
		},
	)
}
Exemple #7
0
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)
}
Exemple #8
0
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)
	}
}
Exemple #9
0
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 v1

import (
	"vulcan/kubernetes/pkg/api"
	"vulcan/kubernetes/pkg/api/registered"
	"vulcan/kubernetes/pkg/runtime"
)

// Codec encodes internal objects to the v1 scheme
var Codec = runtime.CodecFor(api.Scheme, "v1")

func init() {
	// Check if v1 is in the list of supported API versions.
	if !registered.IsRegisteredAPIVersion("v1") {
		return
	}

	// Register the API.
	addKnownTypes()
	addConversionFuncs()
	addDefaultingFuncs()
}

// Adds the list of known types to api.Scheme.
func addKnownTypes() {
Exemple #10
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 v1beta1

import (
	"vulcan/kubernetes/pkg/api"
	"vulcan/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",
		&Deployment{},
		&DeploymentList{},
		&HorizontalPodAutoscaler{},
		&HorizontalPodAutoscalerList{},
		&Job{},
Exemple #11
0
*/

package api

import (
	"vulcan/kubernetes/pkg/api/resource"
	"vulcan/kubernetes/pkg/api/unversioned"
	"vulcan/kubernetes/pkg/conversion"
	"vulcan/kubernetes/pkg/fields"
	"vulcan/kubernetes/pkg/labels"
	"vulcan/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) {
			obj.LabelSelector = labels.Everything()
			obj.FieldSelector = fields.Everything()
		},
		// TODO: see about moving this into v1/defaults.go
		func(obj *PodExecOptions) {
			obj.Stderr = true
			obj.Stdout = true
		},
		func(obj *PodAttachOptions) {
			obj.Stderr = true
			obj.Stdout = true
Exemple #12
0
// 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, testapi.Default.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, testapi.Default.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:   testapi.Default.Version(),
			listVersion:     testapi.Default.Version(),
			testtypeVersion: "unlikelyversion",
			rcVersion:       testapi.Default.Version(),
		},
		"handles second specific version": {
			outputVersion:   "unlikelyversion",
			listVersion:     testapi.Default.Version(),
			testtypeVersion: "unlikelyversion",
			rcVersion:       testapi.Default.Version(), // see expected behavior 3b
		},
		"handles common version": {
			outputVersion:   testapi.Default.Version(),
			listVersion:     testapi.Default.Version(),
			testtypeVersion: "unlikelyversion",
			rcVersion:       testapi.Default.Version(),
		},
	}
	for k, test := range testCases {
		apiCodec := runtime.CodecFor(api.Scheme, testapi.Default.Version())
		regularClient := &fake.RESTClient{
			Codec: apiCodec,
			Client: fake.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 = &fake.RESTClient{
			Codec: codec,
			Client: fake.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: testapi.Default.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)
		}
	}
}
Exemple #13
0
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 v1beta3

import (
	"vulcan/kubernetes/pkg/api"
	"vulcan/kubernetes/pkg/api/registered"
	"vulcan/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() {
// 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 string,
	input []byte,
	validator func(obj runtime.Object) fielderrors.ValidationErrorList,
	expectedKeys map[string]string,
	absentKeys []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 validation 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)
	}

	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))
	}
}