diff --git a/src/controller/cluster.c b/src/controller/cluster.c index d8667d3..02fd0a1 100644 --- a/src/controller/cluster.c +++ b/src/controller/cluster.c @@ -785,6 +785,7 @@ int cluster_init(cluster_t* c) c->myconf->keyfile); if (ssl_ctx == NULL) { ERROR("create_ssl_context failed"); + cluster_fini(c); return -errno; } c->ha.ssl_ctx = ssl_ctx; @@ -794,11 +795,18 @@ int cluster_init(cluster_t* c) if (c->myconf->cluster_config == NULL) { rc = xce_run_hooks(&(c->hooksys), XCE_CONTROLLER_HOOK_CLUSTER, HOOK_BEFORE_EVENT, HOOK_DETAIL_CLUSTER_INIT, c); - if (rc < 0) + if (rc < 0) { + cluster_fini(c); return rc; + } } - return cluster_init_phase2(c); + rc = cluster_init_phase2(c); + if (rc != 0) { + cluster_fini(c); + return rc; + } + return 0; } static int make_heartbeat(cluster_t* c, endpoint_t* ep) diff --git a/src/controller/myapp.c b/src/controller/myapp.c index 11ff22e..bd64265 100644 --- a/src/controller/myapp.c +++ b/src/controller/myapp.c @@ -6,6 +6,7 @@ #include #include "cluster.h" +#include "ha.h" #include "myconf.h" #include "netio.h" #include "xce/cluster_def.h" @@ -43,8 +44,10 @@ int myapp_run(myconf_t* myconf) } c.ha.ssl_ctx = ssl_ctx; - /* Election: determine role before loading config */ - if (am_i_primary(&c)) { + /* Election: determine role before loading config. + * Capture result once — am_i_primary() probes peers and is expensive. */ + int is_primary = am_i_primary(&c); + if (is_primary) { /* Primary: load config from conf/current (FATAL if missing) */ rc = load_primary_config(&c); if (rc != 0) { @@ -52,6 +55,10 @@ int myapp_run(myconf_t* myconf) myconf_fini(myconf); return rc; } + /* Record election outcome so cluster_init_phase2() sees CTRL_PRIMARY. + * ha_init() unconditionally defaults ha->role to CTRL_STANDBY. */ + atomic_store_explicit(&c.ha.role, (int32_t)CTRL_PRIMARY, + memory_order_release); } else { /* Standby: fetch config from primary before Phase 2 */ rc = fetch_config_from_primary(&c); @@ -60,6 +67,7 @@ int myapp_run(myconf_t* myconf) myconf_fini(myconf); return rc; } + /* Role stays CTRL_STANDBY — already set by ha_init(). */ } /* Phase 2: full init (requires cluster_config) */