Skip to content

Commit

Permalink
ndb: add read lock to prevent NDB blob magic error (#48)
Browse files Browse the repository at this point in the history
This error can happen if the ndb packages file is being updated
(e.g. zypper up) while we are reading it. The rpm binary uses a
shared flock when running `rpm -qa` on the ndb backend. This
commit does the same for go-rpmdb.
  • Loading branch information
djoreilly authored Nov 20, 2023
1 parent 1399746 commit 4c52bf7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pkg/ndb/ndb.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ func Open(path string) (*RpmNDB, error) {
return nil, err
}

err = syscallFlock(int(file.Fd()), syscallLOCK_SH)
if err != nil {
return nil, err
}

hdrBuff := ndbHeader{}
err = binary.Read(file, binary.LittleEndian, &hdrBuff)
if err != nil {
Expand Down Expand Up @@ -127,6 +132,7 @@ func Open(path string) (*RpmNDB, error) {
}

func (db *RpmNDB) Close() error {
_ = syscallFlock(int(db.file.Fd()), syscallLOCK_UN)
return db.file.Close()
}

Expand Down
16 changes: 16 additions & 0 deletions pkg/ndb/syscall_generic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//go:build linux || darwin

package ndb

import (
"syscall"
)

const (
syscallLOCK_SH = syscall.LOCK_SH
syscallLOCK_UN = syscall.LOCK_UN
)

func syscallFlock(fd int, how int) error {
return syscall.Flock(fd, how)
}
12 changes: 12 additions & 0 deletions pkg/ndb/syscall_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//go:build windows

package ndb

const (
syscallLOCK_SH = 0
syscallLOCK_UN = 0
)

func syscallFlock(fd int, how int) error {
return nil
}

0 comments on commit 4c52bf7

Please sign in to comment.