Skip to content

Commit

Permalink
Moved directory walk, compare file code to it's own function
Browse files Browse the repository at this point in the history
  • Loading branch information
mccv1r0 committed Sep 25, 2018
1 parent 7b72f2a commit 9959f78
Showing 1 changed file with 18 additions and 26 deletions.
44 changes: 18 additions & 26 deletions plugins/ipam/host-local/backend/disk/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
)

const lastIPFilePrefix = "last_reserved_ip."
const LineBreak = "\r\n"

var defaultDataDir = "/var/lib/cni/networks"

Expand Down Expand Up @@ -65,7 +66,7 @@ func (s *Store) Reserve(id string, ifname string, ip net.IP, rangeID string) (bo
if err != nil {
return false, err
}
if _, err := f.WriteString(strings.TrimSpace(id) + "\n" + ifname); err != nil {
if _, err := f.WriteString(strings.TrimSpace(id) + LineBreak + ifname); err != nil {
f.Close()
os.Remove(f.Name())
return false, err
Expand Down Expand Up @@ -97,10 +98,7 @@ func (s *Store) Release(ip net.IP) error {
return os.Remove(GetEscapedPath(s.dataDir, ip.String()))
}

// N.B. This function eats errors to be tolerant and
// release as much as possible
func (s *Store) ReleaseByID(id string, ifname string) error {

func (s *Store) ReleaseByKey(id string, ifname string, match string) (bool, error) {
found := false
err := filepath.Walk(s.dataDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
Expand All @@ -110,35 +108,29 @@ func (s *Store) ReleaseByID(id string, ifname string) error {
if err != nil {
return nil
}
if strings.TrimSpace(string(data)) == (strings.TrimSpace(id) + "\n" + ifname) {
if strings.TrimSpace(string(data)) == match {
if err := os.Remove(path); err != nil {
return nil
}
found = true
}
return nil
})
return found, err

if (!found) && (err == nil) {
err = filepath.Walk(s.dataDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil {
return nil
}
isCurrent := strings.Contains(string(data), "\n")

if !isCurrent {
if strings.TrimSpace(string(data)) == (strings.TrimSpace(id)) {
if err := os.Remove(path); err != nil {
return nil
}
}
}
return nil
})
}

// N.B. This function eats errors to be tolerant and
// release as much as possible
func (s *Store) ReleaseByID(id string, ifname string) error {
found := false
match := strings.TrimSpace(id) + LineBreak + ifname
found, err := s.ReleaseByKey(id, ifname, match)

// For backwards compatibility, look for files written by a previous version
if !found && err == nil {
match := strings.TrimSpace(id)
found, err = s.ReleaseByKey(id, ifname, match)
}
return err
}
Expand Down

0 comments on commit 9959f78

Please sign in to comment.