Skip to content

allow leader election to accept namespace #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 14 additions & 36 deletions leader/leader.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,12 @@ import (
logf "sigs.k8s.io/controller-runtime/pkg/log"
)

type runModeType string

const (
localRunMode runModeType = "local"
)

// forceRunModeEnv indicates if the operator should be forced to run in either local
// or cluster mode (currently only used for local mode)
var forceRunModeEnv = "OSDK_FORCE_RUN_MODE"

// errNoNamespace indicates that a namespace could not be found for the current
// environment
var errNoNamespace = fmt.Errorf("namespace not found for current environment")
var errNoNamespace = fmt.Errorf("Namespace is required when running outside the cluster")

// errRunLocal indicates that the operator is set to run in local mode (this error
// is returned by functions that only work on operators running in cluster mode)
var errRunLocal = fmt.Errorf("operator run mode forced to local")
// namespaceDir is the default location where namespace information is stored
var namespaceDir = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"

// podNameEnvVar is the constant for env variable POD_NAME
// which is the name of the current pod.
Expand All @@ -59,23 +48,22 @@ var log = logf.Log.WithName("leader")
// attempts to become the leader.
const maxBackoffInterval = time.Second * 16

// Become ensures that the current pod is the leader within its namespace. If
// run outside a cluster, it will skip leader election and return nil. It
// Become ensures that the current pod is the leader within the given
// namespace. If run outside a cluster, it will return an error. It
// continuously tries to create a ConfigMap with the provided name and the
// current pod set as the owner reference. Only one can exist at a time with
// the same name, so the pod that successfully creates the ConfigMap is the
// leader. Upon termination of that pod, the garbage collector will delete the
// ConfigMap, enabling a different pod to become the leader.
func Become(ctx context.Context, lockName string) error {
// leader. Upon termination of that pod, the garbage collector will delete
// the ConfigMap, enabling a different pod to become the leader.
func Become(ctx context.Context, lockName string, ns string) error {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WDYT of duplicating the leaderelection.Options struct from controller-runtime and using that as a parameter to leader.Become()

Suggested change
func Become(ctx context.Context, lockName string, ns string) error {
func Become(ctx context.Context, opts Options) error {

log.Info("Trying to become the leader.")

ns, err := getOperatorNamespace()
if err != nil {
if err == errNoNamespace || err == errRunLocal {
log.Info("Skipping leader election; not running in a cluster.")
return nil
if ns == "" {
namespace, err := getOperatorNamespace()
if err != nil {
return err
}
return err
ns = namespace
}

config, err := config.GetConfig()
Expand Down Expand Up @@ -210,10 +198,7 @@ func isPodEvicted(pod corev1.Pod) bool {

// getOperatorNamespace returns the namespace the operator should be running in.
func getOperatorNamespace() (string, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: have this take a path to make it testable (without resetting a global in tests)

Suggested change
func getOperatorNamespace() (string, error) {
func getOperatorNamespace(namespacePath string) (string, error) {

if isRunModeLocal() {
return "", errRunLocal
}
nsBytes, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
nsBytes, err := ioutil.ReadFile(namespaceDir)
if err != nil {
if os.IsNotExist(err) {
return "", errNoNamespace
Expand All @@ -225,17 +210,10 @@ func getOperatorNamespace() (string, error) {
return ns, nil
}

func isRunModeLocal() bool {
return os.Getenv(forceRunModeEnv) == string(localRunMode)
}

// getPod returns a Pod object that corresponds to the pod in which the code
// is currently running.
// It expects the environment variable POD_NAME to be set by the downwards API.
func getPod(ctx context.Context, client crclient.Client, ns string) (*corev1.Pod, error) {
if isRunModeLocal() {
return nil, errRunLocal
}
podName := os.Getenv(podNameEnvVar)
if podName == "" {
return nil, fmt.Errorf("required env %s not set, please configure downward API", podNameEnvVar)
Expand Down
104 changes: 104 additions & 0 deletions leader/leader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package leader

import (
"context"
"testing"

corev1 "k8s.io/api/core/v1"
)

func TestBecome(t *testing.T) {
err := Become(context.TODO(), "testOperator", "foobar")
if err == nil {
t.Fatal("expected it to fail")
}
}

func TestGetOperatorNamespace(t *testing.T) {
namespaceDir = "/tmp/namespace"

testCases := []struct {
name string
expected string
expectedErr bool
}{
{
name: "no namespace available",
expectedErr: true,
},
}

// test
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actual, err := getOperatorNamespace()
if tc.expectedErr {
if err == nil {
t.Fatal("expected error but got none")
}
}
if actual != tc.expected {
t.Fatalf("expected %v received %v", tc.expected, actual)
}
})
}
}

func TestIsPodEvicted(t *testing.T) {
testCases := []struct {
name string
pod corev1.Pod
expected bool
}{
{
name: "Evicted pod returns true",
expected: true,
pod: corev1.Pod{
Status: corev1.PodStatus{
Phase: corev1.PodFailed,
Reason: "Evicted",
},
},
},
{
name: "Failed pod but not evicted returns false",
expected: false,
pod: corev1.Pod{
Status: corev1.PodStatus{
Phase: corev1.PodFailed,
Reason: "Don't know",
},
},
},
{
name: "Succeeded pod returns false",
expected: false,
pod: corev1.Pod{
Status: corev1.PodStatus{
Phase: corev1.PodSucceeded,
},
},
},
{
name: "Invalid reason for pod returns false",
expected: false,
pod: corev1.Pod{
Status: corev1.PodStatus{
Phase: corev1.PodSucceeded,
Reason: "Evicted",
},
},
},
}

// test
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actual := isPodEvicted(tc.pod)
if actual != tc.expected {
t.Fatalf("expected %v received %v", tc.expected, actual)
}
})
}

}