Exemple #1
0
func main() {

	if len(os.Args) > 1 {

		// 处理普通参数
		switch os.Args[1] {
		case "--help":
			fmt.Println(helpStr)
			return
		case "--version":
			fmt.Println(versionStr)
			return
		}

		// 处理特殊参数
		cmdHandler := rpclient.NewCmdHandler()
		err := cmdHandler.LinkServer(global.Configure["RpcNetwork"], ":"+global.Configure["RpcPort"])
		if err == nil {
			cmdHandler.Exec(os.Args)
			cmdHandler.Close()
			return
		}

		// 过滤此时无效的命令
		if os.Args[1] != "start" {
			fmt.Println("macheart not start!")
			return
		}

		// 创建守护进程
		if os.Getppid() != 1 {
			err := global.ForkOneself(os.Args)
			if err != nil {
				fmt.Println("macheart starts has failed!")
			} else {
				fmt.Println("macheart has started!")
			}
			return
		}

	}

	// 启动RPC服务
	rpcServer := rpcserver.New(global.Configure["RpcNetwork"], ":"+global.Configure["RpcPort"])
	err := rpcServer.Start()
	if err != nil {
		global.Logger.Fatal("the RPC server starts has failed: %s", err.Error())
		return
	}

	startHeart()
}
Exemple #2
0
func NewCmdHandler() *CmdHandler {
	ch := new(CmdHandler)
	ch.cmds = make(map[string]func(args []string) error)
	// start
	ch.cmds["start"] = func(args []string) error {
		fmt.Println("had an instance running!")
		return nil
	}
	// restart
	ch.cmds["restart"] = func(args []string) error {
		var ok bool
		// 停止
		args[1] = "stop"
		fmt.Println("stopping macheart...")
		err := ch.rpcClient.Call("CmdHandleServer.Exec", &args, &ok) //若停止成功,这里必然会返回错误,但是返回错误不一定表示服务停止成功;这里姑且认为返回错误就表示停止成功
		if err != nil {
			fmt.Println("macheart has stopped!")
		} else {
			fmt.Println("macheart stops has failed!")
			return errors.New(args[1] + ": exec failed!")
		}
		// 启动
		args[1] = "start"
		fmt.Println("starting macheart...")
		err = global.ForkOneself(args)
		if err != nil {
			fmt.Println("macheart starts has failed!")
			return err
		} else {
			fmt.Println("macheart has started!")
		}

		return nil
	}
	// stop
	ch.cmds["stop"] = func(args []string) error {
		var ok bool
		fmt.Println("stopping macheart...")
		err := ch.rpcClient.Call("CmdHandleServer.Exec", &args, &ok)
		if err != nil {
			fmt.Println("macheart has stopped!")
		} else {
			fmt.Println("macheart stops has failed!")
			return errors.New(args[1] + ": exec failed!")
		}
		return nil
	}

	return ch
}