Skip to content

Commit d744fd4

Browse files
author
k8s-merge-robot
authored
Merge pull request kubernetes#27598 from xiangpengzhao/optimize_canRunPod
Automatic merge from submit-queue Refactor func canRunPod After refactoring, we only need to check `if pod.Spec.SecurityContext == nil` once. The logic is a bit clearer.
2 parents 700fbd0 + 28286d6 commit d744fd4

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

pkg/kubelet/util.go

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,24 @@ import (
2727

2828
// Check whether we have the capabilities to run the specified pod.
2929
func canRunPod(pod *api.Pod) error {
30-
if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostNetwork {
30+
if !capabilities.Get().AllowPrivileged {
31+
for _, container := range pod.Spec.Containers {
32+
if securitycontext.HasPrivilegedRequest(&container) {
33+
return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID)
34+
}
35+
}
36+
for _, container := range pod.Spec.InitContainers {
37+
if securitycontext.HasPrivilegedRequest(&container) {
38+
return fmt.Errorf("pod with UID %q specified privileged init container, but is disallowed", pod.UID)
39+
}
40+
}
41+
}
42+
43+
if pod.Spec.SecurityContext == nil {
44+
return nil
45+
}
46+
47+
if pod.Spec.SecurityContext.HostNetwork {
3148
allowed, err := allowHostNetwork(pod)
3249
if err != nil {
3350
return err
@@ -37,7 +54,7 @@ func canRunPod(pod *api.Pod) error {
3754
}
3855
}
3956

40-
if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostPID {
57+
if pod.Spec.SecurityContext.HostPID {
4158
allowed, err := allowHostPID(pod)
4259
if err != nil {
4360
return err
@@ -47,7 +64,7 @@ func canRunPod(pod *api.Pod) error {
4764
}
4865
}
4966

50-
if pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostIPC {
67+
if pod.Spec.SecurityContext.HostIPC {
5168
allowed, err := allowHostIPC(pod)
5269
if err != nil {
5370
return err
@@ -57,18 +74,6 @@ func canRunPod(pod *api.Pod) error {
5774
}
5875
}
5976

60-
if !capabilities.Get().AllowPrivileged {
61-
for _, container := range pod.Spec.Containers {
62-
if securitycontext.HasPrivilegedRequest(&container) {
63-
return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID)
64-
}
65-
}
66-
for _, container := range pod.Spec.InitContainers {
67-
if securitycontext.HasPrivilegedRequest(&container) {
68-
return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID)
69-
}
70-
}
71-
}
7277
return nil
7378
}
7479

0 commit comments

Comments
 (0)