Skip to content

Commit 6bc84f3

Browse files
committed
Adding mutex during mutation of hosts
1 parent 5613383 commit 6bc84f3

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

cmd/api.go

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"os"
2323
"strconv"
2424
"strings"
25+
"sync"
2526
"time"
2627

2728
"github.com/bisohns/saido/config"
@@ -81,18 +82,31 @@ type Hosts struct {
8182
Config *config.Config
8283
// Connections : hostname mapped to connection instances to reuse
8384
// across metrics
85+
mu sync.Mutex
8486
Drivers map[string]*driver.Driver
8587
Client chan *Client
8688
Start chan bool
8789
}
8890

91+
func (hosts *Hosts) getDriver(address string) *driver.Driver {
92+
hosts.mu.Lock()
93+
defer hosts.mu.Unlock()
94+
return hosts.Drivers[address]
95+
}
96+
97+
func (hosts *Hosts) resetDriver(host config.Host) {
98+
hosts.mu.Lock()
99+
defer hosts.mu.Unlock()
100+
hostDriver := host.Connection.ToDriver()
101+
hosts.Drivers[host.Address] = &hostDriver
102+
}
103+
89104
func (hosts *Hosts) sendMetric(host config.Host, client *Client) {
90-
if hosts.Drivers[host.Address] == nil {
91-
hostDriver := host.Connection.ToDriver()
92-
hosts.Drivers[host.Address] = &hostDriver
105+
if hosts.getDriver(host.Address) == nil {
106+
hosts.resetDriver(host)
93107
}
94108
for _, metric := range config.GetDashboardInfoConfig(hosts.Config).Metrics {
95-
initializedMetric, err := inspector.Init(metric, hosts.Drivers[host.Address])
109+
initializedMetric, err := inspector.Init(metric, hosts.getDriver(host.Address))
96110
data, err := initializedMetric.Execute()
97111
if err == nil {
98112
var unmarsh interface{}
@@ -115,7 +129,7 @@ func (hosts *Hosts) sendMetric(host config.Host, client *Client) {
115129
errorContent = fmt.Sprintf("Command %s not found on driver %s", metric, host.Address)
116130
}
117131
log.Error(errorContent)
118-
hosts.Drivers[host.Address] = nil
132+
hosts.resetDriver(host)
119133
message := &FullMessage{
120134
Message: errorContent,
121135
Error: true,
@@ -166,7 +180,7 @@ func newHosts(cfg *config.Config) *Hosts {
166180
return hosts
167181
}
168182

169-
func SetHostHandler(w http.ResponseWriter, r *http.Request) {
183+
func setHostHandler(w http.ResponseWriter, r *http.Request) {
170184
b, _ := json.Marshal("Hello World")
171185
w.Write(b)
172186
}
@@ -179,7 +193,7 @@ var apiCmd = &cobra.Command{
179193
// server.HandleFunc("/set-hosts", SetHostHandler)
180194
// FIXME: set up cfg using set-hosts endpoint
181195
hosts := newHosts(cfg)
182-
server.HandleFunc("/set-hosts", SetHostHandler)
196+
server.HandleFunc("/set-hosts", setHostHandler)
183197
server.Handle("/metrics", hosts)
184198
log.Info("listening on :", port)
185199
_, err := strconv.Atoi(port)

0 commit comments

Comments
 (0)