Пример #1
0
// 由入口地址得到所有的controller
func getController(address string) {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		panic(err)
	}

	connection := &utils.Connection{Conn: conn}

	defer func() { conn.Close() }()

	log.Println("Get all controllers request")
	connection.SendCommandString(fmt.Sprintf("%s_join", config.Role), config.ClusterAddress)

	lenght, data, err := connection.Read()
	if err != nil {
		panic(err)
	}

	cmd, payload := utils.CmdDecode(lenght, data)

	log.Printf("Response cmd:%s, payload:%s", cmd, string(payload))

	var controllers map[string]int64
	if err = json.Unmarshal(payload, &controllers); err != nil {
		panic(err)
	}

	for address, _ := range controllers {
		if _, exist := config.Controllers[address]; !exist {
			config.Controllers[address] = time.Now().Unix()
			getController(address)
		}
	}
}
Пример #2
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)
		}
	}
}
Пример #3
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)
}