1
1
package io .javaoperatorsdk .operator ;
2
2
3
+ import java .util .UUID ;
3
4
import java .util .concurrent .CompletableFuture ;
4
5
5
6
import org .slf4j .Logger ;
15
16
import io .javaoperatorsdk .operator .api .config .ConfigurationServiceProvider ;
16
17
import io .javaoperatorsdk .operator .api .config .LeaderElectionConfiguration ;
17
18
18
- class LeaderElectionManager {
19
+ public class LeaderElectionManager {
19
20
20
21
private static final Logger log = LoggerFactory .getLogger (LeaderElectionManager .class );
21
22
@@ -29,7 +30,7 @@ public LeaderElectionManager(ControllerManager controllerManager) {
29
30
}
30
31
31
32
public void init (LeaderElectionConfiguration config , KubernetesClient client ) {
32
- this .identity = config . getIdentity ( );
33
+ this .identity = identity ( config );
33
34
Lock lock = new LeaseLock (config .getLeaseNamespace (), config .getLeaseName (), identity );
34
35
// releaseOnCancel is not used in the underlying implementation
35
36
leaderElector = new LeaderElectorBuilder (client ,
@@ -45,8 +46,9 @@ public boolean isLeaderElectionEnabled() {
45
46
}
46
47
47
48
private LeaderCallbacks leaderCallbacks () {
48
- return new LeaderCallbacks (this ::startLeading , this ::stopLeading ,
49
- leader -> log .info ("New leader with identity: {}" , leader ));
49
+ return new LeaderCallbacks (this ::startLeading , this ::stopLeading , leader -> {
50
+ log .info ("New leader with identity: {}" , leader );
51
+ });
50
52
}
51
53
52
54
private void startLeading () {
@@ -61,6 +63,14 @@ private void stopLeading() {
61
63
System .exit (1 );
62
64
}
63
65
66
+ private String identity (LeaderElectionConfiguration config ) {
67
+ String id = config .getIdentity ().orElse (System .getenv ("HOSTNAME" ));
68
+ if (id == null || id .isBlank ()) {
69
+ id = UUID .randomUUID ().toString ();
70
+ }
71
+ return id ;
72
+ }
73
+
64
74
public void start () {
65
75
if (isLeaderElectionEnabled ()) {
66
76
leaderElectionFuture = leaderElector .start ();
0 commit comments