blob: 3b208d930222ae3075fa36a9b86ed4fbc938f380 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Jan Schär75ea9f42024-07-29 17:01:41 +02004// Package up is used to run a function for some duration. If a new function is
5// added while a previous run is still ongoing, nothing new will be executed.
6package up
7
8// Taken and modified from CoreDNS, under Apache 2.0.
9
10import (
11 "sync"
12 "time"
13)
14
15// Probe is used to run a single Func until it returns true
16// (indicating a target is healthy).
17// If an Func is already in progress no new one will be added,
18// i.e. there is always a maximum of 1 checks in flight.
19//
20// There is a tradeoff to be made in figuring out quickly that an upstream is
21// healthy and not doing much work (sending queries) to find that out.
22// Having some kind of exp. backoff here won't help much, because you don't
23// want to backoff too much. You then also need random queries to be performed
24// every so often to quickly detect a working upstream. In the end we just send
25// a query every 0.5 second to check the upstream. This hopefully strikes a
26// balance between getting information about the upstream state quickly and not
27// doing too much work. Note that 0.5s is still an eternity in DNS, so we may
28// actually want to shorten it.
29type Probe struct {
30 sync.Mutex
31 inprogress int
32 interval time.Duration
33}
34
35// Func is used to determine if a target is alive.
36// If so this function must return nil.
37type Func func() error
38
39// New returns a pointer to an initialized Probe.
40func New() *Probe { return &Probe{} }
41
42// Do will probe target, if a probe is already in progress this is a noop.
43func (p *Probe) Do(f Func) {
44 p.Lock()
45 if p.inprogress != idle {
46 p.Unlock()
47 return
48 }
49 p.inprogress = active
50 interval := p.interval
51 p.Unlock()
52 // Passed the lock. Now run f for as long it returns false.
53 // If a true is returned we return from the goroutine
54 // and we can accept another Func to run.
55 go func() {
56 i := 1
57 for {
58 if err := f(); err == nil {
59 break
60 }
61 time.Sleep(interval)
62 p.Lock()
63 if p.inprogress == stop {
64 p.Unlock()
65 return
66 }
67 p.Unlock()
68 i++
69 }
70
71 p.Lock()
72 p.inprogress = idle
73 p.Unlock()
74 }()
75}
76
77// Stop stops the probing.
78func (p *Probe) Stop() {
79 p.Lock()
80 p.inprogress = stop
81 p.Unlock()
82}
83
84// Start will initialize the probe manager,
85// after which probes can be initiated with Do.
86func (p *Probe) Start(interval time.Duration) {
87 p.Lock()
88 p.interval = interval
89 p.Unlock()
90}
91
92const (
93 idle = iota
94 active
95 stop
96)