本文整理汇总了Golang中k8s/io/kubernetes/pkg/api.NamespaceFrom函数的典型用法代码示例。如果您正苦于以下问题:Golang NamespaceFrom函数的具体用法?Golang NamespaceFrom怎么用?Golang NamespaceFrom使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NamespaceFrom函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestValidNamespace
// TestValidNamespace validates that namespace rules are enforced on a resource prior to create or update
func TestValidNamespace(t *testing.T) {
ctx := api.NewDefaultContext()
namespace, _ := api.NamespaceFrom(ctx)
resource := api.ReplicationController{}
if !api.ValidNamespace(ctx, &resource.ObjectMeta) {
t.Errorf("expected success")
}
if namespace != resource.Namespace {
t.Errorf("expected resource to have the default namespace assigned during validation")
}
resource = api.ReplicationController{ObjectMeta: api.ObjectMeta{Namespace: "other"}}
if api.ValidNamespace(ctx, &resource.ObjectMeta) {
t.Errorf("Expected error that resource and context errors do not match because resource has different namespace")
}
ctx = api.NewContext()
if api.ValidNamespace(ctx, &resource.ObjectMeta) {
t.Errorf("Expected error that resource and context errors do not match since context has no namespace")
}
ctx = api.NewContext()
ns := api.NamespaceValue(ctx)
if ns != "" {
t.Errorf("Expected the empty string")
}
}
示例2: Get
// Get retrieves all pull type secrets in the current namespace. Name is currently ignored and
// reserved for future use.
func (r *REST) Get(ctx kapi.Context, _ string, options runtime.Object) (runtime.Object, error) {
listOptions, ok := options.(*kapi.ListOptions)
if !ok {
return nil, fmt.Errorf("unexpected options: %v", listOptions)
}
ns, ok := kapi.NamespaceFrom(ctx)
if !ok {
ns = kapi.NamespaceAll
}
secrets, err := r.secrets.Secrets(ns).List(*listOptions)
if err != nil {
return nil, err
}
filtered := make([]kapi.Secret, 0, len(secrets.Items))
for i := range secrets.Items {
if secrets.Items[i].Annotations[api.ExcludeImageSecretAnnotation] == "true" {
continue
}
switch secrets.Items[i].Type {
case kapi.SecretTypeDockercfg, kapi.SecretTypeDockerConfigJson:
filtered = append(filtered, secrets.Items[i])
}
}
secrets.Items = filtered
return secrets, nil
}
示例3: Get
func (g *podGetter) Get(ctx kapi.Context, name string) (runtime.Object, error) {
ns, ok := kapi.NamespaceFrom(ctx)
if !ok {
return nil, errors.NewBadRequest("namespace parameter required.")
}
return g.podsNamespacer.Pods(ns).Get(name)
}
示例4: TestNamespaceContext
// TestNamespaceContext validates that a namespace can be get/set on a context object
func TestNamespaceContext(t *testing.T) {
ctx := api.NewDefaultContext()
result, ok := api.NamespaceFrom(ctx)
if !ok {
t.Errorf("Error getting namespace")
}
if api.NamespaceDefault != result {
t.Errorf("Expected: %v, Actual: %v", api.NamespaceDefault, result)
}
ctx = api.NewContext()
result, ok = api.NamespaceFrom(ctx)
if ok {
t.Errorf("Should not be ok because there is no namespace on the context")
}
}
示例5: 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)
})
}
示例6: NewTestGenericEtcdRegistry
func NewTestGenericEtcdRegistry(t *testing.T) (*etcdtesting.EtcdTestServer, *Etcd) {
podPrefix := "/pods"
server := etcdtesting.NewEtcdTestClientServer(t)
s := etcdstorage.NewEtcdStorage(server.Client, testapi.Default.Codec(), etcdtest.PathPrefix())
strategy := &testRESTStrategy{api.Scheme, api.SimpleNameGenerator, true, false, true}
return server, &Etcd{
NewFunc: func() runtime.Object { return &api.Pod{} },
NewListFunc: func() runtime.Object { return &api.PodList{} },
EndpointName: "pods",
CreateStrategy: strategy,
UpdateStrategy: strategy,
KeyRootFunc: func(ctx api.Context) string {
return podPrefix
},
KeyFunc: func(ctx api.Context, id string) (string, error) {
if _, ok := api.NamespaceFrom(ctx); !ok {
return "", fmt.Errorf("namespace is required")
}
return path.Join(podPrefix, id), nil
},
ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Pod).Name, nil },
Storage: s,
}
}
示例7: cacheKey
func cacheKey(ctx kapi.Context, a authorizer.Action) (string, error) {
if a.GetRequestAttributes() != nil {
// TODO: see if we can serialize this?
return "", errors.New("cannot cache request attributes")
}
keyData := map[string]interface{}{
"verb": a.GetVerb(),
"apiVersion": a.GetAPIVersion(),
"apiGroup": a.GetAPIGroup(),
"resource": a.GetResource(),
"resourceName": a.GetResourceName(),
"nonResourceURL": a.IsNonResourceURL(),
"url": a.GetURL(),
}
if namespace, ok := kapi.NamespaceFrom(ctx); ok {
keyData["namespace"] = namespace
}
if user, ok := kapi.UserFrom(ctx); ok {
keyData["user"] = user.GetName()
keyData["groups"] = user.GetGroups()
keyData["scopes"] = user.GetExtra()[authorizationapi.ScopesKey]
}
key, err := json.Marshal(keyData)
return string(key), err
}
示例8: Update
// Update scales the DeploymentConfig for the given Scale subresource, returning the updated Scale.
func (r *ScaleREST) Update(ctx kapi.Context, obj runtime.Object) (runtime.Object, bool, error) {
if obj == nil {
return nil, false, errors.NewBadRequest(fmt.Sprintf("nil update passed to Scale"))
}
scale, ok := obj.(*extensions.Scale)
if !ok {
return nil, false, errors.NewBadRequest(fmt.Sprintf("wrong object passed to Scale update: %v", obj))
}
// fake an existing object to validate
existing := &extensions.Scale{
ObjectMeta: kapi.ObjectMeta{
Name: scale.Name,
CreationTimestamp: scale.CreationTimestamp,
},
}
if existing.Namespace, ok = kapi.NamespaceFrom(ctx); !ok {
existing.Namespace = scale.Namespace
}
if errs := extvalidation.ValidateScaleUpdate(scale, existing); len(errs) > 0 {
return nil, false, errors.NewInvalid("scale", scale.Name, errs)
}
deploymentConfig, err := r.registry.GetDeploymentConfig(ctx, scale.Name)
if err != nil {
return nil, false, errors.NewNotFound("scale", scale.Name)
}
scaleRet := &extensions.Scale{
ObjectMeta: kapi.ObjectMeta{
Name: deploymentConfig.Name,
Namespace: deploymentConfig.Namespace,
CreationTimestamp: deploymentConfig.CreationTimestamp,
},
Spec: extensions.ScaleSpec{
Replicas: scale.Spec.Replicas,
},
Status: extensions.ScaleStatus{
Selector: deploymentConfig.Spec.Selector,
},
}
// TODO(directxman12): this is going to be a bit out of sync, since we are calculating it
// here and not as part of the deploymentconfig loop -- is there a better way of doing it?
totalReplicas, err := r.replicasForDeploymentConfig(deploymentConfig.Namespace, deploymentConfig.Name)
if err != nil {
return nil, false, err
}
oldReplicas := deploymentConfig.Spec.Replicas
deploymentConfig.Spec.Replicas = scale.Spec.Replicas
if err := r.registry.UpdateDeploymentConfig(ctx, deploymentConfig); err != nil {
return nil, false, err
}
scaleRet.Status.Replicas = totalReplicas + (scale.Spec.Replicas - oldReplicas)
return scaleRet, false, nil
}
示例9: Create
// Create registers a given new PodSecurityPolicyReview instance to r.registry.
func (r *REST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {
pspr, ok := obj.(*securityapi.PodSecurityPolicyReview)
if !ok {
return nil, kapierrors.NewBadRequest(fmt.Sprintf("not a PodSecurityPolicyReview: %#v", obj))
}
if errs := securityvalidation.ValidatePodSecurityPolicyReview(pspr); len(errs) > 0 {
return nil, kapierrors.NewInvalid(kapi.Kind("PodSecurityPolicyReview"), "", errs)
}
ns, ok := kapi.NamespaceFrom(ctx)
if !ok {
return nil, kapierrors.NewBadRequest("namespace parameter required.")
}
serviceAccounts, err := getServiceAccounts(pspr.Spec, r.saCache, ns)
if err != nil {
return nil, kapierrors.NewBadRequest(err.Error())
}
if len(serviceAccounts) == 0 {
glog.Errorf("No service accounts for namespace %s", ns)
return nil, kapierrors.NewBadRequest(fmt.Sprintf("unable to find ServiceAccount for namespace: %s", ns))
}
errs := []error{}
newStatus := securityapi.PodSecurityPolicyReviewStatus{}
for _, sa := range serviceAccounts {
userInfo := serviceaccount.UserInfo(ns, sa.Name, "")
saConstraints, err := r.sccMatcher.FindApplicableSCCs(userInfo)
if err != nil {
errs = append(errs, fmt.Errorf("unable to find SecurityContextConstraints for ServiceAccount %s: %v", sa.Name, err))
continue
}
oscc.DeduplicateSecurityContextConstraints(saConstraints)
sort.Sort(oscc.ByPriority(saConstraints))
var namespace *kapi.Namespace
for _, constraint := range saConstraints {
var (
provider kscc.SecurityContextConstraintsProvider
err error
)
pspsrs := securityapi.PodSecurityPolicySubjectReviewStatus{}
if provider, namespace, err = oscc.CreateProviderFromConstraint(ns, namespace, constraint, r.client); err != nil {
errs = append(errs, fmt.Errorf("unable to create provider for service account %s: %v", sa.Name, err))
continue
}
_, err = podsecuritypolicysubjectreview.FillPodSecurityPolicySubjectReviewStatus(&pspsrs, provider, pspr.Spec.Template.Spec, constraint)
if err != nil {
glog.Errorf("unable to fill PodSecurityPolicyReviewStatus from constraint %v", err)
continue
}
sapsprs := securityapi.ServiceAccountPodSecurityPolicyReviewStatus{pspsrs, sa.Name}
newStatus.AllowedServiceAccounts = append(newStatus.AllowedServiceAccounts, sapsprs)
}
}
if len(errs) > 0 {
return nil, kapierrors.NewBadRequest(fmt.Sprintf("%s", kerrors.NewAggregate(errs)))
}
pspr.Status = newStatus
return pspr, nil
}
示例10: NamespaceKeyRootFunc
// NamespaceKeyRootFunc is the default function for constructing storage paths to resource directories enforcing namespace rules.
func NamespaceKeyRootFunc(ctx api.Context, prefix string) string {
key := prefix
ns, ok := api.NamespaceFrom(ctx)
if ok && len(ns) > 0 {
key = key + "/" + ns
}
return key
}
示例11: MakeEtcdListKey
// MakeEtcdListKey constructs etcd paths to resource directories enforcing namespace rules
func MakeEtcdListKey(ctx api.Context, prefix string) string {
key := prefix
ns, ok := api.NamespaceFrom(ctx)
if ok && len(ns) > 0 {
key = key + "/" + ns
}
return key
}
示例12: Create
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
}
示例13: newTestGenericStoreRegistry
func newTestGenericStoreRegistry(t *testing.T, hasCacheEnabled bool) (*etcdtesting.EtcdTestServer, *Store) {
podPrefix := "/pods"
server, sc := etcdtesting.NewUnsecuredEtcd3TestClientServer(t)
strategy := &testRESTStrategy{api.Scheme, api.SimpleNameGenerator, true, false, true}
sc.Codec = testapi.Default.StorageCodec()
s, err := factory.Create(*sc)
if err != nil {
t.Fatalf("Error creating storage: %v", err)
}
if hasCacheEnabled {
config := storage.CacherConfig{
CacheCapacity: 10,
Storage: s,
Versioner: etcdstorage.APIObjectVersioner{},
Type: &api.Pod{},
ResourcePrefix: podPrefix,
KeyFunc: func(obj runtime.Object) (string, error) { return storage.NoNamespaceKeyFunc(podPrefix, obj) },
NewListFunc: func() runtime.Object { return &api.PodList{} },
Codec: sc.Codec,
}
s = storage.NewCacherFromConfig(config)
}
return server, &Store{
NewFunc: func() runtime.Object { return &api.Pod{} },
NewListFunc: func() runtime.Object { return &api.PodList{} },
QualifiedResource: api.Resource("pods"),
CreateStrategy: strategy,
UpdateStrategy: strategy,
DeleteStrategy: strategy,
KeyRootFunc: func(ctx api.Context) string {
return podPrefix
},
KeyFunc: func(ctx api.Context, id string) (string, error) {
if _, ok := api.NamespaceFrom(ctx); !ok {
return "", fmt.Errorf("namespace is required")
}
return path.Join(podPrefix, id), nil
},
ObjectNameFunc: func(obj runtime.Object) (string, error) { return obj.(*api.Pod).Name, nil },
PredicateFunc: func(label labels.Selector, field fields.Selector) *generic.SelectionPredicate {
return &generic.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: func(obj runtime.Object) (labels.Set, fields.Set, error) {
pod, ok := obj.(*api.Pod)
if !ok {
return nil, nil, fmt.Errorf("not a pod")
}
return labels.Set(pod.ObjectMeta.Labels), generic.ObjectMetaFieldsSet(pod.ObjectMeta, true), nil
},
}
},
Storage: s,
}
}
示例14: NoNamespaceKeyFunc
// NoNamespaceKeyFunc is the default function for constructing etcd paths to a resource relative to prefix enforcing
// If a namespace is on context, it errors.
func NoNamespaceKeyFunc(ctx kapi.Context, prefix string, name string) (string, error) {
ns, ok := kapi.NamespaceFrom(ctx)
if ok && len(ns) > 0 {
return "", kerrors.NewBadRequest("Namespace parameter is not allowed.")
}
if len(name) == 0 {
return "", kerrors.NewBadRequest("Name parameter required.")
}
return path.Join(prefix, name), nil
}
示例15: ListClusterRoleBindings
func (r *staticRoles) ListClusterRoleBindings(ctx api.Context, options *api.ListOptions) (*rbac.ClusterRoleBindingList, error) {
namespace, ok := api.NamespaceFrom(ctx)
if ok && namespace != "" {
return nil, errors.New("cannot list cluster role bindings from within a namespace")
}
clusterRoleBindings := new(rbac.ClusterRoleBindingList)
clusterRoleBindings.Items = make([]rbac.ClusterRoleBinding, len(r.clusterRoleBindings))
copy(clusterRoleBindings.Items, r.clusterRoleBindings)
return clusterRoleBindings, nil
}