/usr/share/gocode/src/github.com/xiang90/probing/prober.go is in golang-github-xiang90-probing-dev 0.0.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | package probing
import (
"encoding/json"
"errors"
"net/http"
"sync"
"time"
)
var (
ErrNotFound = errors.New("probing: id not found")
ErrExist = errors.New("probing: id exists")
)
type Prober interface {
AddHTTP(id string, probingInterval time.Duration, endpoints []string) error
Remove(id string) error
RemoveAll()
Reset(id string) error
Status(id string) (Status, error)
}
type prober struct {
mu sync.Mutex
targets map[string]*status
tr http.RoundTripper
}
func NewProber(tr http.RoundTripper) Prober {
p := &prober{targets: make(map[string]*status)}
if tr == nil {
p.tr = http.DefaultTransport
} else {
p.tr = tr
}
return p
}
func (p *prober) AddHTTP(id string, probingInterval time.Duration, endpoints []string) error {
p.mu.Lock()
defer p.mu.Unlock()
if _, ok := p.targets[id]; ok {
return ErrExist
}
s := &status{stopC: make(chan struct{})}
p.targets[id] = s
ticker := time.NewTicker(probingInterval)
go func() {
pinned := 0
for {
select {
case <-ticker.C:
start := time.Now()
req, err := http.NewRequest("GET", endpoints[pinned], nil)
if err != nil {
panic(err)
}
resp, err := p.tr.RoundTrip(req)
if err != nil {
s.recordFailure(err)
pinned = (pinned + 1) % len(endpoints)
continue
}
var hh Health
d := json.NewDecoder(resp.Body)
err = d.Decode(&hh)
resp.Body.Close()
if err != nil || !hh.OK {
s.recordFailure(err)
pinned = (pinned + 1) % len(endpoints)
continue
}
s.record(time.Since(start), hh.Now)
case <-s.stopC:
ticker.Stop()
return
}
}
}()
return nil
}
func (p *prober) Remove(id string) error {
p.mu.Lock()
defer p.mu.Unlock()
s, ok := p.targets[id]
if !ok {
return ErrNotFound
}
close(s.stopC)
delete(p.targets, id)
return nil
}
func (p *prober) RemoveAll() {
p.mu.Lock()
defer p.mu.Unlock()
for _, s := range p.targets {
close(s.stopC)
}
p.targets = make(map[string]*status)
}
func (p *prober) Reset(id string) error {
p.mu.Lock()
defer p.mu.Unlock()
s, ok := p.targets[id]
if !ok {
return ErrNotFound
}
s.reset()
return nil
}
func (p *prober) Status(id string) (Status, error) {
p.mu.Lock()
defer p.mu.Unlock()
s, ok := p.targets[id]
if !ok {
return nil, ErrNotFound
}
return s, nil
}
|