本文整理匯總了Golang中k8s/io/kubernetes/pkg/admission.Attributes.GetResource方法的典型用法代碼示例。如果您正苦於以下問題:Golang Attributes.GetResource方法的具體用法?Golang Attributes.GetResource怎麽用?Golang Attributes.GetResource使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類k8s/io/kubernetes/pkg/admission.Attributes
的用法示例。
在下文中一共展示了Attributes.GetResource方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Admit
func (p *provision) Admit(a admission.Attributes) (err error) {
gvk, err := api.RESTMapper.KindFor(a.GetResource())
if err != nil {
return admission.NewForbidden(a, err)
}
mapping, err := api.RESTMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return admission.NewForbidden(a, err)
}
if mapping.Scope.Name() != meta.RESTScopeNameNamespace {
return nil
}
namespace := &api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: a.GetNamespace(),
Namespace: "",
},
Status: api.NamespaceStatus{},
}
_, exists, err := p.store.Get(namespace)
if err != nil {
return admission.NewForbidden(a, err)
}
if exists {
return nil
}
_, err = p.client.Namespaces().Create(namespace)
if err != nil && !errors.IsAlreadyExists(err) {
return admission.NewForbidden(a, err)
}
return nil
}
示例2: Admit
// Admit will deny any pod that defines AntiAffinity topology key other than metav1.LabelHostname i.e. "kubernetes.io/hostname"
// in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution.
func (p *plugin) Admit(attributes admission.Attributes) (err error) {
// Ignore all calls to subresources or resources other than pods.
if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil
}
pod, ok := attributes.GetObject().(*api.Pod)
if !ok {
return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted")
}
affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations)
if err != nil {
glog.V(5).Infof("Invalid Affinity detected, but we will leave handling of this to validation phase")
return nil
}
if affinity != nil && affinity.PodAntiAffinity != nil {
var podAntiAffinityTerms []api.PodAffinityTerm
if len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {
podAntiAffinityTerms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution
}
// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.
//if len(affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {
// podAntiAffinityTerms = append(podAntiAffinityTerms, affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...)
//}
for _, v := range podAntiAffinityTerms {
if v.TopologyKey != metav1.LabelHostname {
return apierrors.NewForbidden(attributes.GetResource().GroupResource(), pod.Name, fmt.Errorf("affinity.PodAntiAffinity.RequiredDuringScheduling has TopologyKey %v but only key %v is allowed", v.TopologyKey, metav1.LabelHostname))
}
}
}
return nil
}
示例3: Admit
// Admit determines if the service should be admitted based on the configured network CIDR.
func (r *externalIPRanger) Admit(a kadmission.Attributes) error {
if a.GetResource() != kapi.Resource("services") {
return nil
}
svc, ok := a.GetObject().(*kapi.Service)
// if we can't convert then we don't handle this object so just return
if !ok {
return nil
}
var errs field.ErrorList
switch {
// administrator disabled externalIPs
case len(svc.Spec.ExternalIPs) > 0 && len(r.admit) == 0:
errs = append(errs, field.Forbidden(field.NewPath("spec", "externalIPs"), "externalIPs have been disabled"))
// administrator has limited the range
case len(svc.Spec.ExternalIPs) > 0 && len(r.admit) > 0:
for i, s := range svc.Spec.ExternalIPs {
ip := net.ParseIP(s)
if ip == nil {
errs = append(errs, field.Forbidden(field.NewPath("spec", "externalIPs").Index(i), "externalIPs must be a valid address"))
continue
}
if networkSlice(r.reject).Contains(ip) || !networkSlice(r.admit).Contains(ip) {
errs = append(errs, field.Forbidden(field.NewPath("spec", "externalIPs").Index(i), "externalIP is not allowed"))
continue
}
}
}
if len(errs) > 0 {
return apierrs.NewInvalid(a.GetKind(), a.GetName(), errs)
}
return nil
}
示例4: Admit
func (l *lifecycle) Admit(a admission.Attributes) (err error) {
// prevent deletion of immortal namespaces
if a.GetOperation() == admission.Delete && a.GetKind().GroupKind() == api.Kind("Namespace") && l.immortalNamespaces.Has(a.GetName()) {
return errors.NewForbidden(a.GetResource().GroupResource(), a.GetName(), fmt.Errorf("this namespace may not be deleted"))
}
// if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do
// if we're here, then the API server has found a route, which means that if we have a non-empty namespace
// its a namespaced resource.
if len(a.GetNamespace()) == 0 || a.GetKind().GroupKind() == api.Kind("Namespace") {
// if a namespace is deleted, we want to prevent all further creates into it
// while it is undergoing termination. to reduce incidences where the cache
// is slow to update, we forcefully remove the namespace from our local cache.
// this will cause a live lookup of the namespace to get its latest state even
// before the watch notification is received.
if a.GetOperation() == admission.Delete {
l.store.Delete(&api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: a.GetName(),
},
})
}
return nil
}
namespaceObj, exists, err := l.store.Get(&api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: a.GetNamespace(),
Namespace: "",
},
})
if err != nil {
return errors.NewInternalError(err)
}
// refuse to operate on non-existent namespaces
if !exists {
// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not
namespaceObj, err = l.client.Core().Namespaces().Get(a.GetNamespace())
if err != nil {
if errors.IsNotFound(err) {
return err
}
return errors.NewInternalError(err)
}
}
// ensure that we're not trying to create objects in terminating namespaces
if a.GetOperation() == admission.Create {
namespace := namespaceObj.(*api.Namespace)
if namespace.Status.Phase != api.NamespaceTerminating {
return nil
}
// TODO: This should probably not be a 403
return admission.NewForbidden(a, fmt.Errorf("Unable to create new content in namespace %s because it is being terminated.", a.GetNamespace()))
}
return nil
}
示例5: Admit
// Admit admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *limitRanger) Admit(a admission.Attributes) (err error) {
// Ignore all calls to subresources
if a.GetSubresource() != "" {
return nil
}
obj := a.GetObject()
name := "Unknown"
if obj != nil {
name, _ = meta.NewAccessor().Name(obj)
if len(name) == 0 {
name, _ = meta.NewAccessor().GenerateName(obj)
}
}
key := &api.LimitRange{
ObjectMeta: api.ObjectMeta{
Namespace: a.GetNamespace(),
Name: "",
},
}
items, err := l.indexer.Index("namespace", key)
if err != nil {
return admission.NewForbidden(a, fmt.Errorf("Unable to %s %v at this time because there was an error enforcing limit ranges", a.GetOperation(), a.GetResource()))
}
// if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it.
if len(items) == 0 {
lruItemObj, ok := l.liveLookupCache.Get(a.GetNamespace())
if !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) {
liveList, err := l.client.Core().LimitRanges(a.GetNamespace()).List(api.ListOptions{})
if err != nil {
return admission.NewForbidden(a, err)
}
newEntry := liveLookupEntry{expiry: time.Now().Add(l.liveTTL)}
for i := range liveList.Items {
newEntry.items = append(newEntry.items, &liveList.Items[i])
}
l.liveLookupCache.Add(a.GetNamespace(), newEntry)
lruItemObj = newEntry
}
lruEntry := lruItemObj.(liveLookupEntry)
for i := range lruEntry.items {
items = append(items, lruEntry.items[i])
}
}
// ensure it meets each prescribed min/max
for i := range items {
limitRange := items[i].(*api.LimitRange)
err = l.limitFunc(limitRange, a.GetResource().Resource, a.GetObject())
if err != nil {
return admission.NewForbidden(a, err)
}
}
return nil
}
示例6: Admit
func (d *sccExecRestrictions) Admit(a admission.Attributes) (err error) {
if a.GetOperation() != admission.Connect {
return nil
}
if a.GetResource().GroupResource() != kapi.Resource("pods") {
return nil
}
if a.GetSubresource() != "attach" && a.GetSubresource() != "exec" {
return nil
}
pod, err := d.client.Core().Pods(a.GetNamespace()).Get(a.GetName())
if err != nil {
return admission.NewForbidden(a, err)
}
// TODO, if we want to actually limit who can use which service account, then we'll need to add logic here to make sure that
// we're allowed to use the SA the pod is using. Otherwise, user-A creates pod and user-B (who can't use the SA) can exec into it.
createAttributes := admission.NewAttributesRecord(pod, pod, kapi.Kind("Pod").WithVersion(""), a.GetNamespace(), a.GetName(), a.GetResource(), "", admission.Create, a.GetUserInfo())
if err := d.constraintAdmission.Admit(createAttributes); err != nil {
return admission.NewForbidden(a, err)
}
return nil
}
示例7: Admit
// Admit determines if the pod should be admitted based on the requested security context
// and the available SCCs.
//
// 1. Find SCCs for the user.
// 2. Find SCCs for the SA. If there is an error retrieving SA SCCs it is not fatal.
// 3. Remove duplicates between the user/SA SCCs.
// 4. Create the providers, includes setting pre-allocated values if necessary.
// 5. Try to generate and validate an SCC with providers. If we find one then admit the pod
// with the validated SCC. If we don't find any reject the pod and give all errors from the
// failed attempts.
func (c *constraint) Admit(a kadmission.Attributes) error {
if a.GetResource().Resource != string(kapi.ResourcePods) {
return nil
}
pod, ok := a.GetObject().(*kapi.Pod)
// if we can't convert then we don't handle this object so just return
if !ok {
return nil
}
// get all constraints that are usable by the user
glog.V(4).Infof("getting security context constraints for pod %s (generate: %s) in namespace %s with user info %v", pod.Name, pod.GenerateName, a.GetNamespace(), a.GetUserInfo())
matchedConstraints, err := getMatchingSecurityContextConstraints(c.store, a.GetUserInfo())
if err != nil {
return kadmission.NewForbidden(a, err)
}
// get all constraints that are usable by the SA
if len(pod.Spec.ServiceAccountName) > 0 {
userInfo := serviceaccount.UserInfo(a.GetNamespace(), pod.Spec.ServiceAccountName, "")
glog.V(4).Infof("getting security context constraints for pod %s (generate: %s) with service account info %v", pod.Name, pod.GenerateName, userInfo)
saConstraints, err := getMatchingSecurityContextConstraints(c.store, userInfo)
if err != nil {
return kadmission.NewForbidden(a, err)
}
matchedConstraints = append(matchedConstraints, saConstraints...)
}
// remove duplicate constraints and sort
matchedConstraints = deduplicateSecurityContextConstraints(matchedConstraints)
sort.Sort(ByPriority(matchedConstraints))
providers, errs := c.createProvidersFromConstraints(a.GetNamespace(), matchedConstraints)
logProviders(pod, providers, errs)
if len(providers) == 0 {
return kadmission.NewForbidden(a, fmt.Errorf("no providers available to validated pod request"))
}
// all containers in a single pod must validate under a single provider or we will reject the request
validationErrs := field.ErrorList{}
for _, provider := range providers {
if errs := assignSecurityContext(provider, pod, field.NewPath(fmt.Sprintf("provider %s: ", provider.GetSCCName()))); len(errs) > 0 {
validationErrs = append(validationErrs, errs...)
continue
}
// the entire pod validated, annotate and accept the pod
glog.V(4).Infof("pod %s (generate: %s) validated against provider %s", pod.Name, pod.GenerateName, provider.GetSCCName())
if pod.ObjectMeta.Annotations == nil {
pod.ObjectMeta.Annotations = map[string]string{}
}
pod.ObjectMeta.Annotations[allocator.ValidatedSCCAnnotation] = provider.GetSCCName()
return nil
}
// we didn't validate against any security context constraint provider, reject the pod and give the errors for each attempt
glog.V(4).Infof("unable to validate pod %s (generate: %s) against any security context constraint: %v", pod.Name, pod.GenerateName, validationErrs)
return kadmission.NewForbidden(a, fmt.Errorf("unable to validate against any security context constraint: %v", validationErrs))
}
示例8: Admit
func (d *sccExecRestrictions) Admit(a admission.Attributes) (err error) {
if a.GetOperation() != admission.Connect {
return nil
}
if a.GetResource() != kapi.Resource("pods") {
return nil
}
if a.GetSubresource() != "attach" && a.GetSubresource() != "exec" {
return nil
}
pod, err := d.client.Pods(a.GetNamespace()).Get(a.GetName())
if err != nil {
return admission.NewForbidden(a, err)
}
// create a synthentic admission attribute to check SCC admission status for this pod
// clear the SA name, so that any permissions MUST be based on your user's power, not the SAs power.
pod.Spec.ServiceAccountName = ""
createAttributes := admission.NewAttributesRecord(pod, kapi.Kind("Pod"), a.GetNamespace(), a.GetName(), a.GetResource(), a.GetSubresource(), admission.Create, a.GetUserInfo())
if err := d.constraintAdmission.Admit(createAttributes); err != nil {
return admission.NewForbidden(a, err)
}
return nil
}
示例9: Admit
func (a *runOnceDuration) Admit(attributes admission.Attributes) error {
switch {
case a.config == nil,
!a.config.Enabled,
attributes.GetResource() != kapi.Resource("pods"),
len(attributes.GetSubresource()) > 0:
return nil
}
pod, ok := attributes.GetObject().(*kapi.Pod)
if !ok {
return admission.NewForbidden(attributes, fmt.Errorf("unexpected object: %#v", attributes.GetObject()))
}
// Only update pods with a restart policy of Never or OnFailure
switch pod.Spec.RestartPolicy {
case kapi.RestartPolicyNever,
kapi.RestartPolicyOnFailure:
// continue
default:
return nil
}
appliedProjectOverride, err := a.applyProjectAnnotationOverride(attributes.GetNamespace(), pod)
if err != nil {
return admission.NewForbidden(attributes, err)
}
if !appliedProjectOverride && a.config.ActiveDeadlineSecondsOverride != nil {
pod.Spec.ActiveDeadlineSeconds = a.config.ActiveDeadlineSecondsOverride
}
return nil
}
示例10: Admit
// Admit will deny any pod that defines AntiAffinity topology key other than unversioned.LabelHostname i.e. "kubernetes.io/hostname"
// in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution.
func (p *plugin) Admit(attributes admission.Attributes) (err error) {
if attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil
}
pod, ok := attributes.GetObject().(*api.Pod)
if !ok {
return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted")
}
affinity, err := api.GetAffinityFromPodAnnotations(pod.Annotations)
if err != nil {
// this is validated later
return nil
}
if affinity.PodAntiAffinity != nil {
var podAntiAffinityTerms []api.PodAffinityTerm
if len(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) != 0 {
podAntiAffinityTerms = affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution
}
// TODO: Uncomment this block when implement RequiredDuringSchedulingRequiredDuringExecution.
//if len(affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution) != 0 {
// podAntiAffinityTerms = append(podAntiAffinityTerms, affinity.PodAntiAffinity.RequiredDuringSchedulingRequiredDuringExecution...)
//}
for _, v := range podAntiAffinityTerms {
if v.TopologyKey != unversioned.LabelHostname {
return apierrors.NewForbidden(attributes.GetResource().GroupResource(), pod.Name, fmt.Errorf("affinity.PodAntiAffinity.RequiredDuringScheduling has TopologyKey %v but only key %v is allowed", v.TopologyKey, unversioned.LabelHostname))
}
}
}
return nil
}
示例11: Admit
// Admit determines if the endpoints object should be admitted
func (r *restrictedEndpointsAdmission) Admit(a kadmission.Attributes) error {
if a.GetResource().GroupResource() != kapi.Resource("endpoints") {
return nil
}
ep, ok := a.GetObject().(*kapi.Endpoints)
if !ok {
return nil
}
old, ok := a.GetOldObject().(*kapi.Endpoints)
if ok && reflect.DeepEqual(ep.Subsets, old.Subsets) {
return nil
}
restrictedIP := r.findRestrictedIP(ep)
if restrictedIP == "" {
return nil
}
allow, err := r.checkAccess(a)
if err != nil {
return err
}
if !allow {
return kadmission.NewForbidden(a, fmt.Errorf("endpoint address %s is not allowed", restrictedIP))
}
return nil
}
示例12: Admit
func (e *exists) Admit(a admission.Attributes) (err error) {
defaultVersion, kind, err := api.RESTMapper.VersionAndKindForResource(a.GetResource())
if err != nil {
return admission.NewForbidden(a, err)
}
mapping, err := api.RESTMapper.RESTMapping(kind, defaultVersion)
if err != nil {
return admission.NewForbidden(a, err)
}
if mapping.Scope.Name() != meta.RESTScopeNameNamespace {
return nil
}
namespace := &api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: a.GetNamespace(),
Namespace: "",
},
Status: api.NamespaceStatus{},
}
_, exists, err := e.store.Get(namespace)
if err != nil {
return admission.NewForbidden(a, err)
}
if exists {
return nil
}
// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not
_, err = e.client.Namespaces().Get(a.GetNamespace())
if err != nil {
return admission.NewForbidden(a, fmt.Errorf("Namespace %s does not exist", a.GetNamespace()))
}
return nil
}
示例13: Admit
func (a *gcPermissionsEnforcement) Admit(attributes admission.Attributes) (err error) {
// if we aren't changing owner references, then the edit is always allowed
if !isChangingOwnerReference(attributes.GetObject(), attributes.GetOldObject()) {
return nil
}
deleteAttributes := authorizer.AttributesRecord{
User: attributes.GetUserInfo(),
Verb: "delete",
Namespace: attributes.GetNamespace(),
APIGroup: attributes.GetResource().Group,
APIVersion: attributes.GetResource().Version,
Resource: attributes.GetResource().Resource,
Subresource: attributes.GetSubresource(),
Name: attributes.GetName(),
ResourceRequest: true,
Path: "",
}
allowed, reason, err := a.authorizer.Authorize(deleteAttributes)
if allowed {
return nil
}
return admission.NewForbidden(attributes, fmt.Errorf("cannot set an ownerRef on a resource you can't delete: %v, %v", reason, err))
}
示例14: Admit
// Admit will deny pods that have a RunAsUser set that isn't the uid of the user requesting it
func (p *plugin) Admit(a admission.Attributes) (err error) {
if a.GetResource() != string(api.ResourcePods) {
return nil
}
pod, ok := a.GetObject().(*api.Pod)
if !ok {
return apierrors.NewBadRequest("Resource was marked with kind Pod but was unable to be converted")
}
user := a.GetUserInfo()
if user == nil {
return apierrors.NewBadRequest("uidenforcer admission controller can not be used if there is no user set")
}
for i := 0; i < len(pod.Spec.Containers); i++ {
container := &pod.Spec.Containers[i]
uid, ok := strconv.ParseInt(user.GetUID(), 10, 32)
if ok == nil {
if container.SecurityContext == nil {
container.SecurityContext = &api.SecurityContext{
RunAsUser: &uid,
}
} else {
container.SecurityContext.RunAsUser = &uid
}
} else {
return apierrors.NewBadRequest("Requesting user's uid is not an integer")
}
}
return nil
}
示例15: Admit
// Admit enforces that a namespace must exist in order to associate content with it.
// Admit enforces that a namespace that is terminating cannot accept new content being associated with it.
func (e *lifecycle) Admit(a admission.Attributes) (err error) {
if len(a.GetNamespace()) == 0 {
return nil
}
// always allow creatable resources through. These requests should always be allowed.
if e.creatableResources[a.GetResource().GroupResource()] {
return nil
}
groupMeta, err := registered.Group(a.GetKind().Group)
if err != nil {
return err
}
mapping, err := groupMeta.RESTMapper.RESTMapping(a.GetKind().GroupKind())
if err != nil {
glog.V(4).Infof("Ignoring life-cycle enforcement for resource %v; no associated default version and kind could be found.", a.GetResource())
return nil
}
if mapping.Scope.Name() != meta.RESTScopeNameNamespace {
return nil
}
if !e.cache.Running() {
return admission.NewForbidden(a, err)
}
namespace, err := e.cache.GetNamespace(a.GetNamespace())
if err != nil {
return admission.NewForbidden(a, err)
}
// in case of concurrency issues, we will retry this logic
numRetries := 10
interval := time.Duration(rand.Int63n(90)+int64(10)) * time.Millisecond
for retry := 1; retry <= numRetries; retry++ {
// associate this namespace with openshift
_, err = projectutil.Associate(e.client, namespace)
if err == nil {
break
}
// we have exhausted all reasonable efforts to retry so give up now
if retry == numRetries {
return admission.NewForbidden(a, err)
}
// get the latest namespace for the next pass in case of resource version updates
time.Sleep(interval)
// it's possible the namespace actually was deleted, so just forbid if this occurs
namespace, err = e.client.Core().Namespaces().Get(a.GetNamespace())
if err != nil {
return admission.NewForbidden(a, err)
}
}
return nil
}