Skip to content

Commit d51e95c

Browse files
authored
Merge pull request #1 from fly-apps/only_primary_region_primary
Don't allow members outside primary region to become primary
2 parents da54439 + 7b1694f commit d51e95c

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

cmd/start/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ func main() {
3333
for range t.C {
3434

3535
if err := node.PostInit(); err != nil {
36-
fmt.Printf("failed post-init: %s", err)
36+
fmt.Printf("failed post-init: %s. Retrying...", err)
3737
continue
3838
}
3939

pkg/flypg/node.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ type Node struct {
3131
AppName string
3232
PrivateIP string
3333
DataDir string
34+
Region string
3435
PGPort int
3536

3637
SUCredentials Credentials
@@ -48,6 +49,7 @@ func NewNode() (*Node, error) {
4849
DataDir: "/data/postgresql",
4950
ManagerDatabaseName: "repmgr",
5051
ManagerConfigPath: "/data/repmgr.conf",
52+
Region: os.Getenv("FLY_REGION"),
5153
}
5254

5355
if appName := os.Getenv("FLY_APP_NAME"); appName != "" {
@@ -149,6 +151,13 @@ func (n *Node) Init() error {
149151
return nil
150152
}
151153

154+
func (n *Node) ValidPrimary() bool {
155+
if n.Region == os.Getenv("PRIMARY_REGION") {
156+
return true
157+
}
158+
return false
159+
}
160+
152161
// PostInit are operations that should be executed against a running Postgres on boot.
153162
func (n *Node) PostInit() error {
154163
client, err := state.NewConsulClient()
@@ -163,6 +172,11 @@ func (n *Node) PostInit() error {
163172

164173
switch primaryIP {
165174
case "":
175+
// Check if we can be a primary
176+
if !n.ValidPrimary() {
177+
return fmt.Errorf("no primary to follow and can't configure self as primary because primary region is '%s' and we are in '%s'", n.Region, os.Getenv("PRIMARY_REGION"))
178+
}
179+
166180
// Initialize ourselves as the primary.
167181
conn, err := n.NewLocalConnection(context.TODO())
168182
if err != nil {

pkg/flypg/repmgr.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ func writeManagerConf(node Node) error {
9999
"follow_command": fmt.Sprintf("'repmgr standby follow -f %s --log-to-file --upstream-node-id=%%n'", node.ManagerConfigPath),
100100
"event_notification_command": fmt.Sprintf("'/usr/local/bin/event_handler -node-id %%n -event %%e -success %%s -details \"%%d\"'"),
101101
"event_notifications": "'repmgrd_failover_promote,standby_promote'",
102+
"location": node.Region,
102103
}
103104

104105
for key, value := range conf {

0 commit comments

Comments
 (0)