server/server.go

137 lines
2.5 KiB
Go
Raw Normal View History

2017-10-26 11:14:00 +00:00
package server
import (
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"git.loafle.net/commons_go/logging"
)
type Server interface {
Start() error
Stop()
Serve() error
}
2017-10-26 12:13:48 +00:00
func NewServer(sh ServerHandler) Server {
s := &server{
serverHandler: sh,
}
return s
}
2017-10-26 11:14:00 +00:00
type server struct {
serverHandler ServerHandler
listener net.Listener
2017-10-26 12:08:50 +00:00
Stats ConnStats
2017-10-26 11:14:00 +00:00
stopChan chan struct{}
stopWg sync.WaitGroup
}
func (s *server) Start() error {
2017-10-26 12:50:28 +00:00
if nil == s.serverHandler {
2017-10-26 11:14:00 +00:00
panic("Server: server handler must be specified.")
}
s.serverHandler.Validate()
if s.stopChan != nil {
panic("Server: server is already running. Stop it before starting it again")
}
s.stopChan = make(chan struct{})
var err error
if s.listener, err = s.serverHandler.Listen(); nil != err {
return err
}
s.stopWg.Add(1)
go runServer(s)
return nil
}
func (s *server) Stop() {
if s.stopChan == nil {
panic("Server: server must be started before stopping it")
}
close(s.stopChan)
s.stopWg.Wait()
s.stopChan = nil
2017-10-27 05:27:36 +00:00
s.serverHandler.OnStopped()
2017-10-26 11:14:00 +00:00
}
func (s *server) Serve() error {
if err := s.Start(); err != nil {
return err
}
s.stopWg.Wait()
return nil
}
func runServer(s *server) {
defer s.stopWg.Done()
var conn io.ReadWriteCloser
var clientAddr string
var err error
var stopping atomic.Value
for {
acceptChan := make(chan struct{})
go func() {
if conn, clientAddr, err = s.serverHandler.accept(s.listener); err != nil {
if stopping.Load() == nil {
logging.Logger.Error(fmt.Sprintf("Server: [%s]. Cannot accept new connection: [%s]", s.serverHandler.GetAddr(), err))
}
}
close(acceptChan)
}()
select {
case <-s.stopChan:
stopping.Store(true)
s.listener.Close()
<-acceptChan
return
case <-acceptChan:
s.Stats.incAcceptCalls()
}
if err != nil {
s.Stats.incAcceptErrors()
select {
case <-s.stopChan:
return
case <-time.After(time.Second):
}
continue
}
s.stopWg.Add(1)
go handleConnection(s, conn, clientAddr)
}
}
func handleConnection(s *server, conn io.ReadWriteCloser, clientAddr string) {
defer s.stopWg.Done()
2017-10-27 05:33:35 +00:00
logging.Logger.Debug(fmt.Sprintf("Server: Client[%s] is connected.", clientAddr))
clientStopChan := make(chan struct{})
go s.serverHandler.Handle(clientAddr, conn, clientStopChan)
2017-10-26 11:14:00 +00:00
select {
case <-s.stopChan:
2017-10-27 05:33:35 +00:00
close(clientStopChan)
2017-10-26 11:14:00 +00:00
conn.Close()
return
2017-10-27 05:33:35 +00:00
case <-clientStopChan:
2017-10-27 03:47:10 +00:00
conn.Close()
2017-10-27 05:33:35 +00:00
logging.Logger.Debug(fmt.Sprintf("Server: Client[%s] is disconnected.", clientAddr))
2017-10-27 03:47:10 +00:00
return
2017-10-26 11:14:00 +00:00
}
}