mirror of
https://github.com/k8sgpt-ai/k8sgpt.git
synced 2026-07-17 02:04:40 +00:00
fix: guard against nil spec.replicas in deployment analyzer (#1683)
The Deployment analyzer dereferenced *deployment.Spec.Replicas without a nil check. Spec.Replicas is a *int32 and, although the API server usually defaults it to 1, a Deployment object whose replicas field is explicitly unset (nil) panics the analyze run with a nil pointer dereference. Guard the comparison with a nil check, mirroring the sibling StatefulSet analyzer which already checks Spec.Replicas != nil before dereferencing. Add a regression test that analyzes a Deployment with nil Spec.Replicas and asserts Analyze does not panic. Signed-off-by: Anas Khan <83116240+anxkhn@users.noreply.github.com> Co-authored-by: Alex Jones <1235925+AlexsJones@users.noreply.github.com>
This commit is contained in:
@@ -54,7 +54,7 @@ func (d DeploymentAnalyzer) Analyze(a common.Analyzer) ([]common.Result, error)
|
||||
|
||||
for _, deployment := range deployments.Items {
|
||||
var failures []common.Failure
|
||||
if *deployment.Spec.Replicas != deployment.Status.ReadyReplicas {
|
||||
if deployment.Spec.Replicas != nil && *deployment.Spec.Replicas != deployment.Status.ReadyReplicas {
|
||||
if deployment.Status.Replicas > *deployment.Spec.Replicas {
|
||||
doc := apiDoc.GetApiDocV2("spec.replicas")
|
||||
|
||||
|
||||
@@ -74,6 +74,48 @@ func TestDeploymentAnalyzer(t *testing.T) {
|
||||
assert.Equal(t, analysisResults[0].Name, "default/example")
|
||||
}
|
||||
|
||||
func TestDeploymentAnalyzerNilReplicas(t *testing.T) {
|
||||
// A Deployment with an unset spec.replicas (nil) must not panic the analyzer.
|
||||
clientset := fake.NewSimpleClientset(&appsv1.Deployment{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: "example",
|
||||
Namespace: "default",
|
||||
},
|
||||
Spec: appsv1.DeploymentSpec{
|
||||
Replicas: nil,
|
||||
Template: v1.PodTemplateSpec{
|
||||
Spec: v1.PodSpec{
|
||||
Containers: []v1.Container{
|
||||
{
|
||||
Name: "example-container",
|
||||
Image: "nginx",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
Status: appsv1.DeploymentStatus{
|
||||
Replicas: 2,
|
||||
AvailableReplicas: 1,
|
||||
},
|
||||
})
|
||||
|
||||
config := common.Analyzer{
|
||||
Client: &kubernetes.Client{
|
||||
Client: clientset,
|
||||
},
|
||||
Context: context.Background(),
|
||||
Namespace: "default",
|
||||
}
|
||||
|
||||
deploymentAnalyzer := DeploymentAnalyzer{}
|
||||
analysisResults, err := deploymentAnalyzer.Analyze(config)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
assert.Equal(t, len(analysisResults), 0)
|
||||
}
|
||||
|
||||
func TestDeploymentAnalyzerNamespaceFiltering(t *testing.T) {
|
||||
clientset := fake.NewSimpleClientset(
|
||||
&appsv1.Deployment{
|
||||
|
||||
Reference in New Issue
Block a user