@@ -18,6 +18,7 @@ package leaderelection
18
18
19
19
import (
20
20
"fmt"
21
+ "io/ioutil"
21
22
"os"
22
23
23
24
"k8s.io/apimachinery/pkg/util/uuid"
@@ -27,6 +28,8 @@ import (
27
28
"sigs.k8s.io/controller-runtime/pkg/recorder"
28
29
)
29
30
31
+ const inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
32
+
30
33
// Options provides the required configuration to create a new resource lock
31
34
type Options struct {
32
35
// LeaderElection determines whether or not to use leader election when
@@ -49,8 +52,18 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op
49
52
return nil , nil
50
53
}
51
54
52
- if options .LeaderElectionID == "" || options .LeaderElectionNamespace == "" {
53
- return nil , fmt .Errorf ("if leader election is enabled, both LeaderElectionID and LeaderElectionNamespace must be set" )
55
+ // Default the LeaderElectionID
56
+ if options .LeaderElectionID == "" {
57
+ options .LeaderElectionID = "controller-runtime"
58
+ }
59
+
60
+ // Default the namespace (if running in cluster)
61
+ if options .LeaderElectionNamespace == "" {
62
+ var err error
63
+ options .LeaderElectionNamespace , err = getInClusterNamespace ()
64
+ if err != nil {
65
+ return nil , fmt .Errorf ("unable to find leader election namespace: %v" , err )
66
+ }
54
67
}
55
68
56
69
// Leader id, needs to be unique
@@ -76,3 +89,21 @@ func NewResourceLock(config *rest.Config, recorderProvider recorder.Provider, op
76
89
EventRecorder : recorderProvider .GetEventRecorderFor (id ),
77
90
})
78
91
}
92
+
93
+ func getInClusterNamespace () (string , error ) {
94
+ // Check whether the namespace file exists.
95
+ // If not, we are not running in cluster so can't guess the namespace.
96
+ _ , err := os .Stat (inClusterNamespacePath )
97
+ if os .IsNotExist (err ) {
98
+ return "" , fmt .Errorf ("not running in-cluster, please specify LeaderElectionNamespace" )
99
+ } else if err != nil {
100
+ return "" , fmt .Errorf ("error checking namespace file: %v" , err )
101
+ }
102
+
103
+ // Load the namespace file and return itss content
104
+ namespace , err := ioutil .ReadFile (inClusterNamespacePath )
105
+ if err != nil {
106
+ return "" , fmt .Errorf ("error reading namespace file: %v" , err )
107
+ }
108
+ return string (namespace ), nil
109
+ }
0 commit comments