Skip to content

Commit

Permalink
Migrate RemovePodsHavingTooManyRestarts to plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
binacs committed Aug 9, 2022
1 parent 788e9f8 commit 3a9c897
Show file tree
Hide file tree
Showing 9 changed files with 317 additions and 179 deletions.
10 changes: 10 additions & 0 deletions pkg/apis/componentconfig/types_pluginargs.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,13 @@ type RemovePodsViolatingNodeAffinityArgs struct {
LabelSelector *metav1.LabelSelector
NodeAffinityType []string
}

// RemovePodsHavingTooManyRestartsArgs holds arguments used to configure RemovePodsHavingTooManyRestarts plugin.
type RemovePodsHavingTooManyRestartsArgs struct {
metav1.TypeMeta

Namespaces *api.Namespaces
LabelSelector *metav1.LabelSelector
PodRestartThreshold int32
IncludingInitContainers bool
}
17 changes: 16 additions & 1 deletion pkg/apis/componentconfig/validation/validation_pluginargs.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ package validation

import (
"fmt"
utilerrors "k8s.io/apimachinery/pkg/util/errors"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"sigs.k8s.io/descheduler/pkg/api"
"sigs.k8s.io/descheduler/pkg/apis/componentconfig"
)
Expand All @@ -41,6 +41,15 @@ func ValidateRemoveFailedPodsArgs(args *componentconfig.RemoveFailedPodsArgs) er
)
}

// ValidateRemovePodsHavingTooManyRestartsArgs validates RemovePodsHavingTooManyRestarts arguments
func ValidateRemovePodsHavingTooManyRestartsArgs(args *componentconfig.RemovePodsHavingTooManyRestartsArgs) error {
return errorsAggregate(
validateNamespaceArgs(args.Namespaces),
validateLabelSelectorArgs(args.LabelSelector),
validatePodRestartThreshold(args.PodRestartThreshold),
)
}

// errorsAggregate converts all arg validation errors to a single error interface.
// if no errors, it will return nil.
func errorsAggregate(errors ...error) error {
Expand Down Expand Up @@ -76,6 +85,12 @@ func ValidateRemovePodsViolatingNodeAffinityArgs(args *componentconfig.RemovePod
if args.Namespaces != nil && len(args.Namespaces.Include) > 0 && len(args.Namespaces.Exclude) > 0 {
return fmt.Errorf("only one of Include/Exclude namespaces can be set")
}
return nil
}

func validatePodRestartThreshold(podRestartThreshold int32) error {
if podRestartThreshold < 1 {
return fmt.Errorf("PodsHavingTooManyRestarts threshold not set")
}
return nil
}
35 changes: 35 additions & 0 deletions pkg/apis/componentconfig/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pkg/descheduler/descheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ func RunDeschedulerStrategies(ctx context.Context, rs *options.DeschedulerServer
"RemovePodsViolatingInterPodAntiAffinity": strategies.RemovePodsViolatingInterPodAntiAffinity,
"RemovePodsViolatingNodeAffinity": nil,
"RemovePodsViolatingNodeTaints": nil,
"RemovePodsHavingTooManyRestarts": strategies.RemovePodsHavingTooManyRestarts,
"RemovePodsHavingTooManyRestarts": nil,
"PodLifeTime": strategies.PodLifeTime,
"RemovePodsViolatingTopologySpreadConstraint": strategies.RemovePodsViolatingTopologySpreadConstraint,
"RemoveFailedPods": nil,
Expand Down
114 changes: 0 additions & 114 deletions pkg/descheduler/strategies/toomanyrestarts.go

This file was deleted.

26 changes: 26 additions & 0 deletions pkg/descheduler/strategy_migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"sigs.k8s.io/descheduler/pkg/apis/componentconfig/validation"
"sigs.k8s.io/descheduler/pkg/framework"
"sigs.k8s.io/descheduler/pkg/framework/plugins/removefailedpods"
"sigs.k8s.io/descheduler/pkg/framework/plugins/removepodshavingtoomanyrestarts"
"sigs.k8s.io/descheduler/pkg/framework/plugins/removepodsviolatingnodeaffinity"
"sigs.k8s.io/descheduler/pkg/framework/plugins/removepodsviolatingnodetaints"
)
Expand Down Expand Up @@ -103,4 +104,29 @@ var pluginsMap = map[string]func(ctx context.Context, nodes []*v1.Node, params *
klog.V(1).ErrorS(err, "plugin finished with error", "pluginName", removepodsviolatingnodeaffinity.PluginName)
}
},
"RemovePodsHavingTooManyRestarts": func(ctx context.Context, nodes []*v1.Node, params *api.StrategyParameters, handle *handleImpl) {
tooManyRestartsParams := params.PodsHavingTooManyRestarts
if tooManyRestartsParams == nil {
tooManyRestartsParams = &api.PodsHavingTooManyRestarts{}
}
args := &componentconfig.RemovePodsHavingTooManyRestartsArgs{
Namespaces: params.Namespaces,
LabelSelector: params.LabelSelector,
PodRestartThreshold: tooManyRestartsParams.PodRestartThreshold,
IncludingInitContainers: tooManyRestartsParams.IncludingInitContainers,
}
if err := validation.ValidateRemovePodsHavingTooManyRestartsArgs(args); err != nil {
klog.V(1).ErrorS(err, "unable to validate plugin arguments", "pluginName", removepodshavingtoomanyrestarts.PluginName)
return
}
pg, err := removepodshavingtoomanyrestarts.New(args, handle)
if err != nil {
klog.V(1).ErrorS(err, "unable to initialize a plugin", "pluginName", removepodshavingtoomanyrestarts.PluginName)
return
}
status := pg.(framework.DeschedulePlugin).Deschedule(ctx, nodes)
if status != nil && status.Err != nil {
klog.V(1).ErrorS(err, "plugin finished with error", "pluginName", removepodshavingtoomanyrestarts.PluginName)
}
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package removepodshavingtoomanyrestarts

import (
"context"
"fmt"

v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog/v2"

"sigs.k8s.io/descheduler/pkg/apis/componentconfig"
"sigs.k8s.io/descheduler/pkg/descheduler/evictions"
podutil "sigs.k8s.io/descheduler/pkg/descheduler/pod"
"sigs.k8s.io/descheduler/pkg/framework"
)

const PluginName = "RemovePodsHavingTooManyRestarts"

// RemovePodsHavingTooManyRestarts removes the pods that have too many restarts on node.
// There are too many cases leading this issue: Volume mount failed, app error due to nodes' different settings.
// As of now, this strategy won't evict daemonsets, mirror pods, critical pods and pods with local storages.
type RemovePodsHavingTooManyRestarts struct {
handle framework.Handle
args *componentconfig.RemovePodsHavingTooManyRestartsArgs
podFilter podutil.FilterFunc
}

var (
_ framework.Plugin = &RemovePodsHavingTooManyRestarts{}
_ framework.DeschedulePlugin = &RemovePodsHavingTooManyRestarts{}
)

// New builds plugin from its arguments while passing a handle
func New(args runtime.Object, handle framework.Handle) (framework.Plugin, error) {
tooManyRestartsArgs, ok := args.(*componentconfig.RemovePodsHavingTooManyRestartsArgs)
if !ok {
return nil, fmt.Errorf("want args to be of type RemovePodsHavingTooManyRestartsArgs, got %T", args)
}

var includedNamespaces, excludedNamespaces sets.String
if tooManyRestartsArgs.Namespaces != nil {
includedNamespaces = sets.NewString(tooManyRestartsArgs.Namespaces.Include...)
excludedNamespaces = sets.NewString(tooManyRestartsArgs.Namespaces.Exclude...)
}

podFilter, err := podutil.NewOptions().
WithFilter(handle.Evictor().Filter).
WithNamespaces(includedNamespaces).
WithoutNamespaces(excludedNamespaces).
WithLabelSelector(tooManyRestartsArgs.LabelSelector).
BuildFilterFunc()
if err != nil {
return nil, fmt.Errorf("error initializing pod filter function: %v", err)
}

podFilter = podutil.WrapFilterFuncs(podFilter, func(pod *v1.Pod) bool {
if err := validateCanEvict(pod, tooManyRestartsArgs); err != nil {
klog.V(4).InfoS(fmt.Sprintf("ignoring pod for eviction due to: %s", err.Error()), "pod", klog.KObj(pod))
return false
}
return true
})

return &RemovePodsHavingTooManyRestarts{
handle: handle,
args: tooManyRestartsArgs,
podFilter: podFilter,
}, nil
}

// Name retrieves the plugin name
func (d *RemovePodsHavingTooManyRestarts) Name() string {
return PluginName
}

// Deschedule extension point implementation for the plugin
func (d *RemovePodsHavingTooManyRestarts) Deschedule(ctx context.Context, nodes []*v1.Node) *framework.Status {
for _, node := range nodes {
klog.V(1).InfoS("Processing node", "node", klog.KObj(node))
pods, err := podutil.ListAllPodsOnANode(node.Name, d.handle.GetPodsAssignedToNodeFunc(), d.podFilter)
if err != nil {
// no pods evicted as error encountered retrieving evictable Pods
return &framework.Status{
Err: fmt.Errorf("error listing pods on a node: %v", err),
}
}
totalPods := len(pods)
for i := 0; i < totalPods; i++ {
d.handle.Evictor().Evict(ctx, pods[i], evictions.EvictOptions{})
if d.handle.Evictor().NodeLimitExceeded(node) {
break
}
}
}
return nil
}

// validateCanEvict looks at tooManyRestartsArgs to see if pod can be evicted given the args.
func validateCanEvict(pod *v1.Pod, tooManyRestartsArgs *componentconfig.RemovePodsHavingTooManyRestartsArgs) error {
var err error

restarts := calcContainerRestartsFromStatuses(pod.Status.ContainerStatuses)
if tooManyRestartsArgs.IncludingInitContainers {
restarts += calcContainerRestartsFromStatuses(pod.Status.InitContainerStatuses)
}

if restarts < tooManyRestartsArgs.PodRestartThreshold {
err = fmt.Errorf("number of container restarts (%v) not exceeding the threshold", restarts)
}

return err
}

// calcContainerRestartsFromStatuses get container restarts from container statuses.
func calcContainerRestartsFromStatuses(statuses []v1.ContainerStatus) int32 {
var restarts int32
for _, cs := range statuses {
restarts += cs.RestartCount
}
return restarts
}
Loading

0 comments on commit 3a9c897

Please sign in to comment.