83 lines
1.8 KiB
Go
83 lines
1.8 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)
|
|
|
|
if _, err := os.Stat(sh.pidPath); os.IsExist(err) {
|
|
if err := os.Remove(sh.pidPath); nil != err {
|
|
logging.Logger().Errorf("Container: Removing pid file has been failed [%v]", err)
|
|
}
|
|
}
|
|
|
|
s := strconv.FormatInt(int64(sh.port), 10)
|
|
ioutil.WriteFile(sh.pidPath, []byte(s), os.ModePerm)
|
|
}
|
|
|
|
func (sh *ServerHandlers) OnStop(serverCTX server.ServerContext) {
|
|
if _, err := os.Stat(sh.pidPath); os.IsExist(err) {
|
|
if err := os.Remove(sh.pidPath); nil != err {
|
|
logging.Logger().Errorf("Container: Removing pid file has been failed [%v]", err)
|
|
}
|
|
}
|
|
|
|
sh.ServerHandlers.OnStop(serverCTX)
|
|
}
|
|
|
|
func (sh *ServerHandlers) Validate() {
|
|
sh.ServerHandlers.Validate()
|
|
|
|
if "" == sh.pidPath {
|
|
logging.Logger().Panicf("Container: The path of pid file must be specified")
|
|
}
|
|
|
|
}
|