aboutsummaryrefslogtreecommitdiff
path: root/plugin/pkg
diff options
context:
space:
mode:
authorGravatar Miek Gieben <miek@miek.nl> 2018-04-25 11:45:09 +0100
committerGravatar GitHub <noreply@github.com> 2018-04-25 11:45:09 +0100
commit5e6114b797b56d4b0f910d0c11a5dc85b37bfd52 (patch)
treedd489f9c9918d0dbad6719411d19b133bb5040a6 /plugin/pkg
parentce084012df435a98cac5511a294a0c45a1a3abf9 (diff)
downloadcoredns-5e6114b797b56d4b0f910d0c11a5dc85b37bfd52.tar.gz
coredns-5e6114b797b56d4b0f910d0c11a5dc85b37bfd52.tar.zst
coredns-5e6114b797b56d4b0f910d0c11a5dc85b37bfd52.zip
plugin/pkg/uniq: add (#1733)
Spin this out the metrics package so we can use it in the health one of well to fix some reload bugs.
Diffstat (limited to 'plugin/pkg')
-rw-r--r--plugin/pkg/uniq/uniq.go52
-rw-r--r--plugin/pkg/uniq/uniq_test.go17
2 files changed, 69 insertions, 0 deletions
diff --git a/plugin/pkg/uniq/uniq.go b/plugin/pkg/uniq/uniq.go
new file mode 100644
index 000000000..3e50d64b5
--- /dev/null
+++ b/plugin/pkg/uniq/uniq.go
@@ -0,0 +1,52 @@
+// Package uniq keeps track of "thing" that are either "todo" or "done". Multiple
+// identical events will only be processed once.
+package uniq
+
+// U keeps track of item to be done.
+type U struct {
+ u map[string]item
+}
+
+type item struct {
+ state int // either todo or done
+ f func() error // function to be executed.
+}
+
+// New returns a new initialized U.
+func New() U { return U{u: make(map[string]item)} }
+
+// Set sets function f in U under key. If the key already exists
+// it is not overwritten.
+func (u U) Set(key string, f func() error) {
+ if _, ok := u.u[key]; ok {
+ return
+ }
+ u.u[key] = item{todo, f}
+}
+
+// SetTodo sets key to 'todo' again.
+func (u U) SetTodo(key string) {
+ v, ok := u.u[key]
+ if !ok {
+ return
+ }
+ v.state = todo
+ u.u[key] = v
+}
+
+// ForEach iterates for u executes f for each element that is 'todo' and sets it to 'done'.
+func (u U) ForEach() error {
+ for k, v := range u.u {
+ if v.state == todo {
+ v.f()
+ }
+ v.state = done
+ u.u[k] = v
+ }
+ return nil
+}
+
+const (
+ todo = 1
+ done = 2
+)
diff --git a/plugin/pkg/uniq/uniq_test.go b/plugin/pkg/uniq/uniq_test.go
new file mode 100644
index 000000000..5d58c924b
--- /dev/null
+++ b/plugin/pkg/uniq/uniq_test.go
@@ -0,0 +1,17 @@
+package uniq
+
+import "testing"
+
+func TestForEach(t *testing.T) {
+ u, i := New(), 0
+ u.Set("test", func() error { i++; return nil })
+
+ u.ForEach()
+ if i != 1 {
+ t.Errorf("Failed to executed f for %s", "test")
+ }
+ u.ForEach()
+ if i != 1 {
+ t.Errorf("Executed f twice instead of once")
+ }
+}