Files
2026-12-01 19:40:55 +01:00

70 lines
2.2 KiB
Go

package dbcopy
import (
"errors"
"fmt"
"os"
)
// ErrSourceInUse is returned when another process has the sqlite file open
var ErrSourceInUse = errors.New(
"another process has the sqlite database open, most likely the server: stop the server first " +
"(for example systemctl stop phishingclub, or docker compose stop) and keep it stopped until the config points at postgres",
)
// sqlite locks bytes of the database file from this offset on (the pending
// byte, the reserved byte and the shared range, 512 bytes in all), and a
// connection in WAL mode holds a shared lock in that range for as long as it
// is open, also when it is idle. The application always opens its database
// in WAL mode, so a running server, even an idle one, holds such a lock.
const (
sqliteLockOffset = 0x40000000
sqliteLockBytes = 512
)
// SourceProbe looks for a lock another process holds on the sqlite file.
// Open it before the source is opened and close it after the source is
// closed: closing a file drops every POSIX lock the process holds on it,
// the locks sqlite holds through its own handle too, so the probe keeps
// its handle open for the whole run.
type SourceProbe struct {
file *os.File
}
// OpenSourceProbe opens the sqlite file at path for the probe. path is the
// absolute path from SourceFile.
func OpenSourceProbe(path string) (*SourceProbe, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrSourceDSN, err)
}
return &SourceProbe{file: f}, nil
}
// Check returns ErrSourceInUse when another process holds a lock on the
// file. Locks of this process are not seen, so the source the copy opened
// itself does not count.
func (p *SourceProbe) Check() error {
if p == nil || p.file == nil {
return nil
}
pid, held, err := otherLock(p.file, sqliteLockOffset, sqliteLockBytes)
if err != nil {
return fmt.Errorf("checking whether the sqlite database is in use: %w", err)
}
if !held {
return nil
}
if pid > 0 {
return fmt.Errorf("%w (process id %d)", ErrSourceInUse, pid)
}
return ErrSourceInUse
}
// Close closes the file of the probe
func (p *SourceProbe) Close() {
if p != nil && p.file != nil {
_ = p.file.Close()
}
}