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"] }
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), 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, ServerVersion: latest.GroupOrDie("").GroupVersion, Context: m.requestContextMapper, MinRequestTimeout: m.minRequestTimeout, } }
// 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) }
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) } } }
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, }, }, }, }, } }
// 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) }
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}, }, }, }, } }
func (config *KubeletManagedHostConfig) createPodSpec(podName string) *api.Pod { pod := &api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", APIVersion: latest.GroupOrDie("").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 }
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").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").GroupVersion || other.Kind != "DaemonSet" { t.Errorf("unexpected unmarshalled object %#v", other) } }
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 == "" { config.Version = g.GroupVersion //} versionInterfaces, err := g.InterfacesFor(config.Version) if err != nil { return fmt.Errorf("Extensions API version '%s' is not recognized (valid values: %s)", config.Version, 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 }
// 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 len(config.Version) == 0 { config.Version = defaultVersionFor(config) } version := config.Version versionInterfaces, err := latest.GroupOrDie("").InterfacesFor(version) if err != nil { return fmt.Errorf("API version '%s' is not recognized (valid values: %s)", version, 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 }
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 }
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 }
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("").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("").Version || other.Kind != "Pod" { t.Errorf("unexpected unmarshalled object %#v", other) } }
func (m *Master) defaultAPIGroupVersion() *apiserver.APIGroupVersion { return &apiserver.APIGroupVersion{ Root: m.apiPrefix, Mapper: latest.GroupOrDie("").RESTMapper, Creater: api.Scheme, Convertor: api.Scheme, Typer: api.Scheme, Linker: latest.GroupOrDie("").SelfLinker, Admit: m.admissionControl, Context: m.requestContextMapper, MinRequestTimeout: m.minRequestTimeout, } }
// 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 { // TODO: caesarxuchao: Restructure the body once we have a central `latest`. if g.Group == "" { interfaces, err := latest.GroupOrDie("").InterfacesFor(g.VersionUnderTest) if err != nil { panic(err) } return interfaces.MetadataAccessor } if g.Group == "extensions" { interfaces, err := latest.GroupOrDie("extensions").InterfacesFor(g.VersionUnderTest) if err != nil { panic(err) } return interfaces.MetadataAccessor } panic(fmt.Errorf("cannot test group %s", g.Group)) }
// Codec returns the codec for the API version to test against, as set by the // KUBE_TEST_API env var. func (g TestGroup) Codec() runtime.Codec { // TODO: caesarxuchao: Restructure the body once we have a central `latest`. if g.Group == "" { interfaces, err := latest.GroupOrDie("").InterfacesFor(g.GroupVersionUnderTest) if err != nil { panic(err) } return interfaces.Codec } if g.Group == "extensions" { interfaces, err := latest.GroupOrDie("extensions").InterfacesFor(g.GroupVersionUnderTest) if err != nil { panic(err) } return interfaces.Codec } panic(fmt.Errorf("cannot test group %s", g.Group)) }
// defaultVersionFor is shared between defaultServerUrlFor and RESTClientFor func defaultVersionFor(config *Config) string { version := config.Version if version == "" { // Clients default to the preferred code API version // TODO: implement version negotiation (highest version supported by server) version = latest.GroupOrDie("").Version } return version }
// SavePodToFile will encode and save a pod to a given path & permissions func SavePodToFile(pod *api.Pod, filePath string, perm os.FileMode) error { if filePath == "" { return fmt.Errorf("file path not specified") } data, err := latest.GroupOrDie("").Codec.Encode(pod) if err != nil { return fmt.Errorf("failed encoding pod: %v", err) } return ioutil.WriteFile(filePath, data, perm) }
// Delete deletes a job, returns error if one occurs. func (c *jobs) Delete(name string, options *api.DeleteOptions) (err error) { if options == nil { return c.r.Delete().Namespace(c.ns).Resource("jobs").Name(name).Do().Error() } body, err := api.Scheme.EncodeToVersion(options, latest.GroupOrDie("").GroupVersion) if err != nil { return err } return c.r.Delete().Namespace(c.ns).Resource("jobs").Name(name).Body(body).Do().Error() }
// startMasterOrDie starts a kubernetes master and an httpserver to handle api requests func startMasterOrDie(masterConfig *master.Config) (*master.Master, *httptest.Server) { var m *master.Master s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { m.Handler.ServeHTTP(w, req) })) if masterConfig == nil { etcdClient := NewEtcdClient() storageVersions := make(map[string]string) etcdStorage, err := master.NewEtcdStorage(etcdClient, latest.GroupOrDie("").InterfacesFor, latest.GroupOrDie("").GroupVersion, etcdtest.PathPrefix()) storageVersions[""] = latest.GroupOrDie("").GroupVersion if err != nil { glog.Fatalf("Failed to create etcd storage for master %v", err) } expEtcdStorage, err := NewExtensionsEtcdStorage(etcdClient) storageVersions["extensions"] = testapi.Extensions.GroupAndVersion() if err != nil { glog.Fatalf("Failed to create etcd storage for master %v", err) } storageDestinations := master.NewStorageDestinations() storageDestinations.AddAPIGroup("", etcdStorage) storageDestinations.AddAPIGroup("extensions", expEtcdStorage) masterConfig = &master.Config{ StorageDestinations: storageDestinations, StorageVersions: storageVersions, KubeletClient: client.FakeKubeletClient{}, EnableLogsSupport: false, EnableProfiling: true, EnableSwaggerSupport: true, EnableUISupport: false, APIPrefix: "/api", APIGroupPrefix: "/apis", Authorizer: apiserver.NewAlwaysAllowAuthorizer(), AdmissionControl: admit.NewAlwaysAdmit(), } } m = master.New(masterConfig) return m, s }
func TestSavePodToFile(t *testing.T) { pod := volume.NewPersistentVolumeRecyclerPodTemplate() // sets all default values on a pod for equality comparison after decoding from file encoded, err := latest.GroupOrDie("").Codec.Encode(pod) latest.GroupOrDie("").Codec.DecodeInto(encoded, pod) path := fmt.Sprintf("/tmp/kube-io-test-%s", uuid.New()) defer os.Remove(path) if err := io.SavePodToFile(pod, path, 777); err != nil { t.Fatalf("failed to save pod to file: %v", err) } podFromFile, err := io.LoadPodFromFile(path) if err != nil { t.Fatalf("failed to load pod from file: %v", err) } if !api.Semantic.DeepEqual(pod, podFromFile) { t.Errorf("\nexpected %#v\ngot %#v\n", pod, podFromFile) } }
// TestNewEtcdStorage verifies that the usage of NewEtcdStorage reacts properly when // the correct data is input func TestNewEtcdStorage(t *testing.T) { assert := assert.New(t) fakeClient := tools.NewFakeEtcdClient(t) // Pass case _, err := NewEtcdStorage(fakeClient, latest.GroupOrDie("").InterfacesFor, testapi.Default.Version(), etcdtest.PathPrefix()) assert.NoError(err, "Unable to create etcdstorage: %s", err) // Fail case errorFunc := func(apiVersion string) (*meta.VersionInterfaces, error) { return nil, errors.New("ERROR") } _, err = NewEtcdStorage(fakeClient, errorFunc, testapi.Default.Version(), etcdtest.PathPrefix()) assert.Error(err, "NewEtcdStorage should have failed") }
func TestRESTMapper(t *testing.T) { if v, k, err := latest.GroupOrDie("extensions").RESTMapper.VersionAndKindForResource("horizontalpodautoscalers"); err != nil || v != "extensions/v1beta1" || k != "HorizontalPodAutoscaler" { t.Errorf("unexpected version mapping: %s %s %v", v, k, err) } if m, err := latest.GroupOrDie("extensions").RESTMapper.RESTMapping("DaemonSet", ""); err != nil || m.APIVersion != "extensions/v1beta1" || m.Resource != "daemonsets" { t.Errorf("unexpected version mapping: %#v %v", m, err) } for _, groupVersion := range latest.GroupOrDie("extensions").GroupVersions { mapping, err := latest.GroupOrDie("extensions").RESTMapper.RESTMapping("HorizontalPodAutoscaler", groupVersion) if err != nil { t.Errorf("unexpected error: %v", err) } if mapping.Resource != "horizontalpodautoscalers" { t.Errorf("incorrect resource name: %#v", mapping) } if mapping.APIVersion != groupVersion { t.Errorf("incorrect groupVersion: %v", mapping) } interfaces, _ := latest.GroupOrDie("extensions").InterfacesFor(groupVersion) if mapping.Codec != interfaces.Codec { t.Errorf("unexpected codec: %#v, expected: %#v", mapping, interfaces) } rc := &extensions.HorizontalPodAutoscaler{ObjectMeta: api.ObjectMeta{Name: "foo"}} name, err := mapping.MetadataAccessor.Name(rc) if err != nil { t.Errorf("unexpected error: %v", err) } if name != "foo" { t.Errorf("unable to retrieve object meta with: %v", mapping.MetadataAccessor) } } }
func TestRESTMapper(t *testing.T) { if v, k, err := latest.GroupOrDie("").RESTMapper.VersionAndKindForResource("replicationcontrollers"); err != nil || v != "v1" || k != "ReplicationController" { t.Errorf("unexpected version mapping: %s %s %v", v, k, err) } if m, err := latest.GroupOrDie("").RESTMapper.RESTMapping("PodTemplate", ""); err != nil || m.APIVersion != "v1" || m.Resource != "podtemplates" { t.Errorf("unexpected version mapping: %#v %v", m, err) } for _, version := range latest.GroupOrDie("").Versions { mapping, err := latest.GroupOrDie("").RESTMapper.RESTMapping("ReplicationController", version) if err != nil { t.Errorf("unexpected error: %v", err) } if mapping.Resource != "replicationControllers" && mapping.Resource != "replicationcontrollers" { t.Errorf("incorrect resource name: %#v", mapping) } if mapping.APIVersion != version { t.Errorf("incorrect version: %v", mapping) } interfaces, _ := latest.GroupOrDie("").InterfacesFor(version) if mapping.Codec != interfaces.Codec { t.Errorf("unexpected codec: %#v, expected: %#v", mapping, interfaces) } rc := &internal.ReplicationController{ObjectMeta: internal.ObjectMeta{Name: "foo"}} name, err := mapping.MetadataAccessor.Name(rc) if err != nil { t.Errorf("unexpected error: %v", err) } if name != "foo" { t.Errorf("unable to retrieve object meta with: %v", mapping.MetadataAccessor) } } }
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 main() { flag.Parse() if *kubeconfig == "" { log.Fatalf("Need to specify --kubeconfig") } cfg := read(*kubeconfig) secret := &api.Secret{ ObjectMeta: api.ObjectMeta{ Name: *name, Namespace: *ns, }, Data: map[string][]byte{ "config": cfg, }, } fmt.Printf(runtime.EncodeOrDie(latest.GroupOrDie("").Codec, secret)) }
// Complete collects information required to run Convert command from command line. func (o *ConvertOptions) Complete(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) (err error) { o.outputVersion = cmdutil.OutputVersion(cmd, latest.GroupOrDie("").Version) if !registered.IsRegisteredAPIVersion(o.outputVersion) { cmdutil.UsageError(cmd, "'%s' is not a registered version.", o.outputVersion) } // build the builder mapper, typer := f.Object() if o.local { fmt.Fprintln(out, "running in local mode...") o.builder = resource.NewBuilder(mapper, typer, f.NilClientMapperForCommand()) } else { o.builder = resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()) schema, err := f.Validator(cmdutil.GetFlagBool(cmd, "validate"), cmdutil.GetFlagString(cmd, "schema-cache-dir")) if err != nil { return err } o.builder = o.builder.Schema(schema) } cmdNamespace, _, err := f.DefaultNamespace() if err != nil { return err } o.builder = o.builder.NamespaceParam(cmdNamespace). ContinueOnError(). FilenameParam(false, o.filenames...). Flatten() // build the printer o.out = out outputFormat := cmdutil.GetFlagString(cmd, "output") templateFile := cmdutil.GetFlagString(cmd, "template") if len(outputFormat) == 0 { if len(templateFile) == 0 { outputFormat = "yaml" } else { outputFormat = "template" } } o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile) if err != nil { return err } return nil }
func (t *thirdPartyResourceDataMapper) RESTMapping(kind string, groupVersions ...string) (*meta.RESTMapping, error) { if len(groupVersions) != 1 { return nil, fmt.Errorf("unexpected set of groupVersions: %v", groupVersions) } if groupVersions[0] != apiutil.GetGroupVersion(t.group, t.version) { return nil, fmt.Errorf("unknown version %s expected %s", groupVersions[0], apiutil.GetGroupVersion(t.group, t.version)) } if kind != "ThirdPartyResourceData" { return nil, fmt.Errorf("unknown kind %s expected %s", kind, t.kind) } mapping, err := t.mapper.RESTMapping("ThirdPartyResourceData", latest.GroupOrDie("extensions").GroupVersion) if err != nil { return nil, err } mapping.Codec = NewCodec(mapping.Codec, t.kind) return mapping, nil }
func main() { flag.Parse() if *crt == "" || *key == "" { log.Fatalf("Need to specify -crt -key and -template") } nginxCrt := read(*crt) nginxKey := read(*key) secret := &api.Secret{ ObjectMeta: api.ObjectMeta{ Name: "nginxsecret", }, Data: map[string][]byte{ "nginx.crt": nginxCrt, "nginx.key": nginxKey, }, } fmt.Printf(runtime.EncodeOrDie(latest.GroupOrDie("").Codec, secret)) }