Skip to content

Commit

Permalink
Fix nil pointer deref in affinity plugin
Browse files Browse the repository at this point in the history
Both Pod.Spec.Affinity and Pod.Spec.Affinity.NodeAffinity can be nil,
which is properly checked now.
  • Loading branch information
Nuckal777 committed Oct 27, 2021
1 parent d3312f7 commit 48f82b7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 11 deletions.
21 changes: 21 additions & 0 deletions controllers/node_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,27 @@ var _ = Describe("The affinity plugin", func() {

})

It("does not crash if a pod has no affinity set at all", func() {
pod := &corev1.Pod{}
pod.Namespace = "default"
pod.Name = "container"
pod.Spec.NodeName = firstNode.Name
pod.Spec.Containers = []corev1.Container{
{
Name: "nginx",
Image: "nginx",
},
}
Expect(k8sClient.Create(context.Background(), pod)).To(Succeed())
affinity := impl.Affinity{}
result, err := affinity.Check(buildParams(firstNode))
Expect(err).To(Succeed())
Expect(result).To(BeTrue())
result, err = affinity.Check(buildParams(secondNode))
Expect(err).To(Succeed())
Expect(result).To(BeTrue())
})

})

var _ = Describe("The nodecount plugin", func() {
Expand Down
33 changes: 22 additions & 11 deletions plugin/impl/affinity.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,22 +99,33 @@ func hasAffinityPod(nodeName string, params *plugin.Parameters) (bool, error) {
if err != nil {
return false, err
}
for _, pod := range podList.Items {
for _, preferred := range pod.Spec.Affinity.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution {
for _, expr := range preferred.Preference.MatchExpressions {
affinityPod := expr.Key == constants.StateLabelKey &&
expr.Operator == v1.NodeSelectorOpIn &&
len(expr.Values) == 1 &&
expr.Values[0] == "operational"
if affinityPod {
return true, nil
}
}
for i := range podList.Items {
if hasOperationalAffinity(&podList.Items[i]) {
return true, nil
}
}
return false, nil
}

func hasOperationalAffinity(pod *v1.Pod) bool {
if pod.Spec.Affinity == nil || pod.Spec.Affinity.NodeAffinity == nil {
return false
}
nodeAffinity := pod.Spec.Affinity.NodeAffinity
for _, preferred := range nodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution {
for _, expr := range preferred.Preference.MatchExpressions {
affinityPod := expr.Key == constants.StateLabelKey &&
expr.Operator == v1.NodeSelectorOpIn &&
len(expr.Values) == 1 &&
expr.Values[0] == "operational"
if affinityPod {
return true
}
}
}
return false
}

func (a *Affinity) AfterEval(chainResult bool, params plugin.Parameters) error {
return nil
}

0 comments on commit 48f82b7

Please sign in to comment.