Esempio n. 1
0
func (m *Master) thirdpartyapi(group, kind, version string) *apiserver.APIGroupVersion {
	resourceStorage := thirdpartyresourcedataetcd.NewREST(m.thirdPartyStorage, group, kind)

	apiRoot := makeThirdPartyPath("")

	storage := map[string]rest.Storage{
		strings.ToLower(kind) + "s": resourceStorage,
	}

	return &apiserver.APIGroupVersion{
		Root:                   apiRoot,
		Version:                apiutil.GetGroupVersion(group, version),
		APIRequestInfoResolver: m.newAPIRequestInfoResolver(),

		Creater:   thirdpartyresourcedata.NewObjectCreator(group, version, api.Scheme),
		Convertor: api.Scheme,
		Typer:     api.Scheme,

		Mapper:        thirdpartyresourcedata.NewMapper(latest.GroupOrDie("experimental").RESTMapper, kind, version, group),
		Codec:         thirdpartyresourcedata.NewCodec(latest.GroupOrDie("experimental").Codec, kind),
		Linker:        latest.GroupOrDie("experimental").SelfLinker,
		Storage:       storage,
		ServerVersion: latest.GroupOrDie("").GroupVersion,

		Context: m.requestContextMapper,

		ProxyDialerFn:     m.dialer,
		MinRequestTimeout: m.minRequestTimeout,
	}
}
Esempio n. 2
0
func TestRESTMapper(t *testing.T) {
	gv := unversioned.GroupVersion{Group: componentconfig.GroupName, Version: "v1alpha1"}
	proxyGVK := gv.WithKind("KubeProxyConfiguration")

	if gvk, err := latest.GroupOrDie(componentconfig.GroupName).RESTMapper.KindFor(gv.WithResource("kubeproxyconfiguration")); err != nil || gvk != proxyGVK {
		t.Errorf("unexpected version mapping: %v %v", gvk, err)
	}

	if m, err := latest.GroupOrDie(componentconfig.GroupName).RESTMapper.RESTMapping(proxyGVK.GroupKind(), ""); err != nil || m.GroupVersionKind != proxyGVK || m.Resource != "kubeproxyconfigurations" {
		t.Errorf("unexpected version mapping: %#v %v", m, err)
	}

	for _, version := range latest.GroupOrDie(componentconfig.GroupName).GroupVersions {
		mapping, err := latest.GroupOrDie(componentconfig.GroupName).RESTMapper.RESTMapping(proxyGVK.GroupKind(), version.Version)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			continue
		}

		if mapping.Resource != "kubeproxyconfigurations" {
			t.Errorf("incorrect resource name: %#v", mapping)
		}
		if mapping.GroupVersionKind.GroupVersion() != version {
			t.Errorf("incorrect groupVersion: %v", mapping)
		}

		interfaces, _ := latest.GroupOrDie(componentconfig.GroupName).InterfacesFor(version)
		if mapping.Codec != interfaces.Codec {
			t.Errorf("unexpected codec: %#v, expected: %#v", mapping, interfaces)
		}
	}
}
Esempio n. 3
0
func init() {
	kubeTestAPI := os.Getenv("KUBE_TEST_API")
	if kubeTestAPI != "" {
		testGroupVersions := strings.Split(kubeTestAPI, ",")
		for _, groupVersion := range testGroupVersions {
			// TODO: caesarxuchao: the apiutil package is hacky, it will be replaced
			// by a following PR.
			Groups[apiutil.GetGroup(groupVersion)] =
				TestGroup{apiutil.GetGroup(groupVersion), apiutil.GetVersion(groupVersion), groupVersion}
		}
	}

	// TODO: caesarxuchao: we need a central place to store all available API
	// groups and their metadata.
	if _, ok := Groups[""]; !ok {
		// TODO: The second latest.GroupOrDie("").Version will be latest.GroupVersion after we
		// have multiple group support
		Groups[""] = TestGroup{"", latest.GroupOrDie("").Version, latest.GroupOrDie("").GroupVersion}
	}
	if _, ok := Groups["extensions"]; !ok {
		Groups["extensions"] = TestGroup{"extensions", latest.GroupOrDie("extensions").Version, latest.GroupOrDie("extensions").GroupVersion}
	}

	Default = Groups[""]
	Extensions = Groups["extensions"]
}
Esempio n. 4
0
func TestRESTMapper(t *testing.T) {
	if v, k, err := latest.GroupOrDie("componentconfig").RESTMapper.VersionAndKindForResource("kubeproxyconfiguration"); err != nil || v != "componentconfig/v1alpha1" || k != "KubeProxyConfiguration" {
		t.Errorf("unexpected version mapping: %s %s %v", v, k, err)
	}

	if m, err := latest.GroupOrDie("componentconfig").RESTMapper.RESTMapping("KubeProxyConfiguration", ""); err != nil || m.APIVersion != "componentconfig/v1alpha1" || m.Resource != "kubeproxyconfigurations" {
		t.Errorf("unexpected version mapping: %#v %v", m, err)
	}

	for _, groupVersion := range latest.GroupOrDie("componentconfig").GroupVersions {
		mapping, err := latest.GroupOrDie("componentconfig").RESTMapper.RESTMapping("KubeProxyConfiguration", groupVersion)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
		}

		if mapping.Resource != "kubeproxyconfigurations" {
			t.Errorf("incorrect resource name: %#v", mapping)
		}
		if mapping.APIVersion != groupVersion {
			t.Errorf("incorrect groupVersion: %v", mapping)
		}

		interfaces, _ := latest.GroupOrDie("componentconfig").InterfacesFor(groupVersion)
		if mapping.Codec != interfaces.Codec {
			t.Errorf("unexpected codec: %#v, expected: %#v", mapping, interfaces)
		}
	}
}
Esempio n. 5
0
func (m *Master) thirdpartyapi(group, kind, version string) *apiserver.APIGroupVersion {
	resourceStorage := thirdpartyresourcedataetcd.NewREST(m.thirdPartyStorage, group, kind)

	apiRoot := "/thirdparty/" + group + "/"

	storage := map[string]rest.Storage{
		strings.ToLower(kind) + "s": resourceStorage,
	}

	return &apiserver.APIGroupVersion{
		Root: apiRoot,

		Creater:   thirdpartyresourcedata.NewObjectCreator(version, api.Scheme),
		Convertor: api.Scheme,
		Typer:     api.Scheme,

		Mapper:  thirdpartyresourcedata.NewMapper(latest.GroupOrDie("experimental").RESTMapper, kind, version),
		Codec:   latest.GroupOrDie("experimental").Codec,
		Linker:  latest.GroupOrDie("experimental").SelfLinker,
		Storage: storage,
		Version: version,

		Admit:   m.admissionControl,
		Context: m.requestContextMapper,

		ProxyDialerFn:     m.dialer,
		MinRequestTimeout: m.minRequestTimeout,
	}
}
Esempio n. 6
0
func (m *Master) thirdpartyapi(group, kind, version string) *apiserver.APIGroupVersion {
	resourceStorage := thirdpartyresourcedataetcd.NewREST(m.thirdPartyStorage, generic.UndecoratedStorage, group, kind)

	apiRoot := makeThirdPartyPath("")

	storage := map[string]rest.Storage{
		strings.ToLower(kind) + "s": resourceStorage,
	}

	serverGroupVersion := unversioned.ParseGroupVersionOrDie(latest.GroupOrDie("").GroupVersion)

	return &apiserver.APIGroupVersion{
		Root:                apiRoot,
		GroupVersion:        unversioned.GroupVersion{Group: group, Version: version},
		RequestInfoResolver: m.newRequestInfoResolver(),

		Creater:   thirdpartyresourcedata.NewObjectCreator(group, version, api.Scheme),
		Convertor: api.Scheme,
		Typer:     api.Scheme,

		Mapper:             thirdpartyresourcedata.NewMapper(latest.GroupOrDie("extensions").RESTMapper, kind, version, group),
		Codec:              thirdpartyresourcedata.NewCodec(latest.GroupOrDie("extensions").Codec, kind),
		Linker:             latest.GroupOrDie("extensions").SelfLinker,
		Storage:            storage,
		ServerGroupVersion: &serverGroupVersion,

		Context: m.requestContextMapper,

		MinRequestTimeout: m.minRequestTimeout,
	}
}
Esempio n. 7
0
// TODO: Merge this into startMasterOrDie.
func RunAMaster(t *testing.T) (*master.Master, *httptest.Server) {
	etcdClient := NewEtcdClient()
	etcdStorage, err := master.NewEtcdStorage(etcdClient, latest.GroupOrDie("").InterfacesFor, testapi.Default.Version(), etcdtest.PathPrefix())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	expEtcdStorage, err := master.NewEtcdStorage(etcdClient, latest.GroupOrDie("experimental").InterfacesFor, latest.GroupOrDie("experimental").Version, etcdtest.PathPrefix())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	m := master.New(&master.Config{
		DatabaseStorage:    etcdStorage,
		ExpDatabaseStorage: expEtcdStorage,
		KubeletClient:      client.FakeKubeletClient{},
		EnableLogsSupport:  false,
		EnableProfiling:    true,
		EnableUISupport:    false,
		APIPrefix:          "/api",
		APIGroupPrefix:     "/apis",
		EnableExp:          true,
		Authorizer:         apiserver.NewAlwaysAllowAuthorizer(),
		AdmissionControl:   admit.NewAlwaysAdmit(),
	})

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		m.Handler.ServeHTTP(w, req)
	}))

	return m, s
}
Esempio n. 8
0
// experimental returns the resources and codec for the experimental api
func (m *Master) experimental(c *Config) *apiserver.APIGroupVersion {
	controllerStorage := expcontrolleretcd.NewStorage(c.DatabaseStorage)
	autoscalerStorage := horizontalpodautoscaleretcd.NewREST(c.ExpDatabaseStorage)
	thirdPartyResourceStorage := thirdpartyresourceetcd.NewREST(c.ExpDatabaseStorage)
	daemonSetStorage, daemonSetStatusStorage := daemonetcd.NewREST(c.ExpDatabaseStorage)
	deploymentStorage := deploymentetcd.NewStorage(c.ExpDatabaseStorage)
	jobStorage, jobStatusStorage := jobetcd.NewREST(c.ExpDatabaseStorage)

	thirdPartyControl := ThirdPartyController{
		master: m,
		thirdPartyResourceRegistry: thirdPartyResourceStorage,
	}
	go func() {
		util.Forever(func() {
			if err := thirdPartyControl.SyncResources(); err != nil {
				glog.Warningf("third party resource sync failed: %v", err)
			}
		}, 10*time.Second)
	}()
	storage := map[string]rest.Storage{
		strings.ToLower("replicationControllers"):       controllerStorage.ReplicationController,
		strings.ToLower("replicationControllers/scale"): controllerStorage.Scale,
		strings.ToLower("horizontalpodautoscalers"):     autoscalerStorage,
		strings.ToLower("thirdpartyresources"):          thirdPartyResourceStorage,
		strings.ToLower("daemonsets"):                   daemonSetStorage,
		strings.ToLower("daemonsets/status"):            daemonSetStatusStorage,
		strings.ToLower("deployments"):                  deploymentStorage.Deployment,
		strings.ToLower("deployments/scale"):            deploymentStorage.Scale,
		strings.ToLower("jobs"):                         jobStorage,
		strings.ToLower("jobs/status"):                  jobStatusStorage,
	}

	expMeta := latest.GroupOrDie("experimental")

	return &apiserver.APIGroupVersion{
		Root: m.apiGroupPrefix,
		APIRequestInfoResolver: m.newAPIRequestInfoResolver(),

		Creater:   api.Scheme,
		Convertor: api.Scheme,
		Typer:     api.Scheme,

		Mapper:        expMeta.RESTMapper,
		Codec:         expMeta.Codec,
		Linker:        expMeta.SelfLinker,
		Storage:       storage,
		Version:       expMeta.GroupVersion,
		ServerVersion: latest.GroupOrDie("").GroupVersion,

		Admit:   m.admissionControl,
		Context: m.requestContextMapper,

		ProxyDialerFn:     m.dialer,
		MinRequestTimeout: m.minRequestTimeout,
	}
}
Esempio n. 9
0
func TestInterfacesFor(t *testing.T) {
	if _, err := latest.GroupOrDie("componentconfig").InterfacesFor(""); err == nil {
		t.Fatalf("unexpected non-error: %v", err)
	}
	for i, groupVersion := range append([]unversioned.GroupVersion{latest.GroupOrDie("componentconfig").GroupVersion}, latest.GroupOrDie("componentconfig").GroupVersions...) {
		if vi, err := latest.GroupOrDie("componentconfig").InterfacesFor(groupVersion.String()); err != nil || vi == nil {
			t.Fatalf("%d: unexpected result: %v", i, err)
		}
	}
}
Esempio n. 10
0
func TestInterfacesFor(t *testing.T) {
	if _, err := latest.GroupOrDie("extensions").InterfacesFor(""); err == nil {
		t.Fatalf("unexpected non-error: %v", err)
	}
	for i, groupVersion := range append([]string{latest.GroupOrDie("extensions").GroupVersion}, latest.GroupOrDie("extensions").GroupVersions...) {
		if vi, err := latest.GroupOrDie("extensions").InterfacesFor(groupVersion); err != nil || vi == nil {
			t.Fatalf("%d: unexpected result: %v", i, err)
		}
	}
}
Esempio n. 11
0
func TestInterfacesFor(t *testing.T) {
	if _, err := latest.GroupOrDie(extensions.GroupName).InterfacesFor(extensions.SchemeGroupVersion); err == nil {
		t.Fatalf("unexpected non-error: %v", err)
	}
	for i, version := range latest.GroupOrDie(extensions.GroupName).GroupVersions {
		if vi, err := latest.GroupOrDie(extensions.GroupName).InterfacesFor(version); err != nil || vi == nil {
			t.Fatalf("%d: unexpected result: %v", i, err)
		}
	}
}
Esempio n. 12
0
// TestExpapi verifies that the unexported exapi creates
// the an experimental unversioned.APIGroupVersion.
func TestExpapi(t *testing.T) {
	master, config, assert := setUp(t)

	expAPIGroup := master.experimental(&config)
	assert.Equal(expAPIGroup.Root, master.apiGroupPrefix)
	assert.Equal(expAPIGroup.Mapper, latest.GroupOrDie("extensions").RESTMapper)
	assert.Equal(expAPIGroup.Codec, latest.GroupOrDie("extensions").Codec)
	assert.Equal(expAPIGroup.Linker, latest.GroupOrDie("extensions").SelfLinker)
	assert.Equal(expAPIGroup.Version, latest.GroupOrDie("extensions").GroupVersion)
}
Esempio n. 13
0
func TestCodec(t *testing.T) {
	pod := internal.Pod{}
	// We do want to use package latest rather than testapi here, because we
	// want to test if the package install and package latest work as expected.
	data, err := latest.GroupOrDie(internal.GroupName).Codec.Encode(&pod)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	other := internal.Pod{}
	if err := json.Unmarshal(data, &other); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if other.APIVersion != latest.GroupOrDie(internal.GroupName).GroupVersion.Version || other.Kind != "Pod" {
		t.Errorf("unexpected unmarshalled object %#v", other)
	}
}
Esempio n. 14
0
func init() {
	kubeTestAPI := os.Getenv("KUBE_TEST_API")
	if kubeTestAPI != "" {
		testGroupVersions := strings.Split(kubeTestAPI, ",")
		for _, gvString := range testGroupVersions {
			groupVersion, err := unversioned.ParseGroupVersion(gvString)
			if err != nil {
				panic(fmt.Sprintf("Error parsing groupversion %v: %v", gvString, err))
			}

			Groups[groupVersion.Group] = TestGroup{
				externalGroupVersion: groupVersion,
				internalGroupVersion: unversioned.GroupVersion{Group: groupVersion.Group},
			}
		}
	}

	if _, ok := Groups[api.GroupName]; !ok {
		Groups[api.GroupName] = TestGroup{
			externalGroupVersion: unversioned.GroupVersion{Group: api.GroupName, Version: latest.GroupOrDie(api.GroupName).GroupVersion.Version},
			internalGroupVersion: api.SchemeGroupVersion,
		}
	}
	if _, ok := Groups[extensions.GroupName]; !ok {
		Groups[extensions.GroupName] = TestGroup{
			externalGroupVersion: unversioned.GroupVersion{Group: extensions.GroupName, Version: latest.GroupOrDie(extensions.GroupName).GroupVersion.Version},
			internalGroupVersion: extensions.SchemeGroupVersion,
		}
	}

	Default = Groups[api.GroupName]
	Extensions = Groups[extensions.GroupName]
}
Esempio n. 15
0
// SwaggerSchema retrieves and parses the swagger API schema the server supports.
func (c *Client) SwaggerSchema(version string) (*swagger.ApiDeclaration, error) {
	if version == "" {
		version = latest.GroupOrDie("").Version
	}

	vers, err := c.ServerAPIVersions()
	if err != nil {
		return nil, err
	}

	// This check also takes care the case that kubectl is newer than the running endpoint
	if stringDoesntExistIn(version, vers.Versions) {
		return nil, fmt.Errorf("API version: %s is not supported by the server. Use one of: %v", version, vers.Versions)
	}

	body, err := c.Get().AbsPath("/swaggerapi/api/" + version).Do().Raw()
	if err != nil {
		return nil, err
	}
	var schema swagger.ApiDeclaration
	err = json.Unmarshal(body, &schema)
	if err != nil {
		return nil, fmt.Errorf("got '%s': %v", string(body), err)
	}
	return &schema, nil
}
Esempio n. 16
0
func (config *KubeProxyTestConfig) createTestPodSpec() *api.Pod {
	pod := &api.Pod{
		TypeMeta: unversioned.TypeMeta{
			Kind:       "Pod",
			APIVersion: latest.GroupOrDie("").Version,
		},
		ObjectMeta: api.ObjectMeta{
			Name:      testPodName,
			Namespace: config.f.Namespace.Name,
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:            "webserver",
					Image:           netexecImageName,
					ImagePullPolicy: api.PullIfNotPresent,
					Command: []string{
						"/netexec",
						fmt.Sprintf("--http-port=%d", endpointHttpPort),
						fmt.Sprintf("--udp-port=%d", endpointUdpPort),
					},
					Ports: []api.ContainerPort{
						{
							Name:          "http",
							ContainerPort: testContainerHttpPort,
						},
					},
				},
			},
		},
	}
	return pod
}
Esempio n. 17
0
func setExperimentalDefaults(config *Config) error {
	// if experimental group is not registered, return an error
	g, err := latest.Group("experimental")
	if err != nil {
		return err
	}
	config.Prefix = "apis/" + g.Group
	if config.UserAgent == "" {
		config.UserAgent = DefaultKubernetesUserAgent()
	}
	if config.Version == "" {
		config.Version = g.Version
	}

	versionInterfaces, err := g.InterfacesFor(config.Version)
	if err != nil {
		return fmt.Errorf("Experimental API version '%s' is not recognized (valid values: %s)",
			config.Version, strings.Join(latest.GroupOrDie("experimental").Versions, ", "))
	}
	if config.Codec == nil {
		config.Codec = versionInterfaces.Codec
	}
	if config.QPS == 0 {
		config.QPS = 5
	}
	if config.Burst == 0 {
		config.Burst = 10
	}
	return nil
}
Esempio n. 18
0
func runAMaster(t *testing.T) (*master.Master, *httptest.Server) {
	etcdStorage, err := master.NewEtcdStorage(newEtcdClient(), latest.GroupOrDie("").InterfacesFor, testapi.Default.Version(), etcdtest.PathPrefix())
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	storageDestinations := master.NewStorageDestinations()
	storageDestinations.AddAPIGroup("", etcdStorage)

	m := master.New(&master.Config{
		StorageDestinations:   storageDestinations,
		KubeletClient:         client.FakeKubeletClient{},
		EnableCoreControllers: true,
		EnableLogsSupport:     false,
		EnableProfiling:       true,
		EnableUISupport:       false,
		APIPrefix:             "/api",
		Authorizer:            apiserver.NewAlwaysAllowAuthorizer(),
		AdmissionControl:      admit.NewAlwaysAdmit(),
		StorageVersions:       map[string]string{"": testapi.Default.Version()},
	})

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		m.Handler.ServeHTTP(w, req)
	}))

	return m, s
}
Esempio n. 19
0
func TestCodec(t *testing.T) {
	daemonSet := componentconfig.KubeProxyConfiguration{}
	// We do want to use package latest rather than testapi here, because we
	// want to test if the package install and package latest work as expected.
	data, err := latest.GroupOrDie("componentconfig").Codec.Encode(&daemonSet)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	other := componentconfig.KubeProxyConfiguration{}
	if err := json.Unmarshal(data, &other); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if other.APIVersion != latest.GroupOrDie("componentconfig").GroupVersion || other.Kind != "KubeProxyConfiguration" {
		t.Errorf("unexpected unmarshalled object %#v", other)
	}
}
Esempio n. 20
0
// MetadataAccessor returns the MetadataAccessor for the API version to test against,
// as set by the KUBE_TEST_API env var.
func (g TestGroup) MetadataAccessor() meta.MetadataAccessor {
	interfaces, err := latest.GroupOrDie(g.externalGroupVersion.Group).InterfacesFor(g.externalGroupVersion)
	if err != nil {
		panic(err)
	}
	return interfaces.MetadataAccessor
}
Esempio n. 21
0
func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod {
	pod := &api.Pod{
		TypeMeta: unversioned.TypeMeta{
			Kind:       "Pod",
			APIVersion: latest.GroupOrDie(api.GroupName).GroupVersion.Version,
		},
		ObjectMeta: api.ObjectMeta{
			Name:      podName,
			Namespace: config.f.Namespace.Name,
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:            "busybox-1",
					Image:           kubeletEtcHostsImageName,
					ImagePullPolicy: api.PullIfNotPresent,
					Command: []string{
						"sleep",
						"900",
					},
				},
				{
					Name:            "busybox-2",
					Image:           kubeletEtcHostsImageName,
					ImagePullPolicy: api.PullIfNotPresent,
					Command: []string{
						"sleep",
						"900",
					},
				},
				{
					Name:            "busybox-3",
					Image:           kubeletEtcHostsImageName,
					ImagePullPolicy: api.PullIfNotPresent,
					Command: []string{
						"sleep",
						"900",
					},
					VolumeMounts: []api.VolumeMount{
						{
							Name:      "host-etc-hosts",
							MountPath: "/etc/hosts",
						},
					},
				},
			},
			Volumes: []api.Volume{
				{
					Name: "host-etc-hosts",
					VolumeSource: api.VolumeSource{
						HostPath: &api.HostPathVolumeSource{
							Path: "/etc/hosts",
						},
					},
				},
			},
		},
	}
	return pod
}
Esempio n. 22
0
func setExtensionsDefaults(config *Config) error {
	// if experimental group is not registered, return an error
	g, err := latest.Group("extensions")
	if err != nil {
		return err
	}
	config.Prefix = "apis/"
	if config.UserAgent == "" {
		config.UserAgent = DefaultKubernetesUserAgent()
	}
	// TODO: Unconditionally set the config.Version, until we fix the config.
	//if config.Version == "" {
	gv, err := unversioned.ParseGroupVersion(g.GroupVersion)
	if err != nil {
		return err
	}
	config.GroupVersion = &gv
	//}

	versionInterfaces, err := g.InterfacesFor(config.GroupVersion.String())
	if err != nil {
		return fmt.Errorf("Extensions API group/version '%v' is not recognized (valid values: %s)",
			config.GroupVersion, strings.Join(latest.GroupOrDie("extensions").Versions, ", "))
	}
	config.Codec = versionInterfaces.Codec
	if config.QPS == 0 {
		config.QPS = 5
	}
	if config.Burst == 0 {
		config.Burst = 10
	}
	return nil
}
Esempio n. 23
0
func TestCodec(t *testing.T) {
	daemonSet := extensions.DaemonSet{}
	// We do want to use package latest rather than testapi here, because we
	// want to test if the package install and package latest work as expected.
	data, err := latest.GroupOrDie(extensions.GroupName).Codec.Encode(&daemonSet)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	other := extensions.DaemonSet{}
	if err := json.Unmarshal(data, &other); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if other.APIVersion != latest.GroupOrDie(extensions.GroupName).GroupVersion.String() || other.Kind != "DaemonSet" {
		t.Errorf("unexpected unmarshalled object %#v", other)
	}
}
Esempio n. 24
0
func setExtensionsDefaults(config *Config) error {
	// if experimental group is not registered, return an error
	g, err := latest.Group(extensions.GroupName)
	if err != nil {
		return err
	}
	config.APIPath = defaultAPIPath
	if config.UserAgent == "" {
		config.UserAgent = DefaultKubernetesUserAgent()
	}
	// TODO: Unconditionally set the config.Version, until we fix the config.
	//if config.Version == "" {
	copyGroupVersion := g.GroupVersion
	config.GroupVersion = &copyGroupVersion
	//}

	versionInterfaces, err := g.InterfacesFor(*config.GroupVersion)
	if err != nil {
		return fmt.Errorf("Extensions API group/version '%v' is not recognized (valid values: %v)",
			config.GroupVersion, latest.GroupOrDie(extensions.GroupName).GroupVersions)
	}
	config.Codec = versionInterfaces.Codec
	if config.QPS == 0 {
		config.QPS = 5
	}
	if config.Burst == 0 {
		config.Burst = 10
	}
	return nil
}
Esempio n. 25
0
// Converter returns the api.Scheme for the API version to test against, as set by the
// KUBE_TEST_API env var.
func (g TestGroup) Converter() runtime.ObjectConvertor {
	interfaces, err := latest.GroupOrDie(g.externalGroupVersion.Group).InterfacesFor(g.externalGroupVersion)
	if err != nil {
		panic(err)
	}
	return interfaces.ObjectConvertor
}
Esempio n. 26
0
// encodePods creates an api.PodList object from pods and returns the encoded
// PodList.
func encodePods(pods []*api.Pod) (data []byte, err error) {
	podList := new(api.PodList)
	for _, pod := range pods {
		podList.Items = append(podList.Items, *pod)
	}
	return latest.GroupOrDie("").Codec.Encode(podList)
}
Esempio n. 27
0
func rcByNameContainer(name string, replicas int, image string, labels map[string]string, c api.Container) *api.ReplicationController {
	// Add "name": name to the labels, overwriting if it exists.
	labels["name"] = name
	return &api.ReplicationController{
		TypeMeta: unversioned.TypeMeta{
			Kind:       "ReplicationController",
			APIVersion: latest.GroupOrDie("").Version,
		},
		ObjectMeta: api.ObjectMeta{
			Name: name,
		},
		Spec: api.ReplicationControllerSpec{
			Replicas: replicas,
			Selector: map[string]string{
				"name": name,
			},
			Template: &api.PodTemplateSpec{
				ObjectMeta: api.ObjectMeta{
					Labels: labels,
				},
				Spec: api.PodSpec{
					Containers: []api.Container{c},
				},
			},
		},
	}
}
Esempio n. 28
0
func testPodWithVolume(image, path string, source *api.EmptyDirVolumeSource) *api.Pod {
	podName := "pod-" + string(util.NewUUID())
	return &api.Pod{
		TypeMeta: unversioned.TypeMeta{
			Kind:       "Pod",
			APIVersion: latest.GroupOrDie("").Version,
		},
		ObjectMeta: api.ObjectMeta{
			Name: podName,
		},
		Spec: api.PodSpec{
			Containers: []api.Container{
				{
					Name:  containerName,
					Image: image,
					VolumeMounts: []api.VolumeMount{
						{
							Name:      volumeName,
							MountPath: path,
						},
					},
				},
			},
			RestartPolicy: api.RestartPolicyNever,
			Volumes: []api.Volume{
				{
					Name: volumeName,
					VolumeSource: api.VolumeSource{
						EmptyDir: source,
					},
				},
			},
		},
	}
}
Esempio n. 29
0
// SetKubernetesDefaults sets default values on the provided client config for accessing the
// Kubernetes API or returns an error if any of the defaults are impossible or invalid.
// TODO: this method needs to be split into one that sets defaults per group, expected to be fix in PR "Refactoring clientcache.go and helper.go #14592"
func SetKubernetesDefaults(config *Config) error {
	if config.Prefix == "" {
		config.Prefix = "/api"
	}
	if len(config.UserAgent) == 0 {
		config.UserAgent = DefaultKubernetesUserAgent()
	}
	if config.GroupVersion == nil {
		config.GroupVersion = defaultVersionFor(config)
	}
	versionInterfaces, err := latest.GroupOrDie("").InterfacesFor(config.GroupVersion.String())
	if err != nil {
		return fmt.Errorf("API version '%v' is not recognized (valid values: %s)", *config.GroupVersion, strings.Join(latest.GroupOrDie("").Versions, ", "))
	}
	if config.Codec == nil {
		config.Codec = versionInterfaces.Codec
	}
	if config.QPS == 0.0 {
		config.QPS = 5.0
	}
	if config.Burst == 0 {
		config.Burst = 10
	}
	return nil
}
Esempio n. 30
0
func TestImageStreamImportUnsupported(t *testing.T) {
	testCases := []struct {
		status unversioned.Status
		errFn  func(err error) bool
	}{
		{
			status: errors.NewNotFound("", "").(kclient.APIStatus).Status(),
			errFn:  func(err error) bool { return err == ErrImageStreamImportUnsupported },
		},
		{
			status: errors.NewNotFound("Other", "").(kclient.APIStatus).Status(),
			errFn:  func(err error) bool { return err != ErrImageStreamImportUnsupported && errors.IsNotFound(err) },
		},
		{
			status: errors.NewConflict("Other", "", nil).(kclient.APIStatus).Status(),
			errFn:  func(err error) bool { return err != ErrImageStreamImportUnsupported && errors.IsConflict(err) },
		},
	}
	for i, test := range testCases {
		c, err := New(&kclient.Config{
			Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
				buf := bytes.NewBuffer([]byte(runtime.EncodeOrDie(latest.GroupOrDie("").Codec, &test.status)))
				return &http.Response{StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(buf)}, nil
			}),
		})
		if err != nil {
			t.Fatal(err)
		}
		if _, err := c.ImageStreams("test").Import(&api.ImageStreamImport{}); !test.errFn(err) {
			t.Errorf("%d: error: %v", i, err)
		}
	}
}