← Back to Pull requests

Compute NumPropagatedObjects in HNCConfiguration status #542

Merged
sophieliu15 merged 8 files (337 lines) on Mar 26, 2020 20:14 UTC
View on GitHub
sophieliu15 sophieliu15 commented on Mar 24, 2020 13:50 UTC
Author

This PR computes NumPropagatedObjects as a part of HNCConfiguration status. NumPropagatedObjects indicates the number of propagated objects of a specific type created by HNC.

Tested:unit tests, GKE cluster

Issue: #411

Diff: 337 lines (+279 / -58) across 8 files Reviewer: sophieliu15 Review duration: 3264m
All Vouch review confidence checks passed
Residual risk 0.14 = Change Risk (0.85) × (1 − Review Confidence (0.83)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.85 · 337 lines diff across 8 files
0.85
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
83%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.348
Self Review self_review
0.140
Sensitive Paths sensitive_paths
0.085
Real PR Conversation Timeline
40 items
sophieliu15 sophieliu15 commented on Mar 24, 2020 13:50 UTC
Author

/assign @adrianludwin
/assign @yiqigao217

sophieliu15 sophieliu15 commented on code on Mar 24, 2020 13:53 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config_test.go:1
@@ -96,25 +110,18 @@ var _ = Describe("HNCConfiguration", func() {
 			return updateHNCConfig(ctx, config)
 		}).Should(Succeed())
 
-		Eventually(hasHNCConfigurationConditionWithName(ctx, api.CritSingletonNameInvalid, nm)).Should(BeTrue())
-	})
-
-	It("should set ObjectReconcilerCreationFailed condition if an object reconciler creation fails", func() {

Remove this test case because it is tested in the following test case.

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:47 UTC
Code Review
incubator/hnc/pkg/forest/forest.go:1
@@ -32,6 +32,14 @@ type TypeSyncer interface {
 	// SetMode sets the propagation mode of objects that are handled by the reconciler who implements the interface.
 	// The method also syncs objects in the cluster for the type handled by the reconciler if necessary.
 	SetMode(context.Context, api.SynchronizationMode, logr.Logger) error
+	// GetNumPropagatedObjects returns the number of propagated objects on the apiserver.
+	GetNumPropagatedObjects() int32
+}
+
+// ConfigSyncer syncs the status of the HNCConfiguration object. ConfigReconciler implements the interface so that
+// it can be called by an ObjectReconciler if the status needs to be updated.
+type ConfigSyncer interface {
+	SyncHNCConfigStatus(logr.Logger)

Can we call this something a bit more descriptive? The Forest doesn't "know" about any of the configs; this name should indicate _why_ the forest is calling it. Eg something like PropagatedCountSink or something like that (e.g., "this is someone who wants to know when the number of objects has changed").

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:48 UTC
Code Review
incubator/hnc/pkg/forest/forest.go:1
@@ -86,6 +98,14 @@ func (f *Forest) GetTypeSyncer(gvk schema.GroupVersionKind) TypeSyncer {
 	return nil
 }
 
+func (f *Forest) AddConfigSyncer(c ConfigSyncer) {
+	f.config = c
+}
+
+func (f *Forest) GetConfigSyncer() ConfigSyncer {
+	return f.config
+}
+

We can just make f.config public so you don't need getters and setters. I've tried to only use those when there's nontrivial logic.

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:48 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config.go:1
@@ -33,22 +34,31 @@ type ConfigReconciler struct {
 	// Forest is the in-memory data structure that is shared with all other reconcilers.
 	Forest *forest.Forest
 
-	// Igniter is a channel of event.GenericEvent (see "Watching Channels" in
+	// Trigger is a channel of event.GenericEvent (see "Watching Channels" in

Nice

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:51 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config.go:1
@@ -362,21 +374,46 @@ func (r *ConfigReconciler) validateSingletonName(ctx context.Context, nm string)
 	return fmt.Errorf("Error while validating singleton name: %s", msg)
 }
 
-// forceInitialReconcile forces reconciliation to start after setting up the
-// controller with the manager. This is used to create a default singleton if
-// there is no singleton in the cluster. This occurs in a goroutine so the
+// addTypeStatus adds Status.Types for types configured in the spec.
+func (r *ConfigReconciler) addTypeStatus(inst *api.HNCConfiguration) {
+	for _, ts := range r.Forest.GetTypeSyncers() {

I'm not sure how consistent this order will be. Maybe we should ensure the final list is sorted alphabetically or something?

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:52 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -51,10 +53,14 @@ const (
 	ignore
 )
 
+type namespacedNameSet map[types.NamespacedName]bool

Comment to say what this will be used for

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:52 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -51,10 +53,14 @@ const (
 	ignore
 )
 
+type namespacedNameSet map[types.NamespacedName]bool
+
 // ObjectReconciler reconciles generic propagated objects. You must create one for each
 // group/version/kind that needs to be propagated and set its `GVK` field appropriately.
 type ObjectReconciler struct {
 	client.Client
+	lock sync.Mutex

Comment - what does this mutex protect? Or else, put it next to PropagatedObjects and call it PropagatedObjectsLock which is self-descriptive.

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:53 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -111,15 +120,22 @@ func (r *ObjectReconciler) SetMode(ctx context.Context, mode api.Synchronization
 	}
 	r.Log.Info("Changing mode of the object reconciler", "old", oldMode, "new", newMode)
 	r.Mode = newMode
-	// If the new mode is not "ignore", we need to update objects in the cluster
-	// (e.g., propagate or remove existing objects).
-	if newMode != api.Ignore {
-		err := r.enqueueAllObjects(ctx, r.Log)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
+	// For propagate and remove mode, we enqueue all objects to update objects in the cluster (e.g., propagate or
+	// remove existing objects). For ignore mode, we enqueue objects so that reconciliations of objects can trigger
+	// the config reconciler to update the status of the `config` singleton. Triggering object reconciliations in the
+	// ignore mode is necessary because only an object reconciler can compute NumPropagatedObjects for a given type.
+	err := r.enqueueAllObjects(ctx, r.Log)
+	return err
+}
+
+// GetNumPropagatedObjects returns the number of propagated objects of the GVK handled by this object reconciler.
+func (r *ObjectReconciler) GetNumPropagatedObjects() int32 {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()
+	n := len(r.PropagatedObjects)
+	r.lock.Unlock()

Better to say:

r.lock.Lock()
defer r.lock.Unlock()

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:53 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -111,15 +120,22 @@ func (r *ObjectReconciler) SetMode(ctx context.Context, mode api.Synchronization
 	}
 	r.Log.Info("Changing mode of the object reconciler", "old", oldMode, "new", newMode)
 	r.Mode = newMode
-	// If the new mode is not "ignore", we need to update objects in the cluster
-	// (e.g., propagate or remove existing objects).
-	if newMode != api.Ignore {
-		err := r.enqueueAllObjects(ctx, r.Log)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
+	// For propagate and remove mode, we enqueue all objects to update objects in the cluster (e.g., propagate or
+	// remove existing objects). For ignore mode, we enqueue objects so that reconciliations of objects can trigger
+	// the config reconciler to update the status of the `config` singleton. Triggering object reconciliations in the
+	// ignore mode is necessary because only an object reconciler can compute NumPropagatedObjects for a given type.
+	err := r.enqueueAllObjects(ctx, r.Log)
+	return err
+}
+
+// GetNumPropagatedObjects returns the number of propagated objects of the GVK handled by this object reconciler.
+func (r *ObjectReconciler) GetNumPropagatedObjects() int32 {

If we're not using sync/atomic anymore, this should probably just be int now, right?

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:55 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -180,9 +193,29 @@ func (r *ObjectReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
 			return resp, err
 		}
 	}
+
+	// We need to compute NumPropagatedObjects and show it in the status of the `config`
+	// singleton even in ignore mode.

Why? I thought we just stopped reporting status for anything in Ignore?

adrianludwin adrianludwin commented on code on Mar 25, 2020 12:57 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -111,15 +120,22 @@ func (r *ObjectReconciler) SetMode(ctx context.Context, mode api.Synchronization
 	}
 	r.Log.Info("Changing mode of the object reconciler", "old", oldMode, "new", newMode)
 	r.Mode = newMode
-	// If the new mode is not "ignore", we need to update objects in the cluster
-	// (e.g., propagate or remove existing objects).
-	if newMode != api.Ignore {
-		err := r.enqueueAllObjects(ctx, r.Log)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
+	// For propagate and remove mode, we enqueue all objects to update objects in the cluster (e.g., propagate or
+	// remove existing objects). For ignore mode, we enqueue objects so that reconciliations of objects can trigger
+	// the config reconciler to update the status of the `config` singleton. Triggering object reconciliations in the
+	// ignore mode is necessary because only an object reconciler can compute NumPropagatedObjects for a given type.

But SetMode can only be called from the HNC config reconciler, right? Which means that it already knows we're in Ignore mode, and it can stop displaying all statistics?

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:00 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -290,6 +323,7 @@ func (r *ObjectReconciler) syncPropagated(ctx context.Context, log logr.Logger,
 		return write, srcInst
 	}
 
+	r.addToNumPropagated(log, inst.GetNamespace(), inst.GetName())

Why is this here? Shouldn't we only call this in line 473, below?

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:00 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -539,6 +580,34 @@ func (r *ObjectReconciler) exclude(log logr.Logger, inst *unstructured.Unstructu
 	}
 }
 
+// addToNumPropagated adds a propagated object to the PropagatedObjects map if it does not exist.
+func (r *ObjectReconciler) addToNumPropagated(log logr.Logger, namespace, name string) {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()

Use defer

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:00 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -539,6 +580,34 @@ func (r *ObjectReconciler) exclude(log logr.Logger, inst *unstructured.Unstructu
 	}
 }
 
+// addToNumPropagated adds a propagated object to the PropagatedObjects map if it does not exist.
+func (r *ObjectReconciler) addToNumPropagated(log logr.Logger, namespace, name string) {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()
+	nnm := types.NamespacedName{
+		Namespace: namespace,
+		Name:      name,
+	}
+	if !r.PropagatedObjects[nnm] {
+		r.PropagatedObjects[nnm] = true
+	}
+	r.lock.Unlock()
+}
+
+// removeFromNumPropagated removes a propagated object to the PropagatedObjects map.
+func (r *ObjectReconciler) removeFromNumPropagated(log logr.Logger, namespace, name string) {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()

Use defer

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:01 UTC
Code Review
incubator/hnc/pkg/reconcilers/object_test.go:1
@@ -44,13 +44,13 @@ var _ = Describe("Secret", func() {
 		setParent(ctx, barName, fooName)
 		setParent(ctx, bazName, barName)
 
-		Eventually(hasObject(ctx, "Role", barName, "foo-role")).Should(BeTrue())
+		Eventually(hasObject(ctx, "Role", barName, "foo-role"), 4*time.Second).Should(BeTrue())

Save these magic frequencies somewhere as named constants

adrianludwin adrianludwin commented on Mar 25, 2020 13:01 UTC
Reviewer

Nice! Circling back to review the tests now but I wanted to send you what I already had.

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object_test.go:1
@@ -44,13 +44,13 @@ var _ = Describe("Secret", func() {
 		setParent(ctx, barName, fooName)
 		setParent(ctx, bazName, barName)
 
-		Eventually(hasObject(ctx, "Role", barName, "foo-role")).Should(BeTrue())
+		Eventually(hasObject(ctx, "Role", barName, "foo-role"), 4*time.Second).Should(BeTrue())

Wait, why are we waiting this long? The object should show up right away, it only takes 3s for it to show up in the HNC Config status.

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:05 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config_test.go:1
@@ -12,14 +13,24 @@ import (
 	v1 "k8s.io/api/rbac/v1"
 	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 )
 
 var _ = Describe("HNCConfiguration", func() {
-	// sleepTime is the time to sleep for objects propagation to take effect.
+	// objectPropagationTime is the time to sleep for objects propagation to take effect.
 	// From experiment it takes ~0.015s for HNC to propagate an object. Setting
 	// the sleep time to 1s should be long enough.
 	// We may need to increase the sleep time in future if HNC takes longer to propagate objects.
-	const sleepTime = 1 * time.Second
+	const objectPropagationTime = 1 * time.Second

We should specify that we only use this when we're expecting something _not_ to happen. Otherwise, we just use Eventually.

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:08 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config_test.go:1
@@ -12,14 +13,24 @@ import (
 	v1 "k8s.io/api/rbac/v1"
 	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
 )
 
 var _ = Describe("HNCConfiguration", func() {
-	// sleepTime is the time to sleep for objects propagation to take effect.
+	// objectPropagationTime is the time to sleep for objects propagation to take effect.
 	// From experiment it takes ~0.015s for HNC to propagate an object. Setting
 	// the sleep time to 1s should be long enough.
 	// We may need to increase the sleep time in future if HNC takes longer to propagate objects.
-	const sleepTime = 1 * time.Second
+	const objectPropagationTime = 1 * time.Second
+	// hncConfigReconciliationTime is the time to wait for reconciliation of the config
+	// object happens. It is the same as the sleep time at the beginning of the Reconcile method
+	// of HNCConfiguration.
+	const hncConfigReconciliationTime = 3 * time.Second
+	// hncConfigStatusUpdateTime is the time to wait for updating HNCConfiguration status on
+	// the apiserver. From experiment, this is the minimal integer seconds needed for the
+	// status to be updated successfully on the apiserver.
+	// We may need to increase the time in future if it takes longer to update status.
+	const hncConfigStatusUpdateTime = 7 * time.Second

This seems too high to me. From the time we make our _last_ change to an object, I would expect it would take no more than three seconds plus a little bit extra (e.g. four seconds should be enough): 3s for the HNC Config sleep to end, plus a bit of time for it to do its work. So if we said:

SetDefaultEventuallyTimeout(hncConfigReconciliationTime + 2 * time.Second)

Then Eventually will wait up to five seconds and that _should_ be more than enough time. (Or don't change the global default and just pass this into each Eventually) call.

Do you agree with this logic? And if so, do you know why it doesn't work?

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:10 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config_test.go:1
@@ -37,6 +51,7 @@ var _ = Describe("HNCConfiguration", func() {
 		Eventually(func() error {
 			return resetHNCConfigToDefault(ctx)
 		}).Should(Succeed())
+		SetDefaultEventuallyTimeout(2 * time.Second)

Is there a way to restore this to what it used to be (e.g. in case it wasn't 2s for some reason)?

adrianludwin adrianludwin commented on code on Mar 25, 2020 13:12 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config_test.go:1
@@ -28,6 +39,9 @@ var _ = Describe("HNCConfiguration", func() {
 	)
 
 	BeforeEach(func() {
+		// Increase the timeout of `Eventually` for test cases in this file because the `Reconcile`
+		// method of ConfigReconciler sleeps at the very beginning of the method.
+		SetDefaultEventuallyTimeout(4 * time.Second)

You're already overriding Eventually with the constants you've defined above, why do you need this too?

adrianludwin adrianludwin commented on Mar 25, 2020 13:19 UTC
Reviewer

Eh, now I see the downside to putting the Sleep at the beginning of the Reconciler - it means that the regular business logic (e.g. adding/removing types) is also delayed by 3s. I'm not sure we want that. Sorry I missed that.

How about we write some logic to intercept the calls from the object reconcilers and make sure we only _trigger_ one reconciliation every N seconds? That way, most of the reconciler will still work ASAP. You'll have to write the deduping logic yourself but that should be pretty simple. Talk to Yiqi about how to trigger a periodic event using a long-running goroutine. It'll look something like this in the Setup function:

go func() {
  for { // have some kind of way to break the loop when the controller exits
    time.Sleep(3 * time.Second) // use constant instead
    if r.objCountChanged {
      r.objCountChanged = false
      r.enqueueReconcile()
    }
  }
}()

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:03 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -539,6 +580,34 @@ func (r *ObjectReconciler) exclude(log logr.Logger, inst *unstructured.Unstructu
 	}
 }
 
+// addToNumPropagated adds a propagated object to the PropagatedObjects map if it does not exist.
+func (r *ObjectReconciler) addToNumPropagated(log logr.Logger, namespace, name string) {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()
+	nnm := types.NamespacedName{
+		Namespace: namespace,
+		Name:      name,
+	}
+	if !r.PropagatedObjects[nnm] {
+		r.PropagatedObjects[nnm] = true
+	}
+	r.lock.Unlock()
+}
+
+// removeFromNumPropagated removes a propagated object to the PropagatedObjects map.
+func (r *ObjectReconciler) removeFromNumPropagated(log logr.Logger, namespace, name string) {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()

Done

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:03 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -539,6 +580,34 @@ func (r *ObjectReconciler) exclude(log logr.Logger, inst *unstructured.Unstructu
 	}
 }
 
+// addToNumPropagated adds a propagated object to the PropagatedObjects map if it does not exist.
+func (r *ObjectReconciler) addToNumPropagated(log logr.Logger, namespace, name string) {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()

Done

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -290,6 +323,7 @@ func (r *ObjectReconciler) syncPropagated(ctx context.Context, log logr.Logger,
 		return write, srcInst
 	}
 
+	r.addToNumPropagated(log, inst.GetNamespace(), inst.GetName())

If there are propagated objects on the apiserver before we install HNC, we will return ignore action here and those objects will not be counted by line 473 (write method will not be called).

For example, if we create namespace a and b, set a to be parent of b, add an object in a. The NumPropagatedObjects will be 1 as expected. Then if we reinstall (or restart) HNC, NumPropagatedObjects will be 0 if we don't have this line.

Added a comment to explain that.

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -111,15 +120,22 @@ func (r *ObjectReconciler) SetMode(ctx context.Context, mode api.Synchronization
 	}
 	r.Log.Info("Changing mode of the object reconciler", "old", oldMode, "new", newMode)
 	r.Mode = newMode
-	// If the new mode is not "ignore", we need to update objects in the cluster
-	// (e.g., propagate or remove existing objects).
-	if newMode != api.Ignore {
-		err := r.enqueueAllObjects(ctx, r.Log)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
+	// For propagate and remove mode, we enqueue all objects to update objects in the cluster (e.g., propagate or
+	// remove existing objects). For ignore mode, we enqueue objects so that reconciliations of objects can trigger
+	// the config reconciler to update the status of the `config` singleton. Triggering object reconciliations in the
+	// ignore mode is necessary because only an object reconciler can compute NumPropagatedObjects for a given type.

There might be some complications here. config reconciler can set the mode to anything (even an invalid mode). Object reconciler will validate the mode and change it to a valid mode if it is invalid (see getValidateMode).

Ideally, the config reconciler can get a valid mode from an object reconciler by adding& calling GetMode via the TypeSyncer interface. However, if a config reconciler creates (instead of syncs) an object reconciler, the Mode field of the object reconciler will be set to the valid mode when the (first) reconcile is called. If config reconciler calls GetMode before any reconcile happens, it will still get an invalid mode.

This might not be an issue if we only want to know if the mode is propagate in config reconciler (check for propagate or unset mode), but it will be an issue if we want to know if the mode is ignore. To let config reconciler knows the valid mode, we can either move getValidateMode back to config reconciler so config reconciler will set a valid mode to an object reconciler. Or we can see if we can set the Mode field to a valid mode when creating the object reconciler, so that we don't need to wait for the first reconciler to happen.

WDYT?

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -180,9 +193,29 @@ func (r *ObjectReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
 			return resp, err
 		}
 	}
+
+	// We need to compute NumPropagatedObjects and show it in the status of the `config`
+	// singleton even in ignore mode.

I might misunderstand that. We agreed on only reporting NumSourceObjects for propagate mode. I thought that meant we would report NumPropagatedObjects for all modes. I will delete the logic if we decide to follow the same rule and only report NumPropagatedObjects for propagate mode as well.

WDYT?

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -111,15 +120,22 @@ func (r *ObjectReconciler) SetMode(ctx context.Context, mode api.Synchronization
 	}
 	r.Log.Info("Changing mode of the object reconciler", "old", oldMode, "new", newMode)
 	r.Mode = newMode
-	// If the new mode is not "ignore", we need to update objects in the cluster
-	// (e.g., propagate or remove existing objects).
-	if newMode != api.Ignore {
-		err := r.enqueueAllObjects(ctx, r.Log)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
+	// For propagate and remove mode, we enqueue all objects to update objects in the cluster (e.g., propagate or
+	// remove existing objects). For ignore mode, we enqueue objects so that reconciliations of objects can trigger
+	// the config reconciler to update the status of the `config` singleton. Triggering object reconciliations in the
+	// ignore mode is necessary because only an object reconciler can compute NumPropagatedObjects for a given type.
+	err := r.enqueueAllObjects(ctx, r.Log)
+	return err
+}
+
+// GetNumPropagatedObjects returns the number of propagated objects of the GVK handled by this object reconciler.
+func (r *ObjectReconciler) GetNumPropagatedObjects() int32 {

Yes, we need int32 when we write to the status. Changed to int here and converted to int32 in the config reconciler.

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -111,15 +120,22 @@ func (r *ObjectReconciler) SetMode(ctx context.Context, mode api.Synchronization
 	}
 	r.Log.Info("Changing mode of the object reconciler", "old", oldMode, "new", newMode)
 	r.Mode = newMode
-	// If the new mode is not "ignore", we need to update objects in the cluster
-	// (e.g., propagate or remove existing objects).
-	if newMode != api.Ignore {
-		err := r.enqueueAllObjects(ctx, r.Log)
-		if err != nil {
-			return err
-		}
-	}
-	return nil
+	// For propagate and remove mode, we enqueue all objects to update objects in the cluster (e.g., propagate or
+	// remove existing objects). For ignore mode, we enqueue objects so that reconciliations of objects can trigger
+	// the config reconciler to update the status of the `config` singleton. Triggering object reconciliations in the
+	// ignore mode is necessary because only an object reconciler can compute NumPropagatedObjects for a given type.
+	err := r.enqueueAllObjects(ctx, r.Log)
+	return err
+}
+
+// GetNumPropagatedObjects returns the number of propagated objects of the GVK handled by this object reconciler.
+func (r *ObjectReconciler) GetNumPropagatedObjects() int32 {
+	// We need to lock the map because there can be concurrent reconciliation threads reading/writing
+	// the map.
+	r.lock.Lock()
+	n := len(r.PropagatedObjects)
+	r.lock.Unlock()

Done

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -51,10 +53,14 @@ const (
 	ignore
 )
 
+type namespacedNameSet map[types.NamespacedName]bool
+
 // ObjectReconciler reconciles generic propagated objects. You must create one for each
 // group/version/kind that needs to be propagated and set its `GVK` field appropriately.
 type ObjectReconciler struct {
 	client.Client
+	lock sync.Mutex

Changed to propagatedObjectsLock. Thanks for the suggestion!

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/object.go:1
@@ -51,10 +53,14 @@ const (
 	ignore
 )
 
+type namespacedNameSet map[types.NamespacedName]bool

Done.

sophieliu15 sophieliu15 commented on code on Mar 25, 2020 17:04 UTC
Code Review
incubator/hnc/pkg/reconcilers/hnc_config.go:1
@@ -362,21 +374,46 @@ func (r *ConfigReconciler) validateSingletonName(ctx context.Context, nm string)
 	return fmt.Errorf("Error while validating singleton name: %s", msg)
 }
 
-// forceInitialReconcile forces reconciliation to start after setting up the
-// controller with the manager. This is used to create a default singleton if
-// there is no singleton in the cluster. This occurs in a goroutine so the
+// addTypeStatus adds Status.Types for types configured in the spec.
+func (r *ConfigReconciler) addTypeStatus(inst *api.HNCConfiguration) {
+	for _, ts := range r.Forest.GetTypeSyncers() {

Cool! Sorted in alphabetical order based on APIVersion.

sophieliu15 sophieliu15 commented on Mar 25, 2020 17:05 UTC
Author

Eh, now I see the downside to putting the Sleep at the beginning of the Reconciler - it means that the regular business logic (e.g. adding/removing types) is also delayed by 3s. I'm not sure we want that. Sorry I missed that.

> How about we write some logic to intercept the calls from the object reconcilers and make sure we only _trigger_ one reconciliation every N seconds? That way, most of the reconciler will still work ASAP. You'll have to write the deduping logic yourself but that should be pretty simple. Talk to Yiqi about how to trigger a periodic event using a long-running goroutine. It'll look something like this in the Setup function:

>
> go func() {
>   for { // have some kind of way to break the loop when the controller exits
>     time.Sleep(3 * time.Second) // use constant instead
>     if r.objCountChanged {
>       r.objCountChanged = false
>       r.enqueueReconcile()
>     }
>   }
> }()
> 

Thanks for the suggestion! I will resolve the comments about tests later after I change to this method. Hopefully it won't take that long after.

sophieliu15 sophieliu15 commented on Mar 26, 2020 17:47 UTC
Author

Hi @adrianludwin

Thanks so much for the review. I updated the code and replied to all your comments. Feel free to take a look!

Thank you!

adrianludwin adrianludwin commented on Mar 26, 2020 18:49 UTC
Reviewer

Sorry for the terse comments, just trying to get this back to you ASAP. Almost ready to go, just a few last comments

adrianludwin adrianludwin commented on Mar 26, 2020 19:25 UTC
Reviewer

/lgtm
/approve
/assign @rjbez17
/hold

rjbez17 rjbez17 commented on Mar 26, 2020 20:09 UTC
Contributor

/lgtm
/approve
/hold cancel

k8s-ci-robot k8s-ci-robot commented on Mar 26, 2020 20:09 UTC
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/multi-tenancy/pull/542#pullrequestreview-382342732" title="Approved">adrianludwin</a>, <a href="https://github.com/kubernetes-sigs/multi-tenancy/pull/542#issuecomment-604658829" title="Approved">rjbez17</a>, <a href="https://github.com/kubernetes-sigs/multi-tenancy/pull/542#" title="Author self-approved">sophieliu15</a>

The full list of commands accepted by this bot can be found here.

The pull request process is described here

<details >
Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [adrianludwin,rjbez17]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    Reviewers
    Assignees
    sophieliu15 sophieliu15
    Labels
    risk: low confidence: 83.3% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.3% (HIGH) · Higher = larger blast radius
    85.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 83.3% · Lower = rushed or shallow review
    83.3%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14.3% · Safe to merge
    14.3%