Skip to content

Commit

Permalink
Merge pull request #4521 from enxebre/get-node-index
Browse files Browse the repository at this point in the history
🌱 Add providerID index to get nodes
  • Loading branch information
k8s-ci-robot authored Jul 19, 2021
2 parents 604a465 + 3c9e61a commit 9719e4f
Show file tree
Hide file tree
Showing 11 changed files with 273 additions and 102 deletions.
51 changes: 31 additions & 20 deletions controllers/machine_controller_noderef.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,15 @@ import (
"context"
"fmt"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/cluster-api/util/annotations"
"sigs.k8s.io/cluster-api/util/patch"

"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4"
"sigs.k8s.io/cluster-api/controllers/noderefutil"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/annotations"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
Expand Down Expand Up @@ -170,29 +169,41 @@ func summarizeNodeConditions(node *corev1.Node) (corev1.ConditionStatus, string)

func (r *MachineReconciler) getNode(ctx context.Context, c client.Reader, providerID *noderefutil.ProviderID) (*corev1.Node, error) {
log := ctrl.LoggerFrom(ctx, "providerID", providerID)

nodeList := corev1.NodeList{}
for {
if err := c.List(ctx, &nodeList, client.Continue(nodeList.Continue)); err != nil {
return nil, err
}
if err := c.List(ctx, &nodeList, client.MatchingFields{noderefutil.NodeProviderIDIndex: providerID.IndexKey()}); err != nil {
return nil, err
}
if len(nodeList.Items) == 0 {
// If for whatever reason the index isn't registered or available, we fallback to loop over the whole list.
nl := corev1.NodeList{}
for {
if err := c.List(ctx, &nl, client.Continue(nl.Continue)); err != nil {
return nil, err
}

for key, node := range nl.Items {
nodeProviderID, err := noderefutil.NewProviderID(node.Spec.ProviderID)
if err != nil {
log.Error(err, "Failed to parse ProviderID", "node", client.ObjectKeyFromObject(&nl.Items[key]).String())
continue
}

for _, node := range nodeList.Items {
nodeProviderID, err := noderefutil.NewProviderID(node.Spec.ProviderID)
if err != nil {
log.Error(err, "Failed to parse ProviderID", "node", node.Name)
continue
if providerID.Equals(nodeProviderID) {
return &node, nil
}
}

if providerID.Equals(nodeProviderID) {
return &node, nil
if nl.Continue == "" {
break
}
}

if nodeList.Continue == "" {
break
}
return nil, ErrNodeNotFound
}

if len(nodeList.Items) != 1 {
return nil, fmt.Errorf("unexpectedly found more than one Node matching the providerID %s", providerID.String())
}

return nil, ErrNodeNotFound
return &nodeList.Items[0], nil
}
184 changes: 117 additions & 67 deletions controllers/machine_controller_noderef_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,101 +20,151 @@ import (
"testing"

. "github.com/onsi/gomega"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/record"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4"
"sigs.k8s.io/cluster-api/controllers/noderefutil"
"sigs.k8s.io/cluster-api/controllers/remote"
"sigs.k8s.io/cluster-api/util"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

func TestGetNodeReference(t *testing.T) {
func TestGetNode(t *testing.T) {
g := NewWithT(t)

r := &MachineReconciler{
Client: fake.NewClientBuilder().Build(),
recorder: record.NewFakeRecorder(32),
}
ns, err := env.CreateNamespace(ctx, "test-get-node")
g.Expect(err).ToNot(HaveOccurred())

nodeList := []client.Object{
&corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "node-1",
},
Spec: corev1.NodeSpec{
ProviderID: "aws://us-east-1/id-node-1",
},
},
&corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "node-2",
},
Spec: corev1.NodeSpec{
ProviderID: "aws://us-west-2/id-node-2",
},
},
&corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "gce-node-2",
},
Spec: corev1.NodeSpec{
ProviderID: "gce://us-central1/id-node-2",
},
// Set up cluster to test against.
testCluster := &clusterv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "test-get-node-",
Namespace: ns.Name,
},
}

client := fake.NewClientBuilder().WithObjects(nodeList...).Build()
g.Expect(env.Create(ctx, testCluster)).To(BeNil())
g.Expect(env.CreateKubeconfigSecret(ctx, testCluster)).To(Succeed())
defer func(do ...client.Object) {
g.Expect(env.Cleanup(ctx, do...)).To(Succeed())
}(ns, testCluster)

testCases := []struct {
name string
providerID string
expected *corev1.ObjectReference
err error
name string
node *corev1.Node
providerIDInput string
error error
}{
{
name: "valid provider id, valid aws node",
providerID: "aws:///id-node-1",
expected: &corev1.ObjectReference{Name: "node-1"},
name: "full providerID matches",
node: &corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "test-get-node-node-1",
},
Spec: corev1.NodeSpec{
ProviderID: "aws://us-east-1/test-get-node-1",
},
},
providerIDInput: "aws://us-east-1/test-get-node-1",
},
{
name: "valid provider id, valid aws node",
providerID: "aws:///id-node-2",
expected: &corev1.ObjectReference{Name: "node-2"},
name: "aws prefix: cloudProvider and ID matches",
node: &corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "test-get-node-node-2",
},
Spec: corev1.NodeSpec{
ProviderID: "aws://us-west-2/test-get-node-2",
},
},
providerIDInput: "aws:///test-get-node-2",
},
{
name: "valid provider id, valid gce node",
providerID: "gce:///id-node-2",
expected: &corev1.ObjectReference{Name: "gce-node-2"},
name: "gce prefix, cloudProvider and ID matches",
node: &corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "test-get-node-gce-node-2",
},
Spec: corev1.NodeSpec{
ProviderID: "gce://us-central1/test-get-node-2",
},
},
providerIDInput: "gce:///test-get-node-2",
},
{
name: "valid provider id, no node found",
providerID: "aws:///id-node-100",
expected: nil,
err: ErrNodeNotFound,
name: "Node is not found",
node: &corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "test-get-node-not-found",
},
Spec: corev1.NodeSpec{
ProviderID: "gce://us-central1/anything",
},
},
providerIDInput: "gce://not-found",
error: ErrNodeNotFound,
},
}

for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
gt := NewWithT(t)
providerID, err := noderefutil.NewProviderID(test.providerID)
gt.Expect(err).NotTo(HaveOccurred(), "Expected no error parsing provider id %q, got %v", test.providerID, err)

node, err := r.getNode(ctx, client, providerID)
if test.err == nil {
g.Expect(err).To(BeNil())
} else {
gt.Expect(err).NotTo(BeNil())
gt.Expect(err).To(Equal(test.err), "Expected error %v, got %v", test.err, err)
}
nodesToCleanup := make([]client.Object, 0, len(testCases))
for _, tc := range testCases {
g.Expect(env.Create(ctx, tc.node)).To(BeNil())
nodesToCleanup = append(nodesToCleanup, tc.node)
}
defer func(do ...client.Object) {
g.Expect(env.Cleanup(ctx, do...)).To(Succeed())
}(nodesToCleanup...)

tracker, err := remote.NewClusterCacheTracker(
env.Manager, remote.ClusterCacheTrackerOptions{
Indexes: []remote.Index{
{
Object: &corev1.Node{},
Field: noderefutil.NodeProviderIDIndex,
ExtractValue: noderefutil.IndexNodeByProviderID,
},
},
},
)
g.Expect(err).ToNot(HaveOccurred())

r := &MachineReconciler{
Tracker: tracker,
Client: env,
}

w, err := ctrl.NewControllerManagedBy(env.Manager).For(&corev1.Node{}).Build(r)
g.Expect(err).ToNot(HaveOccurred())

g.Expect(tracker.Watch(ctx, remote.WatchInput{
Name: "TestGetNode",
Cluster: util.ObjectKey(testCluster),
Watcher: w,
Kind: &corev1.Node{},
EventHandler: handler.EnqueueRequestsFromMapFunc(func(client.Object) []reconcile.Request {
return nil
}),
})).To(Succeed())

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
g := NewWithT(t)
remoteClient, err := r.Tracker.GetClient(ctx, util.ObjectKey(testCluster))
g.Expect(err).ToNot(HaveOccurred())

if test.expected == nil && node == nil {
providerID, err := noderefutil.NewProviderID(tc.providerIDInput)
g.Expect(err).ToNot(HaveOccurred())

node, err := r.getNode(ctx, remoteClient, providerID)
if tc.error != nil {
g.Expect(err).To(Equal(tc.error))
return
}

gt.Expect(node.Name).To(Equal(test.expected.Name), "Expected NodeRef's name to be %v, got %v", node.Name, test.expected.Name)
gt.Expect(node.Namespace).To(Equal(test.expected.Namespace), "Expected NodeRef's namespace to be %v, got %v", node.Namespace, test.expected.Namespace)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(node.Name).To(Equal(tc.node.Name))
})
}
}
Expand Down
26 changes: 26 additions & 0 deletions controllers/noderefutil/indexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,18 @@ import (
"fmt"

"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
// NodeProviderIDIndex is used to index Nodes by ProviderID. Remote caches use this to find Nodes in a workload cluster
// out of management cluster machine.spec.providerID.
NodeProviderIDIndex = "spec.providerID"
)

// AddMachineNodeIndex adds the machine node name index to the
// managers cache.
func AddMachineNodeIndex(ctx context.Context, mgr ctrl.Manager) error {
Expand All @@ -50,3 +57,22 @@ func indexMachineByNodeName(o client.Object) []string {
}
return nil
}

// IndexNodeByProviderID contains the logic to index Nodes by ProviderID.
func IndexNodeByProviderID(o client.Object) []string {
node, ok := o.(*corev1.Node)
if !ok {
panic(fmt.Sprintf("Expected a Node but got a %T", o))
}

if node.Spec.ProviderID != "" {
providerID, err := NewProviderID(node.Spec.ProviderID)
if err != nil {
// Failed to create providerID, skipping.
return nil
}
return []string{providerID.IndexKey()}
}

return nil
}
9 changes: 9 additions & 0 deletions controllers/noderefutil/providerid.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package noderefutil

import (
"errors"
"fmt"
"regexp"
"strings"
)
Expand Down Expand Up @@ -100,3 +101,11 @@ func (p *ProviderID) String() string {
func (p *ProviderID) Validate() bool {
return p.CloudProvider() != "" && p.ID() != ""
}

// IndexKey returns a string concatenating the cloudProvider and the ID parts of the providerID.
// E.g Format: cloudProvider://optional/segments/etc/id. IndexKey: cloudProvider/id
// This is useful to use the providerID as a reliable index between nodes and machines
// as it guarantees the infra Providers contract.
func (p *ProviderID) IndexKey() string {
return fmt.Sprintf("%s/%s", p.CloudProvider(), p.ID())
}
Loading

0 comments on commit 9719e4f

Please sign in to comment.