overflow_probe_container/server/server_handlers.go
crusader 11ee798e72 ing
2018-03-21 19:51:34 +09:00

74 lines
1.4 KiB
Go

package server
import (
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"git.loafle.net/commons_go/logging"
"git.loafle.net/commons_go/server"
)
func NewServerHandler(pidPath string, serverName string, socketHandler SocketHandler) ServerHandler {
sh := &ServerHandlers{
pidPath: pidPath,
}
sh.Name = serverName
sh.SocketHandler = socketHandler
return sh
}
type ServerHandlers struct {
server.ServerHandlers
pidPath string
port int
}
func (sh *ServerHandlers) Init(serverCTX server.ServerContext) error {
if err := sh.ServerHandlers.Init(serverCTX); nil != err {
return err
}
return nil
}
func (sh *ServerHandlers) Listen(serverCTX server.ServerContext) (net.Listener, error) {
for i := 60000; i < 61000; i++ {
addr := fmt.Sprintf("localhost:%d", i)
l, err := net.Listen("tcp", addr)
if nil == err {
sh.port = i
return l, nil
}
}
return nil, fmt.Errorf("Container: Cannot find availrable port")
}
func (sh *ServerHandlers) OnStart(serverCTX server.ServerContext) {
sh.ServerHandlers.OnStart(serverCTX)
os.Remove(sh.pidPath)
s := strconv.FormatInt(int64(sh.port), 10)
ioutil.WriteFile(sh.pidPath, []byte(s), os.ModePerm)
}
func (sh *ServerHandlers) OnStop(serverCTX server.ServerContext) {
os.Remove(sh.pidPath)
sh.ServerHandlers.OnStop(serverCTX)
}
func (sh *ServerHandlers) Validate() {
sh.ServerHandlers.Validate()
if "" == sh.pidPath {
logging.Logger().Panicf("Server: The path of pid file must be specified")
}
}