2021-02-14 09:26:56 -09:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2021-02-14 16:55:56 -09:00
|
|
|
"context"
|
2021-02-14 09:26:56 -09:00
|
|
|
"fmt"
|
|
|
|
"git.binarythought.com/cdramey/alrm/config"
|
2021-02-14 16:55:56 -09:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2021-02-14 09:26:56 -09:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2021-02-14 16:55:56 -09:00
|
|
|
workers []*worker
|
2021-03-01 07:26:27 -09:00
|
|
|
config *config.Config
|
2021-02-14 16:55:56 -09:00
|
|
|
shutdownc chan bool
|
|
|
|
http http.Server
|
2021-02-14 09:26:56 -09:00
|
|
|
}
|
|
|
|
|
2021-02-14 16:55:56 -09:00
|
|
|
func (srv *Server) Start() (bool, error) {
|
2021-03-01 07:26:27 -09:00
|
|
|
listen, err := net.Listen("tcp", srv.config.Listen)
|
2021-02-14 16:55:56 -09:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
2021-02-14 09:26:56 -09:00
|
|
|
for _, w := range srv.workers {
|
2021-02-14 14:22:30 -09:00
|
|
|
go w.start()
|
2021-02-14 09:26:56 -09:00
|
|
|
}
|
|
|
|
|
2021-02-14 16:55:56 -09:00
|
|
|
srv.http = http.Server{Handler: srv}
|
|
|
|
go srv.http.Serve(listen)
|
|
|
|
|
2021-03-01 07:26:27 -09:00
|
|
|
t := time.NewTicker(srv.config.Interval)
|
2021-02-14 09:26:56 -09:00
|
|
|
defer t.Stop()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case r := <-t.C:
|
2021-03-01 07:26:27 -09:00
|
|
|
if srv.config.DebugLevel > 0 {
|
2021-02-14 09:26:56 -09:00
|
|
|
fmt.Printf("interval check at %s\n", r)
|
|
|
|
}
|
|
|
|
for _, w := range srv.workers {
|
2021-02-14 14:22:30 -09:00
|
|
|
w.wake()
|
2021-02-14 09:26:56 -09:00
|
|
|
}
|
2021-02-14 16:55:56 -09:00
|
|
|
case b := <-srv.shutdownc:
|
|
|
|
srv.http.Shutdown(context.Background())
|
|
|
|
for _, w := range srv.workers {
|
|
|
|
w.shutdown()
|
|
|
|
}
|
|
|
|
return b, nil
|
2021-02-14 09:26:56 -09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-28 04:51:35 -09:00
|
|
|
func NewServer(cfg *config.Config) *Server {
|
2021-02-14 16:55:56 -09:00
|
|
|
srv := &Server{
|
2021-03-01 07:26:27 -09:00
|
|
|
config: cfg,
|
2021-02-14 16:55:56 -09:00
|
|
|
shutdownc: make(chan bool, 1),
|
|
|
|
}
|
2021-02-14 09:26:56 -09:00
|
|
|
for _, g := range cfg.Groups {
|
2021-02-14 16:55:56 -09:00
|
|
|
srv.workers = append(
|
2021-02-28 04:51:35 -09:00
|
|
|
srv.workers, makeworker(g, cfg.DebugLevel),
|
2021-02-14 16:55:56 -09:00
|
|
|
)
|
2021-02-14 09:26:56 -09:00
|
|
|
}
|
|
|
|
return srv
|
|
|
|
}
|