예제 #1
0
// 从连接中读取数据,解析并调用相应handler响应
func serve(conn net.Conn) {
	var (
		n          int
		ok         bool
		err        error
		cmd        string
		data       []byte
		payload    []byte
		handler    HandlerFunc
		connection *utils.Connection
	)

	connection = &utils.Connection{Conn: conn}
	ClusterSwitcher.register <- connection

	defer func() {
		ClusterSwitcher.unregister <- connection
		conn.Close()
	}()

	for {
		if n, data, err = connection.Read(); err != nil {
			break
		}
		cmd, payload = utils.CmdDecode(n, data)

		log.Printf("Controller receive cmd:%s", cmd)

		if handler, ok = ClusterSwitcher.handlers[cmd]; ok {
			handler(connection, payload)
		} else {
			log.Printf("Command[%s] does not exist", cmd)
		}
	}
}
예제 #2
0
// docker连接到controller,保持着
func connectController(address string) {

	var (
		length     int
		exist      bool
		err        error
		cmd        string
		data       []byte
		payload    []byte
		conn       net.Conn
		handler    HandlerFunc
		connection *utils.Connection
	)

	defer func() { connCloseCh <- address }()

	log.Printf("Connect controller %s", address)

	conn, err = net.Dial("tcp", address)
	if err != nil {
		log.Println(err)
		waitGroup.Done()
		return
	}

	connection = &utils.Connection{
		Conn: conn,
		Src:  address,
	}
	ClusterSwitcher.register <- connection

	defer func() {
		conn.Close()
		ClusterSwitcher.unregister <- connection
	}()

	waitGroup.Done()
	connection.SendCommandString("docker_greetings", config.ClusterAddress)

	for {
		if length, data, err = connection.Read(); err != nil {
			break
		}
		cmd, payload = utils.CmdDecode(length, data)

		log.Printf("Cmd:%s", cmd)

		if handler, exist = ClusterSwitcher.handlers[cmd]; exist {
			handler(connection, payload)
		} else {
			log.Printf("Command[%s] is not exist", cmd)
		}
	}
	log.Printf("Controller %s is disconnect", address)
}