本文整理汇总了Golang中k8s/io/kubernetes/pkg/api.WithNamespace函数的典型用法代码示例。如果您正苦于以下问题:Golang WithNamespace函数的具体用法?Golang WithNamespace怎么用?Golang WithNamespace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithNamespace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestResourceRestrictionsWithWeirdWork
func TestResourceRestrictionsWithWeirdWork(t *testing.T) {
test1 := &authorizeTest{
context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Rachel"}),
attributes: &DefaultAuthorizationAttributes{
Verb: "get",
Resource: "BUILDCONFIGS",
},
expectedAllowed: true,
expectedReason: "allowed by rule in adze",
}
test1.clusterPolicies = newDefaultClusterPolicies()
test1.policies = newAdzePolicies()
test1.clusterBindings = newDefaultClusterPolicyBindings()
test1.bindings = newAdzeBindings()
test1.test(t)
test2 := &authorizeTest{
context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Rachel"}),
attributes: &DefaultAuthorizationAttributes{
Verb: "get",
Resource: "buildconfigs",
},
expectedAllowed: true,
expectedReason: "allowed by rule in adze",
}
test2.clusterPolicies = newDefaultClusterPolicies()
test2.policies = newAdzePolicies()
test2.clusterBindings = newDefaultClusterPolicyBindings()
test2.bindings = newAdzeBindings()
test2.test(t)
}
示例2: TestVerbRestrictionsWork
func TestVerbRestrictionsWork(t *testing.T) {
test1 := &authorizeTest{
context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Valerie"}),
attributes: &DefaultAuthorizationAttributes{
Verb: "get",
Resource: "buildConfigs",
},
expectedAllowed: true,
expectedReason: "allowed by rule in adze",
}
test1.clusterPolicies = newDefaultClusterPolicies()
test1.policies = newAdzePolicies()
test1.clusterBindings = newDefaultClusterPolicyBindings()
test1.bindings = newAdzeBindings()
test1.test(t)
test2 := &authorizeTest{
context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Valerie"}),
attributes: &DefaultAuthorizationAttributes{
Verb: "create",
Resource: "buildConfigs",
},
expectedAllowed: false,
expectedReason: `User "Valerie" cannot create buildConfigs in project "adze"`,
}
test2.clusterPolicies = newDefaultClusterPolicies()
test2.policies = newAdzePolicies()
test2.clusterBindings = newDefaultClusterPolicyBindings()
test2.bindings = newAdzeBindings()
test2.test(t)
}
示例3: GetRoleReferenceRules
// GetRoleReferenceRules attempts resolve the RoleBinding or ClusterRoleBinding.
func (r *DefaultRuleResolver) GetRoleReferenceRules(ctx api.Context, roleRef api.ObjectReference, bindingNamespace string) ([]rbac.PolicyRule, error) {
switch roleRef.Kind {
case "Role":
// Roles can only be referenced by RoleBindings within the same namespace.
if len(bindingNamespace) == 0 {
return nil, fmt.Errorf("cluster role binding references role %q in namespace %q", roleRef.Name, roleRef.Namespace)
} else {
if bindingNamespace != roleRef.Namespace {
return nil, fmt.Errorf("role binding in namespace %q references role %q in namespace %q", bindingNamespace, roleRef.Name, roleRef.Namespace)
}
}
role, err := r.roleGetter.GetRole(api.WithNamespace(ctx, roleRef.Namespace), roleRef.Name)
if err != nil {
return nil, err
}
return role.Rules, nil
case "ClusterRole":
clusterRole, err := r.clusterRoleGetter.GetClusterRole(api.WithNamespace(ctx, ""), roleRef.Name)
if err != nil {
return nil, err
}
return clusterRole.Rules, nil
default:
return nil, fmt.Errorf("unsupported role reference kind: %q", roleRef.Kind)
}
}
示例4: TestEtcdListRoutesInDifferentNamespaces
func TestEtcdListRoutesInDifferentNamespaces(t *testing.T) {
fakeClient := tools.NewFakeEtcdClient(t)
namespaceAlfa := kapi.WithNamespace(kapi.NewContext(), "alfa")
namespaceBravo := kapi.WithNamespace(kapi.NewContext(), "bravo")
fakeClient.Data["/routes/alfa"] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Nodes: []*etcd.Node{
{
Value: runtime.EncodeOrDie(latest.Codec, &api.Route{ObjectMeta: kapi.ObjectMeta{Name: "foo1"}}),
},
},
},
},
E: nil,
}
fakeClient.Data["/routes/bravo"] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Nodes: []*etcd.Node{
{
Value: runtime.EncodeOrDie(latest.Codec, &api.Route{ObjectMeta: kapi.ObjectMeta{Name: "foo2"}}),
},
{
Value: runtime.EncodeOrDie(latest.Codec, &api.Route{ObjectMeta: kapi.ObjectMeta{Name: "bar2"}}),
},
},
},
},
E: nil,
}
registry := NewTestEtcd(fakeClient)
routesAlfa, err := registry.ListRoutes(namespaceAlfa, labels.Everything())
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(routesAlfa.Items) != 1 || routesAlfa.Items[0].Name != "foo1" {
t.Errorf("Unexpected builds list: %#v", routesAlfa)
}
routesBravo, err := registry.ListRoutes(namespaceBravo, labels.Everything())
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(routesBravo.Items) != 2 || routesBravo.Items[0].Name != "foo2" || routesBravo.Items[1].Name != "bar2" {
t.Errorf("Unexpected builds list: %#v", routesBravo)
}
}
示例5: TestDeleteGracefulImmediate
func (t *Tester) TestDeleteGracefulImmediate(existing runtime.Object, expectedGrace int64, wasGracefulFn func() bool) {
objectMeta, err := api.ObjectMetaFor(existing)
if err != nil {
t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, existing)
}
ctx := api.WithNamespace(t.TestContext(), objectMeta.Namespace)
_, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(expectedGrace))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !wasGracefulFn() {
t.Errorf("did not gracefully delete resource")
}
// second delete is immediate, resource is deleted
out, err := t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(0))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
_, err = t.storage.(rest.Getter).Get(ctx, objectMeta.Name)
if !errors.IsNotFound(err) {
t.Errorf("unexpected error, object should be deleted immediately: %v", err)
}
objectMeta, err = api.ObjectMetaFor(out)
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
if objectMeta.DeletionTimestamp == nil || objectMeta.DeletionGracePeriodSeconds == nil || *objectMeta.DeletionGracePeriodSeconds != 0 {
t.Errorf("unexpected deleted meta: %#v", objectMeta)
}
}
示例6: TestUpdate
func TestUpdate(t *testing.T) {
storage := makeLocalTestStorage()
ctx := kapi.WithNamespace(kapi.NewContext(), "unittest")
realizedRoleObj, _ := storage.Create(ctx, &authorizationapi.Role{
ObjectMeta: kapi.ObjectMeta{Name: "my-role"},
})
realizedRole := realizedRoleObj.(*authorizationapi.Role)
role := &authorizationapi.Role{
ObjectMeta: kapi.ObjectMeta{Name: "my-role", ResourceVersion: realizedRole.ResourceVersion},
}
obj, created, err := storage.Update(ctx, role)
if err != nil || created {
t.Errorf("Unexpected error %v", err)
}
switch obj.(type) {
case *unversioned.Status:
t.Errorf("Unexpected operation error: %v", obj)
case *authorizationapi.Role:
if !reflect.DeepEqual(role, obj) {
t.Errorf("Updated role does not match input role."+
" Expected: %v, Got: %v", role, obj)
}
default:
t.Errorf("Unexpected result type: %v", obj)
}
}
示例7: namespacingFilter
// namespacingFilter adds a filter that adds the namespace of the request to the context. Not all requests will have namespaces,
// but any that do will have the appropriate value added.
func namespacingFilter(handler http.Handler, contextMapper kapi.RequestContextMapper) http.Handler {
infoResolver := &apiserver.RequestInfoResolver{APIPrefixes: sets.NewString("api", "osapi", "oapi", "apis"), GrouplessAPIPrefixes: sets.NewString("api", "osapi", "oapi")}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx, ok := contextMapper.Get(req)
if !ok {
http.Error(w, "Unable to find request context", http.StatusInternalServerError)
return
}
if _, exists := kapi.NamespaceFrom(ctx); !exists {
if requestInfo, err := infoResolver.GetRequestInfo(req); err == nil {
// only set the namespace if the apiRequestInfo was resolved
// keep in mind that GetAPIRequestInfo will fail on non-api requests, so don't fail the entire http request on that
// kind of failure.
// TODO reconsider special casing this. Having the special case hereallow us to fully share the kube
// APIRequestInfoResolver without any modification or customization.
namespace := requestInfo.Namespace
if (requestInfo.Resource == "projects") && (len(requestInfo.Name) > 0) {
namespace = requestInfo.Name
}
ctx = kapi.WithNamespace(ctx, namespace)
contextMapper.Update(req, ctx)
}
}
handler.ServeHTTP(w, req)
})
}
示例8: TestUpdateCannotChangeRoleRefError
func TestUpdateCannotChangeRoleRefError(t *testing.T) {
ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"})
storage := makeTestStorage()
obj, err := storage.Create(ctx, &authorizationapi.RoleBinding{
ObjectMeta: kapi.ObjectMeta{Name: "my-different"},
RoleRef: kapi.ObjectReference{Name: "admin"},
})
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
original := obj.(*authorizationapi.RoleBinding)
roleBinding := &authorizationapi.RoleBinding{
ObjectMeta: kapi.ObjectMeta{Name: "my-different", ResourceVersion: original.ResourceVersion},
RoleRef: kapi.ObjectReference{Name: "cluster-admin"},
}
_, _, err = storage.Update(ctx, roleBinding)
if err == nil {
t.Errorf("Missing expected error")
return
}
expectedErr := "cannot change roleRef"
if !strings.Contains(err.Error(), expectedErr) {
t.Errorf("Expected %v, got %v", expectedErr, err.Error())
}
}
示例9: TestStatusUpdate
func TestStatusUpdate(t *testing.T) {
storage, server := newStorage(t)
defer server.Terminate(t)
ctx := api.WithNamespace(api.NewContext(), namespace)
key := etcdtest.AddPrefix("/deployments/" + namespace + "/" + name)
if err := storage.Deployment.Storage.Set(ctx, key, &validDeployment, nil, 0); err != nil {
t.Fatalf("unexpected error: %v", err)
}
update := extensions.Deployment{
ObjectMeta: validDeployment.ObjectMeta,
Spec: extensions.DeploymentSpec{
Replicas: 100,
},
Status: extensions.DeploymentStatus{
Replicas: 100,
},
}
if _, _, err := storage.Status.Update(ctx, &update); err != nil {
t.Fatalf("unexpected error: %v", err)
}
obj, err := storage.Deployment.Get(ctx, name)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
deployment := obj.(*extensions.Deployment)
if deployment.Spec.Replicas != 7 {
t.Errorf("we expected .spec.replicas to not be updated but it was updated to %v", deployment.Spec.Replicas)
}
if deployment.Status.Replicas != 100 {
t.Errorf("we expected .status.replicas to be updated to 100 but it was %v", deployment.Status.Replicas)
}
}
示例10: TestConflictingUpdate
func TestConflictingUpdate(t *testing.T) {
storage := makeLocalTestStorage()
ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"})
realizedRoleObj, err := storage.Create(ctx, &authorizationapi.Role{
ObjectMeta: kapi.ObjectMeta{Name: "my-role"},
Rules: []authorizationapi.PolicyRule{
{Verbs: sets.NewString(authorizationapi.VerbAll)},
},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
realizedRole := realizedRoleObj.(*authorizationapi.Role)
role := &authorizationapi.Role{
ObjectMeta: realizedRole.ObjectMeta,
Rules: []authorizationapi.PolicyRule{
{Verbs: sets.NewString("list", "update")},
},
}
role.ResourceVersion += "1"
_, _, err = storage.Update(ctx, role.Name, rest.DefaultUpdatedObjectInfo(role, kapi.Scheme))
if err == nil || !kapierrors.IsConflict(err) {
t.Errorf("Expected conflict error, got: %#v", err)
}
}
示例11: TestStoreDeleteCollection
func TestStoreDeleteCollection(t *testing.T) {
podA := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
podB := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}
testContext := api.WithNamespace(api.NewContext(), "test")
server, registry := NewTestGenericStoreRegistry(t)
defer server.Terminate(t)
if _, err := registry.Create(testContext, podA); err != nil {
t.Errorf("Unexpected error: %v", err)
}
if _, err := registry.Create(testContext, podB); err != nil {
t.Errorf("Unexpected error: %v", err)
}
// Delete all pods.
deleted, err := registry.DeleteCollection(testContext, nil, &api.ListOptions{})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
deletedPods := deleted.(*api.PodList)
if len(deletedPods.Items) != 2 {
t.Errorf("Unexpected number of pods deleted: %d, expected: 2", len(deletedPods.Items))
}
if _, err := registry.Get(testContext, podA.Name); !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
if _, err := registry.Get(testContext, podB.Name); !errors.IsNotFound(err) {
t.Errorf("Unexpected error: %v", err)
}
}
示例12: ConfirmNoEscalation
// ConfirmNoEscalation determines if the roles for a given user in a given namespace encompass the provided role.
func ConfirmNoEscalation(ctx api.Context, ruleResolver AuthorizationRuleResolver, rules []rbac.PolicyRule) error {
ruleResolutionErrors := []error{}
ownerLocalRules, err := ruleResolver.GetEffectivePolicyRules(ctx)
if err != nil {
// As per AuthorizationRuleResolver contract, this may return a non fatal error with an incomplete list of policies. Log the error and continue.
user, _ := api.UserFrom(ctx)
glog.V(1).Infof("non-fatal error getting local rules for %v: %v", user, err)
ruleResolutionErrors = append(ruleResolutionErrors, err)
}
masterContext := api.WithNamespace(ctx, "")
ownerGlobalRules, err := ruleResolver.GetEffectivePolicyRules(masterContext)
if err != nil {
// Same case as above. Log error, don't fail.
user, _ := api.UserFrom(ctx)
glog.V(1).Infof("non-fatal error getting global rules for %v: %v", user, err)
ruleResolutionErrors = append(ruleResolutionErrors, err)
}
ownerRules := make([]rbac.PolicyRule, 0, len(ownerGlobalRules)+len(ownerLocalRules))
ownerRules = append(ownerRules, ownerLocalRules...)
ownerRules = append(ownerRules, ownerGlobalRules...)
ownerRightsCover, missingRights := Covers(ownerRules, rules)
if !ownerRightsCover {
user, _ := api.UserFrom(ctx)
return errors.NewUnauthorized(fmt.Sprintf("attempt to grant extra privileges: %v user=%v ownerrules=%v ruleResolutionErrors=%v", missingRights, user, ownerRules, ruleResolutionErrors))
}
return nil
}
示例13: Bind
// Bind just does a POST binding RPC.
func (b *binder) Bind(binding *api.Binding) error {
glog.V(2).Infof("Attempting to bind %v to %v", binding.Name, binding.Target.Name)
ctx := api.WithNamespace(api.NewContext(), binding.Namespace)
return b.Post().Namespace(api.NamespaceValue(ctx)).Resource("bindings").Body(binding).Do().Error()
// TODO: use Pods interface for binding once clusters are upgraded
// return b.Pods(binding.Namespace).Bind(binding)
}
示例14: TestDeleteGracefulWithValue
func (t *Tester) TestDeleteGracefulWithValue(existing runtime.Object, expectedGrace int64, wasGracefulFn func() bool) {
objectMeta, err := api.ObjectMetaFor(existing)
if err != nil {
t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, existing)
}
ctx := api.WithNamespace(t.TestContext(), objectMeta.Namespace)
_, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(expectedGrace+2))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !wasGracefulFn() {
t.Errorf("did not gracefully delete resource")
}
object, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name)
if err != nil {
t.Errorf("unexpected error, object should exist: %v", err)
}
objectMeta, err = api.ObjectMetaFor(object)
if err != nil {
t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, object)
}
if objectMeta.DeletionTimestamp == nil {
t.Errorf("did not set deletion timestamp")
}
if objectMeta.DeletionGracePeriodSeconds == nil {
t.Fatalf("did not set deletion grace period seconds")
}
if *objectMeta.DeletionGracePeriodSeconds != expectedGrace+2 {
t.Errorf("actual grace period does not match expected: %d", *objectMeta.DeletionGracePeriodSeconds)
}
}
示例15: TestUpdateImageStreamConflictingNamespace
func TestUpdateImageStreamConflictingNamespace(t *testing.T) {
fakeEtcdClient, helper := newHelper(t)
fakeEtcdClient.Data["/imagestreams/legal-name/bar"] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Value: runtime.EncodeOrDie(latest.Codec, &api.ImageStream{
ObjectMeta: kapi.ObjectMeta{Name: "bar", Namespace: "default"},
}),
ModifiedIndex: 2,
},
},
}
storage, _ := NewREST(helper, noDefaultRegistry, &fakeSubjectAccessReviewRegistry{})
ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "legal-name"), &fakeUser{})
obj, created, err := storage.Update(ctx, &api.ImageStream{
ObjectMeta: kapi.ObjectMeta{Name: "bar", Namespace: "some-value", ResourceVersion: "2"},
})
if obj != nil || created {
t.Error("Expected a nil obj, but we got a value")
}
checkExpectedNamespaceError(t, err)
}