本文整理汇总了Golang中github.com/GoogleCloudPlatform/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: resolveImageStreamReference
// resolveImageStreamReference looks up the ImageStream[Tag/Image] and converts it to a
// docker pull spec that can be used in an Image field.
func (g *BuildGenerator) resolveImageStreamReference(ctx kapi.Context, from kapi.ObjectReference, defaultNamespace string) (string, error) {
var namespace string
if len(from.Namespace) != 0 {
namespace = from.Namespace
} else {
namespace = defaultNamespace
}
glog.V(4).Infof("Resolving ImageStreamReference %s of Kind %s in namespace %s", from.Name, from.Kind, namespace)
switch from.Kind {
case "ImageStream":
// NOTE: The 'ImageStream' reference should be used only for the 'output' image
is, err := g.Client.GetImageStream(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
glog.V(2).Infof("Error getting ImageStream %s/%s: %v", namespace, from.Name, err)
return "", err
}
image, err := imageapi.DockerImageReferenceForStream(is)
if err != nil {
glog.V(2).Infof("Error resolving Docker image reference for %s/%s: %v", namespace, from.Name, err)
return "", err
}
return image.String(), nil
case "ImageStreamImage":
imageStreamImage, err := g.Client.GetImageStreamImage(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
glog.V(2).Infof("Error ImageStreamReference %s in namespace %s: %v", from.Name, namespace, err)
if errors.IsNotFound(err) {
return "", err
}
return "", fatalError{err}
}
image := imageStreamImage.Image
glog.V(4).Infof("Resolved ImageStreamReference %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "ImageStreamTag":
imageStreamTag, err := g.Client.GetImageStreamTag(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
glog.V(2).Infof("Error resolving ImageStreamTag reference %s in namespace %s: %v", from.Name, namespace, err)
if errors.IsNotFound(err) {
return "", err
}
return "", fatalError{err}
}
image := imageStreamTag.Image
glog.V(4).Infof("Resolved ImageStreamTag %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "DockerImage":
return from.Name, nil
default:
return "", fatalError{fmt.Errorf("Unknown From Kind %s", from.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: ListResource
// ListResource returns a function that handles retrieving a list of resources from a RESTStorage object.
func ListResource(r RESTLister, ctxFn ContextFunc, namer ScopeNamer, codec runtime.Codec, version, apiResource string) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
w := res.ResponseWriter
namespace, err := namer.Namespace(req)
if err != nil {
errorJSON(err, codec, w)
return
}
ctx := ctxFn(req)
ctx = api.WithNamespace(ctx, namespace)
label, field, err := parseSelectorQueryParams(req.Request.URL.Query(), version, apiResource)
if err != nil {
errorJSON(err, codec, w)
return
}
result, err := r.List(ctx, label, field)
if err != nil {
errorJSON(err, codec, w)
return
}
if err := setListSelfLink(result, req, namer); err != nil {
errorJSON(err, codec, w)
return
}
writeJSON(http.StatusOK, codec, result, w)
}
}
示例6: 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)
}
示例7: getServiceEnvironmentVariables
// getServiceEnvironmentVariables populates a list of environment variables that are used
// in the container environment to get access to services.
func (b *BasicBoundPodFactory) getServiceEnvironmentVariables(ctx api.Context, registry service.Registry, machine string) ([]api.EnvVar, error) {
var result []api.EnvVar
servicesInNs, err := registry.ListServices(ctx)
if err != nil {
return result, err
}
masterServices, err := registry.ListServices(api.WithNamespace(api.NewContext(), b.MasterServiceNamespace))
if err != nil {
return result, err
}
projection := map[string]api.Service{}
services := []api.Service{}
for _, service := range masterServices.Items {
if masterServiceNames.Has(service.Name) {
projection[service.Name] = service
}
}
for _, service := range servicesInNs.Items {
projection[service.Name] = service
}
for _, service := range projection {
services = append(services, service)
}
return envvars.FromServices(&api.ServiceList{Items: services}), nil
}
示例8: confirmNoEscalation
func (m *VirtualStorage) confirmNoEscalation(ctx kapi.Context, roleBinding *authorizationapi.RoleBinding) error {
modifyingRole, err := m.getReferencedRole(roleBinding.RoleRef)
if err != nil {
return err
}
ruleResolver := rulevalidation.NewDefaultRuleResolver(
m.PolicyRegistry,
m.BindingRegistry,
m.ClusterPolicyRegistry,
m.ClusterPolicyBindingRegistry,
)
ownerLocalRules, err := ruleResolver.GetEffectivePolicyRules(ctx)
if err != nil {
return err
}
masterContext := kapi.WithNamespace(ctx, "")
ownerGlobalRules, err := ruleResolver.GetEffectivePolicyRules(masterContext)
if err != nil {
return err
}
ownerRules := make([]authorizationapi.PolicyRule, 0, len(ownerGlobalRules)+len(ownerLocalRules))
ownerRules = append(ownerRules, ownerLocalRules...)
ownerRules = append(ownerRules, ownerGlobalRules...)
ownerRightsCover, missingRights := rulevalidation.Covers(ownerRules, modifyingRole.Rules)
if !ownerRightsCover {
user, _ := kapi.UserFrom(ctx)
return fmt.Errorf("attempt to grant extra privileges: %v\nuser=%v\nownerrules%v\n", missingRights, user, ownerRules)
}
return nil
}
示例9: ConnectResource
// ConnectResource returns a function that handles a connect request on a rest.Storage object.
func ConnectResource(connecter rest.Connecter, scope RequestScope, connectOptionsKind string, subpath bool, subpathKey string) restful.RouteFunction {
return func(req *restful.Request, res *restful.Response) {
w := res.ResponseWriter
namespace, name, err := scope.Namer.Name(req)
if err != nil {
errorJSON(err, scope.Codec, w)
return
}
ctx := scope.ContextFunc(req)
ctx = api.WithNamespace(ctx, namespace)
opts, err := getRequestOptions(req, scope, connectOptionsKind, subpath, subpathKey)
if err != nil {
errorJSON(err, scope.Codec, w)
return
}
handler, err := connecter.Connect(ctx, name, opts)
if err != nil {
errorJSON(err, scope.Codec, w)
return
}
handler.ServeHTTP(w, req.Request)
err = handler.RequestError()
if err != nil {
errorJSON(err, scope.Codec, w)
return
}
}
}
示例10: TestGet
func TestGet(t *testing.T) {
expect := validNewPod()
expect.Status.Host = "machine"
fakeEtcdClient, helper := newHelper(t)
fakeEtcdClient.Data["/registry/pods/test/foo"] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Value: runtime.EncodeOrDie(latest.Codec, expect),
},
},
}
storage, _, _ := NewREST(helper)
cache := &fakeCache{statusToReturn: &api.PodStatus{Phase: api.PodRunning}}
storage = storage.WithPodStatus(cache)
obj, err := storage.Get(api.WithNamespace(api.NewContext(), "test"), "foo")
pod := obj.(*api.Pod)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expect.Status.Phase = api.PodRunning
if e, a := expect, pod; !api.Semantic.DeepEqual(e, a) {
t.Errorf("Unexpected pod: %s", util.ObjectDiff(e, a))
}
}
示例11: 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())
}
}
示例12: TestGetClusterPolicy
// TestGetClusterPolicy tests that a ReadOnlyPolicyClient GetPolicy() call correctly retrieves a cluster policy
// when the namespace given is equal to the empty string
func TestGetClusterPolicy(t *testing.T) {
testClient, policyStopChannel, bindingStopChannel, testChannel := beforeTestingSetup_readonlycache()
defer close(policyStopChannel)
defer close(bindingStopChannel)
var clusterPolicy *authorizationapi.Policy
var err error
namespace := ""
context := kapi.WithNamespace(kapi.NewContext(), namespace)
name := "uniqueClusterPolicyName"
util.Until(func() {
clusterPolicy, err = testClient.GetPolicy(context, name)
if (err == nil) &&
(clusterPolicy != nil) &&
(clusterPolicy.Name == name) &&
(clusterPolicy.Namespace == namespace) {
close(testChannel)
}
}, 1*time.Millisecond, testChannel)
switch {
case err != nil:
t.Errorf("Error getting cluster policy using GetPolicy(): %v", err)
case clusterPolicy == nil:
t.Error("Policy is nil")
case clusterPolicy.Name != name:
t.Errorf("Expected policy.Name to be '%s', but got '%s'", name, clusterPolicy.Name)
case clusterPolicy.Namespace != "":
t.Errorf("Expected policy.Namespace to be '%s', but got '%s'", namespace, clusterPolicy.Namespace)
}
}
示例13: TestUpdateError
func TestUpdateError(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-roleBinding", ResourceVersion: original.ResourceVersion},
RoleRef: kapi.ObjectReference{Name: "admin"},
}
_, _, err = storage.Update(ctx, roleBinding)
if err == nil {
t.Errorf("Missing expected error")
return
}
if !kapierrors.IsNotFound(err) {
t.Errorf("Unexpected error %v", err)
}
}
示例14: NewReadOnlyClusterPolicyCache
func NewReadOnlyClusterPolicyCache(registry clusterpolicyregistry.WatchingRegistry) readOnlyClusterPolicyCache {
ctx := kapi.WithNamespace(kapi.NewContext(), kapi.NamespaceAll)
indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc})
reflector := cache.NewReflector(
&cache.ListWatch{
ListFunc: func() (runtime.Object, error) {
return registry.ListClusterPolicies(ctx, labels.Everything(), fields.Everything())
},
WatchFunc: func(resourceVersion string) (watch.Interface, error) {
return registry.WatchClusterPolicies(ctx, labels.Everything(), fields.Everything(), resourceVersion)
},
},
&authorizationapi.ClusterPolicy{},
indexer,
2*time.Minute,
)
return readOnlyClusterPolicyCache{
registry: registry,
indexer: indexer,
reflector: *reflector,
keyFunc: cache.MetaNamespaceKeyFunc,
}
}
示例15: 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 *kapi.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)
}
}