// TestAdmissionNamespaceExistsUnknownToHandler func TestAdmissionNamespaceExistsUnknownToHandler(t *testing.T) { namespace := "test" mockClient := &fake.Clientset{} mockClient.AddReactor("create", "namespaces", func(action core.Action) (bool, runtime.Object, error) { return true, nil, errors.NewAlreadyExists(api.Resource("namespaces"), namespace) }) informerFactory := informers.NewSharedInformerFactory(mockClient, 5*time.Minute) informerFactory.Namespaces() informerFactory.Start(wait.NeverStop) handler := &provision{ client: mockClient, informerFactory: informerFactory, } pod := api.Pod{ ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace}, Spec: api.PodSpec{ Volumes: []api.Volume{{Name: "vol"}}, Containers: []api.Container{{Name: "ctr", Image: "image"}}, }, } err := handler.Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, nil)) if err != nil { t.Errorf("Unexpected error returned from admission handler") } }
func (m *VirtualStorage) createRole(ctx kapi.Context, obj runtime.Object, allowEscalation bool) (*authorizationapi.Role, error) { if err := rest.BeforeCreate(m.CreateStrategy, ctx, obj); err != nil { return nil, err } role := obj.(*authorizationapi.Role) if !allowEscalation { if err := rulevalidation.ConfirmNoEscalation(ctx, authorizationapi.Resource("role"), role.Name, m.RuleResolver, authorizationinterfaces.NewLocalRoleAdapter(role)); err != nil { return nil, err } } policy, err := m.EnsurePolicy(ctx) if err != nil { return nil, err } if _, exists := policy.Roles[role.Name]; exists { return nil, kapierrors.NewAlreadyExists(authorizationapi.Resource("role"), role.Name) } role.ResourceVersion = policy.ResourceVersion policy.Roles[role.Name] = role policy.LastModified = unversioned.Now() if err := m.PolicyStorage.UpdatePolicy(ctx, policy); err != nil { return nil, err } return role, nil }
func (m *VirtualStorage) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) { if err := rest.BeforeCreate(m.CreateStrategy, ctx, obj); err != nil { return nil, err } role := obj.(*authorizationapi.Role) policy, err := m.EnsurePolicy(ctx) if err != nil { return nil, err } if _, exists := policy.Roles[role.Name]; exists { return nil, kapierrors.NewAlreadyExists("Role", role.Name) } role.ResourceVersion = policy.ResourceVersion policy.Roles[role.Name] = role policy.LastModified = util.Now() if err := m.PolicyStorage.UpdatePolicy(ctx, policy); err != nil { return nil, err } return role, nil }
func TestInitCmd_exsits(t *testing.T) { home, err := ioutil.TempDir("", "helm_home") if err != nil { t.Fatal(err) } defer os.Remove(home) var buf bytes.Buffer fc := fake.NewSimpleClientset(&extensions.Deployment{ ObjectMeta: api.ObjectMeta{ Namespace: api.NamespaceDefault, Name: "tiller-deploy", }, }) fc.AddReactor("*", "*", func(action testcore.Action) (bool, runtime.Object, error) { return true, nil, errors.NewAlreadyExists(api.Resource("deployments"), "1") }) cmd := &initCmd{ out: &buf, home: helmpath.Home(home), kubeClient: fc.Extensions(), namespace: api.NamespaceDefault, } if err := cmd.run(); err != nil { t.Errorf("expected error: %v", err) } expected := "Warning: Tiller is already installed in the cluster. (Use --client-only to suppress this message.)" if !strings.Contains(buf.String(), expected) { t.Errorf("expected %q, got %q", expected, buf.String()) } }
func TestCheckGeneratedNameError(t *testing.T) { expect := errors.NewNotFound("foo", "bar") if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Pod{}); err != expect { t.Errorf("NotFoundError should be ignored: %v", err) } expect = errors.NewAlreadyExists("foo", "bar") if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Pod{}); err != expect { t.Errorf("AlreadyExists should be returned when no GenerateName field: %v", err) } expect = errors.NewAlreadyExists("foo", "bar") if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Pod{ObjectMeta: api.ObjectMeta{GenerateName: "foo"}}); err == nil || !errors.IsServerTimeout(err) { t.Errorf("expected try again later error: %v", err) } }
// TestHandle_deployerPodAlreadyExists ensures that attempts to create a // deployer pod which was already created don't result in an error // (effectively skipping the handling as redundant). func TestHandle_deployerPodAlreadyExists(t *testing.T) { var updatedDeployment *kapi.ReplicationController config := deploytest.OkDeploymentConfig(1) deployment, _ := deployutil.MakeDeployment(config, codec) deployment.Annotations[deployapi.DeploymentStatusAnnotation] = string(deployapi.DeploymentStatusNew) deployerPodName := deployutil.DeployerPodNameForDeployment(deployment.Name) fake := &ktestclient.Fake{} fake.AddReactor("create", "pods", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) { name := action.(ktestclient.CreateAction).GetObject().(*kapi.Pod).Name return true, nil, kerrors.NewAlreadyExists(kapi.Resource("Pod"), name) }) fake.AddReactor("update", "replicationcontrollers", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) { rc := action.(ktestclient.UpdateAction).GetObject().(*kapi.ReplicationController) updatedDeployment = rc return true, rc, nil }) controller := okDeploymentController(fake, deployment, nil, true) if err := controller.Handle(deployment); err != nil { t.Fatalf("unexpected error: %v", err) } if updatedDeployment.Annotations[deployapi.DeploymentPodAnnotation] != deployerPodName { t.Fatalf("deployment not updated with pod name annotation") } if updatedDeployment.Annotations[deployapi.DeploymentStatusAnnotation] != string(deployapi.DeploymentStatusPending) { t.Fatalf("deployment status not updated to pending") } }
// InterpretCreateError converts a generic etcd error on a create // operation into the appropriate API error. func InterpretCreateError(err error, kind, name string) error { switch { case etcdstorage.IsEtcdNodeExist(err): return errors.NewAlreadyExists(kind, name) default: return err } }
func (c *mockRecyclerClient) CreatePod(pod *api.Pod) (*api.Pod, error) { if c.pod == nil { c.pod = pod return c.pod, nil } // Simulate "already exists" error return nil, errors.NewAlreadyExists(api.Resource("pods"), pod.Name) }
// Create creates a new ConfigMap. func (mock *MockConfigMapsInterface) Create(cfgmap *api.ConfigMap) (*api.ConfigMap, error) { name := cfgmap.ObjectMeta.Name if object, ok := mock.objects[name]; ok { return object, kberrs.NewAlreadyExists(api.Resource("tests"), name) } mock.objects[name] = cfgmap return cfgmap, nil }
func (r *REST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) { istag, ok := obj.(*imageapi.ImageStreamTag) if !ok { return nil, kapierrors.NewBadRequest(fmt.Sprintf("obj is not an ImageStreamTag: %#v", obj)) } if err := rest.BeforeCreate(Strategy, ctx, obj); err != nil { return nil, err } namespace, ok := kapi.NamespaceFrom(ctx) if !ok { return nil, kapierrors.NewBadRequest("a namespace must be specified to import images") } imageStreamName, imageTag, ok := imageapi.SplitImageStreamTag(istag.Name) if !ok { return nil, fmt.Errorf("%q must be of the form <stream_name>:<tag>", istag.Name) } target, err := r.imageStreamRegistry.GetImageStream(ctx, imageStreamName) if err != nil { if !kapierrors.IsNotFound(err) { return nil, err } // try to create the target if it doesn't exist target = &imageapi.ImageStream{ ObjectMeta: kapi.ObjectMeta{ Name: imageStreamName, Namespace: namespace, }, } } if target.Spec.Tags == nil { target.Spec.Tags = make(map[string]imageapi.TagReference) } // The user wants to symlink a tag. _, exists := target.Spec.Tags[imageTag] if exists { return nil, kapierrors.NewAlreadyExists(imageapi.Resource("imagestreamtag"), istag.Name) } target.Spec.Tags[imageTag] = *istag.Tag // Check the stream creation timestamp and make sure we will not // create a new image stream while deleting. if target.CreationTimestamp.IsZero() { _, err = r.imageStreamRegistry.CreateImageStream(ctx, target) } else { _, err = r.imageStreamRegistry.UpdateImageStream(ctx, target) } if err != nil { return nil, err } return istag, nil }
// InterpretCreateError converts a generic error on a create // operation into the appropriate API error. func InterpretCreateError(err error, qualifiedResource unversioned.GroupResource, name string) error { switch { case storage.IsNodeExist(err): return errors.NewAlreadyExists(qualifiedResource, name) case storage.IsUnreachable(err): return errors.NewServerTimeout(qualifiedResource, "create", 2) // TODO: make configurable or handled at a higher level default: return err } }
// InterpretCreateError converts a generic etcd error on a create // operation into the appropriate API error. func InterpretCreateError(err error, kind, name string) error { switch { case etcdutil.IsEtcdNodeExist(err): return errors.NewAlreadyExists(kind, name) case etcdutil.IsEtcdUnreachable(err): return errors.NewServerTimeout(kind, "create", 2) // TODO: make configurable or handled at a higher level default: return err } }
func (t *Tester) testCreateGeneratesNameReturnsServerTimeout(valid runtime.Object) { objectMeta := t.getObjectMetaOrFail(valid) objectMeta.Name = "" objectMeta.GenerateName = "test-" t.withStorageError(errors.NewAlreadyExists("kind", "thing"), func() { _, err := t.storage.(rest.Creater).Create(t.TestContext(), valid) if err == nil || !errors.IsServerTimeout(err) { t.Fatalf("Unexpected error: %v", err) } }) }
func TestCreateAppEnvConfigSecretAlreadyExists(t *testing.T) { alreadyExistErr := apierrors.NewAlreadyExists(api.Resource("tests"), "1") secretsClient := &k8s.FakeSecret{ FnCreate: func(*api.Secret) (*api.Secret, error) { return &api.Secret{}, alreadyExistErr }, FnUpdate: func(*api.Secret) (*api.Secret, error) { return &api.Secret{}, nil }, } err := createAppEnvConfigSecret(secretsClient, "test", nil) assert.NoErr(t, err) }
// TestHandle_unrelatedPodAlreadyExists ensures that attempts to create a // deployer pod, when a pod with the same name but missing annotations results // a transition to failed. func TestHandle_unrelatedPodAlreadyExists(t *testing.T) { var updatedDeployment *kapi.ReplicationController config := deploytest.OkDeploymentConfig(1) deployment, _ := deployutil.MakeDeployment(config, kapi.Codec) deployment.Annotations[deployapi.DeploymentStatusAnnotation] = string(deployapi.DeploymentStatusNew) otherPod := unrelatedPod(deployment) controller := &DeploymentController{ decodeConfig: func(deployment *kapi.ReplicationController) (*deployapi.DeploymentConfig, error) { return deployutil.DecodeDeploymentConfig(deployment, api.Codec) }, deploymentClient: &deploymentClientImpl{ updateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) { updatedDeployment = deployment return updatedDeployment, nil }, }, podClient: &podClientImpl{ getPodFunc: func(namespace, name string) (*kapi.Pod, error) { return otherPod, nil }, createPodFunc: func(namespace string, pod *kapi.Pod) (*kapi.Pod, error) { return nil, kerrors.NewAlreadyExists("Pod", pod.Name) }, }, makeContainer: func(strategy *deployapi.DeploymentStrategy) (*kapi.Container, error) { return okContainer(), nil }, recorder: &record.FakeRecorder{}, } err := controller.Handle(deployment) if err != nil { t.Fatalf("unexpected error: %v", err) } if _, exists := updatedDeployment.Annotations[deployapi.DeploymentPodAnnotation]; exists { t.Fatalf("deployment updated with pod name annotation") } if e, a := deployapi.DeploymentFailedUnrelatedDeploymentExists, deployment.Annotations[deployapi.DeploymentStatusReasonAnnotation]; e != a { t.Errorf("expected reason annotation %s, got %s", e, a) } if e, a := deployapi.DeploymentStatusFailed, deployutil.DeploymentStatusFor(updatedDeployment); e != a { t.Errorf("expected deployment status %s, got %s", e, a) } }
func (t *Tester) TestCreateGeneratesNameReturnsServerTimeout(valid runtime.Object) { objectMeta, err := api.ObjectMetaFor(valid) if err != nil { t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid) } objectMeta.Name = "" objectMeta.GenerateName = "test-" t.withStorageError(errors.NewAlreadyExists("kind", "thing"), func() { _, err := t.storage.(rest.Creater).Create(t.TestContext(), valid) if err == nil || !errors.IsServerTimeout(err) { t.Fatalf("Unexpected error: %v", err) } }) }
// CreateClusterPolicy creates a new policy. func (r *ClusterPolicyRegistry) CreateClusterPolicy(ctx kapi.Context, policy *authorizationapi.ClusterPolicy) error { if r.Err != nil { return r.Err } namespace := kapi.NamespaceValue(ctx) if len(namespace) != 0 { return errors.New("invalid request. Namespace parameter disallowed.") } if existing, _ := r.GetClusterPolicy(ctx, policy.Name); existing != nil { return kapierrors.NewAlreadyExists("ClusterPolicy", policy.Name) } addClusterPolicy(r.ClusterPolicies, *policy) return nil }
// CreateClusterPolicyBinding creates a new policyBinding. func (r *ClusterPolicyBindingRegistry) CreateClusterPolicyBinding(ctx kapi.Context, policyBinding *authorizationapi.ClusterPolicyBinding) error { if r.Err != nil { return r.Err } namespace := kapi.NamespaceValue(ctx) if len(namespace) != 0 { return errors.New("invalid request. Namespace parameter disallowed.") } if existing, _ := r.GetClusterPolicyBinding(ctx, policyBinding.Name); existing != nil { return kapierrors.NewAlreadyExists(authorizationapi.Resource("clusterpolicybinding"), policyBinding.Name) } addClusterPolicyBinding(r.clusterPolicyBindings, *policyBinding) return nil }
// TestHandle_deployerPodAlreadyExists ensures that attempts to create a // deployer pod which was already created don't result in an error // (effectively skipping the handling as redundant). func TestHandle_deployerPodAlreadyExists(t *testing.T) { var updatedDeployment *kapi.ReplicationController config := deploytest.OkDeploymentConfig(1) deployment, _ := deployutil.MakeDeployment(config, kapi.Codec) deployment.Annotations[deployapi.DeploymentStatusAnnotation] = string(deployapi.DeploymentStatusNew) deployerPod := relatedPod(deployment) controller := &DeploymentController{ decodeConfig: func(deployment *kapi.ReplicationController) (*deployapi.DeploymentConfig, error) { return deployutil.DecodeDeploymentConfig(deployment, api.Codec) }, deploymentClient: &deploymentClientImpl{ updateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) { updatedDeployment = deployment return updatedDeployment, nil }, }, podClient: &podClientImpl{ getPodFunc: func(namespace, name string) (*kapi.Pod, error) { return deployerPod, nil }, createPodFunc: func(namespace string, pod *kapi.Pod) (*kapi.Pod, error) { return nil, kerrors.NewAlreadyExists("Pod", pod.Name) }, }, makeContainer: func(strategy *deployapi.DeploymentStrategy) (*kapi.Container, error) { return okContainer(), nil }, recorder: &record.FakeRecorder{}, } err := controller.Handle(deployment) if err != nil { t.Fatalf("unexpected error: %v", err) } if updatedDeployment.Annotations[deployapi.DeploymentPodAnnotation] != deployerPod.Name { t.Fatalf("deployment not updated with pod name annotation") } if updatedDeployment.Annotations[deployapi.DeploymentStatusAnnotation] != string(deployapi.DeploymentStatusPending) { t.Fatalf("deployment status not updated to pending") } }
func (m *FakeNodeHandler) Create(node *api.Node) (*api.Node, error) { m.createLock.Lock() defer func() { m.RequestCount++ m.createLock.Unlock() }() for _, n := range m.Existing { if n.Name == node.Name { return nil, apierrors.NewAlreadyExists(api.Resource("nodes"), node.Name) } } if m.CreateHook == nil || m.CreateHook(m, node) { nodeCopy := *node m.CreatedNodes = append(m.CreatedNodes, &nodeCopy) return node, nil } else { return nil, errors.New("Create error.") } }
func (m *VirtualStorage) createRoleBinding(ctx kapi.Context, obj runtime.Object, allowEscalation bool) (*authorizationapi.RoleBinding, error) { // Copy object before passing to BeforeCreate, since it mutates objCopy, err := kapi.Scheme.DeepCopy(obj) if err != nil { return nil, err } obj = objCopy.(runtime.Object) if err := rest.BeforeCreate(m.CreateStrategy, ctx, obj); err != nil { return nil, err } roleBinding := obj.(*authorizationapi.RoleBinding) if !allowEscalation { if err := m.confirmNoEscalation(ctx, roleBinding); err != nil { return nil, err } } // Retry if we hit a conflict on the underlying PolicyBinding object if err := kclient.RetryOnConflict(kclient.DefaultRetry, func() error { policyBinding, err := m.getPolicyBindingForPolicy(ctx, roleBinding.RoleRef.Namespace, allowEscalation) if err != nil { return err } _, exists := policyBinding.RoleBindings[roleBinding.Name] if exists { return kapierrors.NewAlreadyExists(authorizationapi.Resource("rolebinding"), roleBinding.Name) } roleBinding.ResourceVersion = policyBinding.ResourceVersion policyBinding.RoleBindings[roleBinding.Name] = roleBinding policyBinding.LastModified = unversioned.Now() return m.BindingRegistry.UpdatePolicyBinding(ctx, policyBinding) }); err != nil { return nil, err } return roleBinding, nil }
func TestErrorsToAPIStatus(t *testing.T) { cases := map[error]unversioned.Status{ errors.NewNotFound(unversioned.GroupResource{Group: "legacy.kubernetes.io", Resource: "foos"}, "bar"): { Status: unversioned.StatusFailure, Code: http.StatusNotFound, Reason: unversioned.StatusReasonNotFound, Message: "foos.legacy.kubernetes.io \"bar\" not found", Details: &unversioned.StatusDetails{ Group: "legacy.kubernetes.io", Kind: "foos", Name: "bar", }, }, errors.NewAlreadyExists(api.Resource("foos"), "bar"): { Status: unversioned.StatusFailure, Code: http.StatusConflict, Reason: "AlreadyExists", Message: "foos \"bar\" already exists", Details: &unversioned.StatusDetails{ Group: "", Kind: "foos", Name: "bar", }, }, errors.NewConflict(api.Resource("foos"), "bar", stderrs.New("failure")): { Status: unversioned.StatusFailure, Code: http.StatusConflict, Reason: "Conflict", Message: "Operation cannot be fulfilled on foos \"bar\": failure", Details: &unversioned.StatusDetails{ Group: "", Kind: "foos", Name: "bar", }, }, } for k, v := range cases { actual := errToAPIStatus(k) if !reflect.DeepEqual(actual, &v) { t.Errorf("%s: Expected %#v, Got %#v", k, v, actual) } } }
func TestRegister_withSemiKnownNode(t *testing.T) { // semi-known because the lookup func doesn't see the a very newly created node // but our apiserver "create" call returns an already-exists error. in this case // CreateOrUpdate should proceed to attempt an update. fc := &core.Fake{} nodes := &fakeNodes{&fake.FakeNodes{&fake.FakeCore{fc}}} createCalled, createOnce := calledOnce(true, nil, errors.NewAlreadyExists(unversioned.GroupResource{"", ""}, "nodes")) fc.AddReactor("create", "nodes", createOnce) updateCalled, updateOnce := calledOnce(true, nil, nil) fc.AddReactor("update", "nodes", updateOnce) lookup := func(hostName string) *api.Node { select { case <-updateCalled: return &api.Node{ObjectMeta: api.ObjectMeta{Name: "foo"}} default: // this makes the node semi-known: apiserver knows it but the store/cache doesn't return nil } } r := NewRegistrator(nodes, lookup) ch := make(chan struct{}) defer close(ch) r.Run(ch) t.Logf("registering node foo") ok, err := r.Register("foo", nil) if !ok { t.Fatalf("registration failed without error") } else if err != nil { t.Fatalf("registration failed with error %v", err) } // wait for node update t.Logf("awaiting node update") <-createCalled <-updateCalled }
func TestErrorsToAPIStatus(t *testing.T) { cases := map[error]unversioned.Status{ errors.NewNotFound("foo", "bar"): { Status: unversioned.StatusFailure, Code: http.StatusNotFound, Reason: unversioned.StatusReasonNotFound, Message: "foo \"bar\" not found", Details: &unversioned.StatusDetails{ Kind: "foo", Name: "bar", }, }, errors.NewAlreadyExists("foo", "bar"): { Status: unversioned.StatusFailure, Code: http.StatusConflict, Reason: "AlreadyExists", Message: "foo \"bar\" already exists", Details: &unversioned.StatusDetails{ Kind: "foo", Name: "bar", }, }, errors.NewConflict("foo", "bar", stderrs.New("failure")): { Status: unversioned.StatusFailure, Code: http.StatusConflict, Reason: "Conflict", Message: "foo \"bar\" cannot be updated: failure", Details: &unversioned.StatusDetails{ Kind: "foo", Name: "bar", }, }, } for k, v := range cases { actual := errToAPIStatus(k) if !reflect.DeepEqual(actual, &v) { t.Errorf("%s: Expected %#v, Got %#v", k, v, actual) } } }
// TestHandle_unrelatedPodAlreadyExistsTestScaled ensures that attempts to create a // deployer pod, when a pod with the same name but be scaled to zero results // a transition to failed. func TestHandle_unrelatedPodAlreadyExistsTestScaled(t *testing.T) { var updatedDeployment *kapi.ReplicationController config := deploytest.TestDeploymentConfig(deploytest.OkDeploymentConfig(1)) deployment, _ := deployutil.MakeDeployment(config, codec) deployment.Annotations[deployapi.DeploymentStatusAnnotation] = string(deployapi.DeploymentStatusNew) deployment.Spec.Replicas = 1 fake := &ktestclient.Fake{} fake.AddReactor("create", "pods", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) { name := action.(ktestclient.CreateAction).GetObject().(*kapi.Pod).Name return true, nil, kerrors.NewAlreadyExists(kapi.Resource("Pod"), name) }) fake.AddReactor("update", "replicationcontrollers", func(action ktestclient.Action) (handled bool, ret runtime.Object, err error) { rc := action.(ktestclient.UpdateAction).GetObject().(*kapi.ReplicationController) updatedDeployment = rc return true, rc, nil }) controller := okDeploymentController(fake, deployment, nil, false, kapi.PodRunning) if err := controller.Handle(deployment); err != nil { t.Fatalf("unexpected error: %v", err) } if _, exists := updatedDeployment.Annotations[deployapi.DeploymentPodAnnotation]; exists { t.Fatalf("deployment updated with pod name annotation") } if e, a := deployapi.DeploymentFailedUnrelatedDeploymentExists, updatedDeployment.Annotations[deployapi.DeploymentStatusReasonAnnotation]; e != a { t.Fatalf("expected reason annotation %s, got %s", e, a) } if e, a := deployapi.DeploymentStatusFailed, deployutil.DeploymentStatusFor(updatedDeployment); e != a { t.Fatalf("expected deployment status %s, got %s", e, a) } if e, a := int32(0), updatedDeployment.Spec.Replicas; e != a { t.Fatalf("expected failed deployment to be scaled to zero: %d", a) } }
func TestAdmissionWithLatentCache(t *testing.T) { namespace := "test" mockClient := newMockClientForTest([]string{}) mockClient.AddReactor("create", "namespaces", func(action core.Action) (bool, runtime.Object, error) { return true, nil, errors.NewAlreadyExists(api.Resource("namespaces"), namespace) }) handler, informerFactory, err := newHandlerForTest(mockClient) if err != nil { t.Errorf("unexpected error initializing handler: %v", err) } informerFactory.Start(wait.NeverStop) pod := newPod(namespace) err = handler.Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, nil)) if err != nil { t.Errorf("unexpected error returned from admission handler") } if !hasCreateNamespaceAction(mockClient) { t.Errorf("expected create namespace action") } }
// TestAdmissionNamespaceExistsUnknownToHandler func TestAdmissionNamespaceExistsUnknownToHandler(t *testing.T) { namespace := "test" mockClient := &testclient.Fake{} mockClient.SetErr(errors.NewAlreadyExists("namespaces", namespace)) store := cache.NewStore(cache.MetaNamespaceKeyFunc) handler := &provision{ client: mockClient, store: store, } pod := api.Pod{ ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace}, Spec: api.PodSpec{ Volumes: []api.Volume{{Name: "vol"}}, Containers: []api.Container{{Name: "ctr", Image: "image"}}, }, } err := handler.Admit(admission.NewAttributesRecord(&pod, "Pod", pod.Namespace, pod.Name, "pods", "", admission.Create, nil)) if err != nil { t.Errorf("Unexpected error returned from admission handler") } }
func (m *VirtualStorage) createRole(ctx kapi.Context, obj runtime.Object, allowEscalation bool) (*authorizationapi.Role, error) { // Copy object before passing to BeforeCreate, since it mutates objCopy, err := kapi.Scheme.DeepCopy(obj) if err != nil { return nil, err } obj = objCopy.(runtime.Object) if err := rest.BeforeCreate(m.CreateStrategy, ctx, obj); err != nil { return nil, err } role := obj.(*authorizationapi.Role) if !allowEscalation { if err := rulevalidation.ConfirmNoEscalation(ctx, m.Resource, role.Name, m.RuleResolver, m.CachedRuleResolver, authorizationinterfaces.NewLocalRoleAdapter(role)); err != nil { return nil, err } } if err := kclient.RetryOnConflict(kclient.DefaultRetry, func() error { policy, err := m.EnsurePolicy(ctx) if err != nil { return err } if _, exists := policy.Roles[role.Name]; exists { return kapierrors.NewAlreadyExists(m.Resource, role.Name) } role.ResourceVersion = policy.ResourceVersion policy.Roles[role.Name] = role policy.LastModified = unversioned.Now() return m.PolicyStorage.UpdatePolicy(ctx, policy) }); err != nil { return nil, err } return role, nil }
// TestAdmissionNamespaceExistsUnknownToHandler func TestAdmissionNamespaceExistsUnknownToHandler(t *testing.T) { namespace := "test" mockClient := &testclient.Fake{} mockClient.AddReactor("create", "namespaces", func(action testclient.Action) (bool, runtime.Object, error) { return true, nil, errors.NewAlreadyExists("namespaces", namespace) }) store := cache.NewStore(cache.MetaNamespaceKeyFunc) handler := &provision{ client: mockClient, store: store, } pod := api.Pod{ ObjectMeta: api.ObjectMeta{Name: "123", Namespace: namespace}, Spec: api.PodSpec{ Volumes: []api.Volume{{Name: "vol"}}, Containers: []api.Container{{Name: "ctr", Image: "image"}}, }, } err := handler.Admit(admission.NewAttributesRecord(&pod, api.Kind("Pod"), pod.Namespace, pod.Name, api.Resource("pods"), "", admission.Create, nil)) if err != nil { t.Errorf("Unexpected error returned from admission handler") } }
func (m *VirtualStorage) createRoleBinding(ctx kapi.Context, obj runtime.Object, allowEscalation bool) (*authorizationapi.RoleBinding, error) { if err := rest.BeforeCreate(m.CreateStrategy, ctx, obj); err != nil { return nil, err } roleBinding := obj.(*authorizationapi.RoleBinding) if err := m.validateReferentialIntegrity(ctx, roleBinding); err != nil { return nil, err } if !allowEscalation { if err := m.confirmNoEscalation(ctx, roleBinding); err != nil { return nil, err } } policyBinding, err := m.getPolicyBindingForPolicy(ctx, roleBinding.RoleRef.Namespace, allowEscalation) if err != nil { return nil, err } _, exists := policyBinding.RoleBindings[roleBinding.Name] if exists { return nil, kapierrors.NewAlreadyExists("RoleBinding", roleBinding.Name) } roleBinding.ResourceVersion = policyBinding.ResourceVersion policyBinding.RoleBindings[roleBinding.Name] = roleBinding policyBinding.LastModified = util.Now() if err := m.BindingRegistry.UpdatePolicyBinding(ctx, policyBinding); err != nil { return nil, err } return roleBinding, nil }