overflow_probe_container/server/server_handlers.go

91 lines
2.0 KiB
Go
Raw Normal View History

2017-12-05 05:20:42 +00:00
package server
import (
"fmt"
2017-12-14 08:24:03 +00:00
"io/ioutil"
"net"
"os"
2018-03-22 12:38:00 +00:00
"path/filepath"
2017-12-14 08:24:03 +00:00
"strconv"
2017-12-05 05:20:42 +00:00
"git.loafle.net/commons_go/logging"
"git.loafle.net/commons_go/server"
)
2017-12-14 08:24:03 +00:00
func NewServerHandler(pidPath string, serverName string, socketHandler SocketHandler) ServerHandler {
2018-03-22 12:38:00 +00:00
pidPathABS, err := filepath.Abs(pidPath)
if nil != err {
logging.Logger().Panicf("Container: pid file path[%s] is not valid %v", pidPath, err)
}
2017-12-05 05:20:42 +00:00
sh := &ServerHandlers{
2018-03-22 12:38:00 +00:00
pidPath: pidPath,
pidPathABS: pidPathABS,
2017-12-05 05:20:42 +00:00
}
2017-12-05 05:27:56 +00:00
sh.Name = serverName
2017-12-05 05:20:42 +00:00
sh.SocketHandler = socketHandler
return sh
}
type ServerHandlers struct {
server.ServerHandlers
2018-03-22 12:38:00 +00:00
pidPath string
pidPathABS string
port int
2017-12-05 05:20:42 +00:00
}
func (sh *ServerHandlers) Init(serverCTX server.ServerContext) error {
if err := sh.ServerHandlers.Init(serverCTX); nil != err {
return err
}
return nil
}
2017-12-14 08:24:03 +00:00
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")
}
2017-12-05 05:20:42 +00:00
func (sh *ServerHandlers) OnStart(serverCTX server.ServerContext) {
sh.ServerHandlers.OnStart(serverCTX)
2018-03-22 12:38:00 +00:00
if _, err := os.Stat(sh.pidPathABS); os.IsExist(err) {
if err := os.Remove(sh.pidPathABS); nil != err {
2018-03-22 12:31:47 +00:00
logging.Logger().Errorf("Container: Removing pid file has been failed [%v]", err)
}
2018-03-22 12:12:17 +00:00
}
2017-12-14 08:24:03 +00:00
s := strconv.FormatInt(int64(sh.port), 10)
2018-03-22 12:38:00 +00:00
ioutil.WriteFile(sh.pidPathABS, []byte(s), os.ModePerm)
2017-12-05 05:20:42 +00:00
}
func (sh *ServerHandlers) OnStop(serverCTX server.ServerContext) {
2018-03-22 12:38:00 +00:00
if _, err := os.Stat(sh.pidPathABS); os.IsExist(err) {
if err := os.Remove(sh.pidPathABS); nil != err {
2018-03-22 12:31:47 +00:00
logging.Logger().Errorf("Container: Removing pid file has been failed [%v]", err)
}
2018-03-22 12:12:17 +00:00
}
2017-12-05 05:20:42 +00:00
sh.ServerHandlers.OnStop(serverCTX)
}
func (sh *ServerHandlers) Validate() {
sh.ServerHandlers.Validate()
2017-12-14 08:24:03 +00:00
if "" == sh.pidPath {
2018-03-22 12:12:17 +00:00
logging.Logger().Panicf("Container: The path of pid file must be specified")
2017-12-05 05:20:42 +00:00
}
}