@@ -30,6 +30,7 @@ import (
3030 "context"
3131 "fmt"
3232 "net/http"
33+ "sync/atomic"
3334 "time"
3435
3536 "github.com/AliceO2Group/Control/common/logger"
@@ -38,8 +39,8 @@ import (
3839)
3940
4041var (
41- // scraping endpoint implementation
42- server * http.Server
42+ // atomic holder for the HTTP server instance
43+ server atomic. Pointer [ http.Server ]
4344 // objects to store incoming metrics
4445 metricsInternal * MetricsAggregate
4546 metricsHistogramInternal * MetricsReservoirSampling
@@ -154,33 +155,30 @@ func handleFunc(endpointName string) {
154155//
155156// If we attempt send more messages than the size of the buffer, these overflowing messages will be ignored and warning will be logged.
156157func Run (port uint16 , endpointName string ) error {
157- if IsRunning () {
158+ srv := & http.Server {Addr : fmt .Sprintf (":%d" , port )}
159+ // only one Run should initialize and serve
160+ if ! server .CompareAndSwap (nil , srv ) {
158161 return nil
159162 }
160-
161163 initChannels ()
162-
163164 go eventLoop ()
164-
165- server = & http.Server {Addr : fmt .Sprintf (":%d" , port )}
166165 handleFunc (endpointName )
167- return server .ListenAndServe ()
166+ // block until Shutdown is called
167+ return srv .ListenAndServe ()
168168}
169169
170170func Stop () {
171- if ! IsRunning () {
171+ srv := server .Swap (nil )
172+ if srv == nil {
172173 return
173174 }
174-
175175 ctx , cancel := context .WithTimeout (context .Background (), 5 * time .Second )
176176 defer cancel ()
177- server .Shutdown (ctx )
178-
177+ srv .Shutdown (ctx )
179178 endChannel <- struct {}{}
180179 <- endChannel
181- server = nil
182180}
183181
184182func IsRunning () bool {
185- return server != nil
183+ return server . Load () != nil
186184}
0 commit comments