@@ -26,6 +26,9 @@ import (
26
26
27
27
v1 "k8s.io/api/core/v1"
28
28
"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"
29
32
"k8s.io/client-go/tools/record"
30
33
"k8s.io/klog/v2"
31
34
ctrl "sigs.k8s.io/controller-runtime"
@@ -99,7 +102,9 @@ func (r *ShardingConfigReconciler) Reconcile(ctx context.Context, req ctrl.Reque
99
102
}
100
103
return reconcile.Result {}, err
101
104
}
102
-
105
+ if err = r .clearOldPods (ctx , shardingConfig .Namespace ); err != nil {
106
+ return reconcile.Result {}, err
107
+ }
103
108
allPods , err := r .getPodsForShardingConfig (ctx , shardingConfig )
104
109
if err != nil {
105
110
return reconcile.Result {}, err
@@ -280,6 +285,42 @@ func (r *ShardingConfigReconciler) getPodsForShardingConfig(ctx context.Context,
280
285
return pods , nil
281
286
}
282
287
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
+
283
324
// SetupWithManager sets up the controller with the Manager.
284
325
func (r * ShardingConfigReconciler ) SetupWithManager (mgr ctrl.Manager ) error {
285
326
r .recorder = mgr .GetEventRecorderFor ("sharding-config-controller" )
0 commit comments