Skip to content
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

Fixing race condition during restore process #248

Merged
merged 2 commits into from
Jul 25, 2024
Merged
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
28 changes: 28 additions & 0 deletions internal/flypg/restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
const (
pathToHBAFile = "/data/postgresql/pg_hba.conf"
pathToHBABackup = "/data/postgresql/pg_hba.conf.bak"
postmasterPath = "/data/postgresql/postmaster.pid"
restoreLockFile = "/data/restore.lock"
)

Expand Down Expand Up @@ -85,6 +86,12 @@ func prepareRemoteRestore(ctx context.Context, node *Node) error {

svisor.Stop()

// Wait for the postmaster to exit
// TODO - This should be done in the supervisor
if err := waitForPostmasterExit(ctx); err != nil {
return fmt.Errorf("failed to wait for postmaster to exit: %s", err)
}

// Set the lock file so the init process knows not to restart
// the restore process.
if err := setRestoreLock(); err != nil {
Expand All @@ -98,6 +105,27 @@ func prepareRemoteRestore(ctx context.Context, node *Node) error {
return nil
}

func waitForPostmasterExit(ctx context.Context) error {
ticker := time.NewTicker(1 * time.Second)
timeout := time.After(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
switch _, err := os.Stat(postmasterPath); {
case os.IsNotExist(err):
return nil
case err != nil:
return fmt.Errorf("error checking postmaster file: %v", err)
}
case <-timeout:
return fmt.Errorf("timed out waiting for postmaster to exit")
case <-ctx.Done():
return ctx.Err()
}
}
}

func isRestoreActive() (bool, error) {
if _, err := os.Stat(restoreLockFile); err == nil {
val, err := os.ReadFile(restoreLockFile)
Expand Down
Loading