@@ -26,6 +26,9 @@ import (
2626
2727 v1 "k8s.io/api/core/v1"
2828 "k8s.io/apimachinery/pkg/api/errors"
29+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
30+ "k8s.io/apimachinery/pkg/labels"
31+ "k8s.io/apimachinery/pkg/types"
2932 "k8s.io/client-go/tools/record"
3033 "k8s.io/klog/v2"
3134 ctrl "sigs.k8s.io/controller-runtime"
@@ -99,7 +102,9 @@ func (r *ShardingConfigReconciler) Reconcile(ctx context.Context, req ctrl.Reque
99102 }
100103 return reconcile.Result {}, err
101104 }
102-
105+ if err = r .clearOldPods (ctx , shardingConfig .Namespace ); err != nil {
106+ return reconcile.Result {}, err
107+ }
103108 allPods , err := r .getPodsForShardingConfig (ctx , shardingConfig )
104109 if err != nil {
105110 return reconcile.Result {}, err
@@ -280,6 +285,42 @@ func (r *ShardingConfigReconciler) getPodsForShardingConfig(ctx context.Context,
280285 return pods , nil
281286}
282287
288+ func (r * ShardingConfigReconciler ) clearOldPods (ctx context.Context , namespace string ) error {
289+ podList := v1.PodList {}
290+ if err := r .List (ctx , & podList , client .InNamespace (namespace ), client.HasLabels {ctrlmeshv1alpha1 .ShardingConfigInjectedKey }); err != nil {
291+ return err
292+ }
293+ for i := range podList .Items {
294+ po := & podList .Items [i ]
295+ if po .DeletionTimestamp != nil {
296+ continue
297+ }
298+ shardName := po .Labels [ctrlmeshv1alpha1 .ShardingConfigInjectedKey ]
299+ if shardName == "" {
300+ continue
301+ }
302+ shard := & ctrlmeshv1alpha1.ShardingConfig {}
303+ if err := r .Get (ctx , types.NamespacedName {Namespace : namespace , Name : shardName }, shard ); err != nil {
304+ if ! errors .IsNotFound (err ) {
305+ return err
306+ }
307+ err = r .Delete (ctx , po )
308+ if ! errors .IsNotFound (err ) {
309+ return err
310+ }
311+ continue
312+ }
313+ selector , _ := metav1 .LabelSelectorAsSelector (shard .Spec .Selector )
314+ if ! selector .Matches (labels .Set (po .Labels )) {
315+ err := r .Delete (ctx , po )
316+ if ! errors .IsNotFound (err ) {
317+ return err
318+ }
319+ }
320+ }
321+ return nil
322+ }
323+
283324// SetupWithManager sets up the controller with the Manager.
284325func (r * ShardingConfigReconciler ) SetupWithManager (mgr ctrl.Manager ) error {
285326 r .recorder = mgr .GetEventRecorderFor ("sharding-config-controller" )
0 commit comments