Skip to content

Commit

Permalink
aghnet: impl handle set
Browse files Browse the repository at this point in the history
  • Loading branch information
EugeneOne1 committed Aug 23, 2023
1 parent b643793 commit d1f7d73
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions internal/aghnet/hostscontainer.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func NewHostsContainer(

// Load initially.
if err = hc.refresh(); err != nil {
log.Error("%s: refreshing initially: %s", hostsContainerPrefix, err)
return nil, err
}

for _, p := range paths {
Expand Down Expand Up @@ -201,7 +201,7 @@ func (hc *HostsContainer) handleEvents() {
}

if err := hc.refresh(); err != nil {
log.Error("%s: %s", hostsContainerPrefix, err)
log.Error("WARNING %s: %s", hostsContainerPrefix, err)
}
case _, ok = <-hc.done:
// Go on.
Expand Down Expand Up @@ -244,16 +244,31 @@ func (idx *hostsIndex) walk(r io.Reader) (patterns []string, cont bool, err erro
// type check
var _ hostsfile.Set = (*hostsIndex)(nil)

// Add puts the record for the IP address to the rules builder if needed.
// The first host is considered to be the canonical name for the IP address.
// hosts must have at least one name.
// Add implements the [hostsfile.Set] interface for *hostsIndex.
func (idx *hostsIndex) Add(rec *hostsfile.Record) {
idx.addrs[rec.Addr] = append(idx.addrs[rec.Addr], rec)
for _, name := range rec.Names {
idx.names[name] = append(idx.names[name], rec)
}
}

// type check
var _ hostsfile.HandleSet = (*hostsIndex)(nil)

// HandleInvalid implements the [hostsfile.HandleSet] interface for *hostsIndex.
func (idx *hostsIndex) HandleInvalid(src string, _ []byte, err error) {
lineErr := &hostsfile.LineError{}
if !errors.As(err, &lineErr) {
// Must not happen if idx passed to [hostsfile.Parse].
return
} else if errors.Is(lineErr, hostsfile.ErrEmptyLine) {
// Ignore empty lines.
return
}

log.Info("WARNING: %s: parsing line %d of %q: %s", hostsContainerPrefix, lineErr.Line, src, err)
}

// equalRecs is an equality function for [*hostsfile.Record].
func equalRecs(a, b *hostsfile.Record) (ok bool) {
return a.Addr == b.Addr && a.Source == b.Source && slices.Equal(a.Names, b.Names)
Expand Down Expand Up @@ -291,14 +306,9 @@ func (hc *HostsContainer) refresh() (err error) {
}

_, err = aghos.FileWalker(idx.walk).Walk(hc.fsys, hc.patterns...)

if err != nil {
if len(idx.addrs) == 0 {
// Don't wrap the error since it's informative enough as is.
return err
} else {
log.Debug("%s: refreshing: %s", hostsContainerPrefix, err)
}
// Don't wrap the error since it's informative enough as is.
return err
}

// TODO(e.burkov): Serialize updates using time.
Expand Down

0 comments on commit d1f7d73

Please sign in to comment.