diff --git a/console/command.go b/console/command.go new file mode 100644 index 0000000..eec9794 --- /dev/null +++ b/console/command.go @@ -0,0 +1,54 @@ +package console + +import ( + "fmt" + "strconv" + "strings" +) + +var mapRegisterCmd map[string]func(param interface{}) = map[string]func(param interface{}){} +var programName string + +func Run(args []string) error { + programName = args[0] + if len(args) <= 1 { + return fmt.Errorf("command not found, try `%s help` for help",args[0]) + } + + fn,ok := mapRegisterCmd[args[1]] + if ok == false{ + return fmt.Errorf("command not found, try `%s help` for help",args[0]) + } + + switch args[1] { + case "start": + if len(args)<2 { + return fmt.Errorf("command not found, try `%s help` for help",args[0]) + }else{ + return start(fn,args[2]) + } + } + + return fmt.Errorf("command not found, try `%s help` for help",args[0]) +} + +func start(fn func(param interface{}),param string) error { + sparam := strings.Split(param,"=") + if len(sparam) != 2 { + return fmt.Errorf("invalid option %s",param) + } + if sparam[0]!="nodeid" { + return fmt.Errorf("invalid option %s",param) + } + nodeId,err:= strconv.Atoi(sparam[1]) + if err != nil { + return fmt.Errorf("invalid option %s",param) + } + + fn(nodeId) + return nil +} + +func RegisterCommand(cmd string,fn func(param interface{})){ + mapRegisterCmd[cmd] = fn +} diff --git a/example/main.go b/example/main.go index 630a610..4637631 100644 --- a/example/main.go +++ b/example/main.go @@ -193,8 +193,6 @@ func main(){ gateService := &GateService.GateService{} tcpService.SetEventReciver(gateService) node.Setup(tcpService,gateService) - node.Init() - node.Start() } diff --git a/node/node.go b/node/node.go index 5ffd14e..6e8dfda 100644 --- a/node/node.go +++ b/node/node.go @@ -3,6 +3,7 @@ package node import ( "fmt" "github.com/duanhf2012/origin/cluster" + "github.com/duanhf2012/origin/console" "github.com/duanhf2012/origin/service" "io/ioutil" "os" @@ -14,7 +15,7 @@ import ( var closeSig chan bool var sigs chan os.Signal - +var nodeId int var preSetupService []service.IService //预安装 func init() { @@ -56,10 +57,11 @@ func writeProcessPid() { } func GetNodeId() int { - return 1 + return nodeId } -func Init(){ +func initNode(id int){ + nodeId = id //1.初始化集群 err := cluster.GetCluster().Init(GetNodeId()) if err != nil { @@ -82,6 +84,22 @@ func Init(){ } func Start() { + console.RegisterCommand("start",startNode) + console.RegisterCommand("stop",stopNode) + err := console.Run(os.Args) + if err!=nil { + fmt.Printf("%+v\n",err) + return + } +} + + +func stopNode(processid interface{}){ + +} + +func startNode(paramNodeId interface{}) { + initNode(paramNodeId.(int)) cluster.GetCluster().Start() service.Start() writeProcessPid()