Exemple #1
0
func (self *table) get(key string) (ret []byte, err error) {
	if len(key) > keylen {
		return nil, fmt.Errorf("key (%s) len must <= 64", key)
	}

	defer self.tableStats.Record("get", time.Now())
	hid := makeHash(key)

	if self.caches != nil {
		cidx := self.getCacheNode(hid)
		cache := cidx.Get()
		defer cache.Recycle()

		ret, err = redis.Bytes(cache.Conn.Do("GET", self.name+"_"+key))
		//fmt.Print("GET ", self.name+"_"+key, "\n")
		if err != nil {

			if err != redis.ErrNil {
				logger.Fatal("get error: %s (%s, %v)", err.Error(), key, ret)
			} else {
				err = nil
			}
		}

		if ret != nil {
			return
		}
	}

	if self.dbs != nil {
		didx := self.getDbNode(hid)
		db := didx.Get()
		defer db.Recycle()

		var rows *sql.Rows
		rows, err = db.Query("SELECT body from "+self.name+" where id = CAST(? as BINARY(64)) LIMIT 1;", key)

		if err != nil {
			logger.Fatal("get error: %s (%s, %v)", err.Error(), key, rows)
		}

		defer rows.Close()

		for rows.Next() {
			err = rows.Scan(&ret)
			if err != nil {
				logger.Fatal("get scan error %s (%s)", err.Error(), key)
			}
			return
		}
	}

	return nil, nil
}
Exemple #2
0
func main() {
	logger.Info("start fight server")

	var cfg config.SvrConfig
	if err := config.ReadConfig(*svrConfigFile, &cfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
		return
	}

	fightserver.StartServices(&cfg, fightServerId)

	handler := func(s os.Signal, arg interface{}) {
		logger.Info("handle signal: %v\n", s)
		logger.Info("stop game server")
		os.Exit(0)
	}

	handlerArray := []os.Signal{syscall.SIGINT,
		syscall.SIGILL,
		syscall.SIGFPE,
		syscall.SIGSEGV,
		syscall.SIGTERM,
		syscall.SIGABRT}

	common.WatchSystemSignal(&handlerArray, handler)

	logger.Info("stop fight server")
}
Exemple #3
0
func CreateServices(authcfg config.AuthConfig) *AuthServer {

	//初始化db
	logger.Info("Init DB")
	db.Init()

	//初始化cache
	var cacheCfg config.CacheConfig
	if err := config.ReadConfig("etc/maincache.json", &cacheCfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
	}
	logger.Info("Init Cache %v", cacheCfg)

	pAuthServices = &AuthServer{
		maincache: db.NewCachePool(cacheCfg),
		rpcServer: rpc.NewServer(),
		exit:      make(chan bool),
	}

	pAuthServices.rpcServer.Register(pAuthServices)

	pAuthServices.rpcServer.ListenAndServe(authcfg.AuthHost, nil)

	return pAuthServices
}
Exemple #4
0
func Init() {
	//base
	var dbCfg config.DBConfig
	if err := config.ReadConfig("etc/dbBase.json", &dbCfg); err != nil {
		logger.Fatal("%v", err)
	}

	aHosts := make([]string, 0)
	aHosts = append(aHosts, dbCfg.DBHost)
	pPollBase = rpc.CreateClientPool(aHosts)
	if pPollBase == nil {
		logger.Fatal("create failed")
	}

	logger.Debug("Init DBClient : %v ", dbCfg.DBHost)
}
Exemple #5
0
func (server *Server) register(rcvr interface{}, name string, useName bool, rcvrFns ...interface{}) error {
	server.mu.Lock()
	if server.serviceMap == nil {
		server.serviceMap = make(map[string]*service)
	}

	rcvrValue := reflect.ValueOf(rcvr)
	sname := reflect.Indirect(rcvrValue).Type().Name()
	if useName {
		sname = name
	}
	if sname == "" {
		logger.Fatal("rpc: no service name for type %v", reflect.ValueOf(rcvr).Interface())
	}
	if !isExported(sname) && !useName {
		s := "rpc Register: type " + sname + " is not exported"
		logger.Info(s)
		server.mu.Lock()
		return errors.New(s)
	}

	var s *service
	if value, ok := server.serviceMap[sname]; ok {
		server.mu.Lock()
		s = value
		logger.Warning("rpc: service already defined: %s", sname)
		//return errors.New("rpc: service already defined: " + sname)
	} else {

		s = new(service)
		s.typ = reflect.TypeOf(rcvr)
		s.rcvr = reflect.ValueOf(rcvr)
		s.name = sname
		s.method = make(map[uint32]*methodType)
	}

	// Install the methods
	// logger.Debug("Install the methods begine!")
	s.method = server.suitableMethods(rcvr, s, s.typ, true, rcvrFns...)

	if len(s.method) == 0 {
		str := ""
		// To help the user, see if a pointer receiver would work.
		method := server.suitableMethods(rcvr, s, reflect.PtrTo(s.typ), false)
		if len(method) != 0 {
			str = "rpc.Register: type " + sname + " has no exported methods of suitable type (hint: pass a pointer to value of that type)"
		} else {
			str = "rpc.Register: type " + sname + " has no exported methods of suitable type"
		}
		logger.Info(str)
		server.mu.Unlock()
		return errors.New(str)
	}
	server.serviceMap[s.name] = s
	server.mu.Unlock()
	return nil
}
Exemple #6
0
func StartServices(cfg *config.SvrConfig, id *uint64) *FightServer {
	fightServer = &FightServer{}

	fightServer = &FightServer{
		rpcServer: server.NewServer(),
		battles:   make(map[string]*Battle),
	}
	fightServer.rpcServer.Register(fightServer)

	fightServer.rpcServer.RegCallBackOnConn(
		func(conn server.RpcConn) {
			fightServer.onConn(conn)
		},
	)

	listener, err := net.Listen("tcp", cfg.FsHost[*id])
	if err != nil {
		logger.Fatal("net.Listen: %s", err.Error())
	}

	fightServer.id = *id

	go func() {
		for {
			//For Client/////////////////////////////
			time.Sleep(time.Millisecond * 5)
			conn, err := listener.Accept()
			if err != nil {
				logger.Error("fightserver StartServices %s", err.Error())
				break
			}
			go func() {
				rpcConn := server.NewTCPSocketConn(fightServer.rpcServer, conn, 1000, 0, 1)
				rpcConn.SetResultServer("Connector")

				defer func() {
					if r := recover(); r != nil {
						logger.Error("player rpc runtime error begin:", r)
						debug.PrintStack()
						rpcConn.Close()

						logger.Error("player rpc runtime error end ")
					}
				}()

				fightServer.rpcServer.ServeConn(rpcConn)
			}()
		}
	}()

	return fightServer
}
Exemple #7
0
func (server *Server) ListenAndServe(tcpAddr string, context interface{}) {
	//logger.Debug("ListenAndServe :[%s]", tcpAddr)
	listener, err := net.Listen("tcp", tcpAddr)
	if err != nil {
		logger.Fatal("net.Listen: %s", err.Error())
	}

	go func() {
		for {
			//For Client/////////////////////////////
			//time.Sleep(time.Millisecond * 5)
			conn, err := listener.Accept()
			if err != nil {
				logger.Error("gateserver StartServices %s", err.Error())
				break
			}
			if context != nil {
				go func(context interface{}) {

					for _, v := range server.onConn {
						v(context)
					}

					server.ServeConnWithContext(conn, context)
					conn.Close()

					for _, v := range server.onConn {
						v(context)
					}

				}(context)
			} else {
				go func() {

					for _, v := range server.onConn {
						v(nil)
					}

					server.ServeConn(conn)
					conn.Close()

					for _, v := range server.onConn {
						v(nil)
					}

				}()
			}
		}
		listener.Close()
	}()
}
Exemple #8
0
func (self *table) del(key string) (err error) {
	if len(key) > keylen {
		return fmt.Errorf("key (%s) len must <= 64", key)
	}

	defer self.tableStats.Record("del", time.Now())
	hid := makeHash(key)

	if self.caches != nil {
		cidx := self.getCacheNode(hid)
		cache := cidx.Get()
		defer cache.Recycle()

		_, err = cache.Conn.Do("DEL", self.name+"_"+key)

		if err != nil {
			if err != redis.ErrNil {
				logger.Fatal("del error: %s (%s)", err.Error(), key)
			} else {
				err = nil
			}
		}
	}

	if self.dbs != nil {
		didx := self.getDbNode(hid)
		db := didx.Get()
		defer db.Recycle()

		_, err = db.Query("DELETE from "+self.name+" where id = CAST(? as BINARY(64));", key)

		if err != nil {
			logger.Fatal("delete error: %s (%s)", err.Error(), key)
		}
	}

	return
}
func Register_lua_db_CachePool_newClass(L *lua.LState) int {
	cfg := L.CheckString(2)
	var cacheCfg config.CacheConfig
	if err := config.ReadConfig(cfg, &cacheCfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
	}
	logger.Info("Init Cache %v", cacheCfg)
	cache := db.NewCachePool(cacheCfg)
	ud := L.NewUserData()
	ud.Value = cache
	L.SetMetatable(ud, L.GetTypeMetatable(luaCachePoolTypeName))
	L.Push(ud)
	return 1
}
Exemple #10
0
func main() {
	logger.Info("start db server")

	var dbcfg config.DBConfig
	if err := config.ReadConfig(*dbConfigFile, &dbcfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
		return
	}

	server.CreateServices(dbcfg)

	common.WatchSystemSignal()

	logger.Info("stop db server")
}
Exemple #11
0
func main() {
	logger.Info("start auth server")

	var authcfg config.AuthConfig
	if err := config.ReadConfig(*authConfigFile, &authcfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
		return
	}

	server.CreateServices(authcfg)

	common.WatchSystemSignal()

	logger.Info("stop auth server")
}
Exemple #12
0
func (self *table) write(key string, value []byte) (err error) {
	if len(key) > keylen {
		return fmt.Errorf("key (%s) len must <= 64", key)
	}

	defer self.tableStats.Record("write", time.Now())
	hid := makeHash(key)

	if self.caches != nil {
		cidx := self.getCacheNode(hid)
		cache := cidx.Get()
		defer cache.Recycle()

		_, err = cache.Conn.Do("SET", self.name+"_"+key, value)
		//fmt.Print("SET ", self.name+"_"+key, " : ",value, "\n")

		if err != nil {
			logger.Fatal("write error: %s (%s, %v)", err.Error(), key, value)
		}
	}

	if self.dbs != nil {
		didx := self.getDbNode(hid)
		db := didx.Get()
		defer db.Recycle()

		_, err = db.Exec("INSERT INTO "+self.name+" (id, body) values(?, ?) ON DUPLICATE KEY UPDATE body=?;", key, value, value)
		//_, err = db.Exec("REPLACE INTO "+self.name+" (id, body) values(?, ?);", key, value)

		if err != nil {
			logger.Fatal("write error: %s (%s, %v)", err.Error(), key, value)
		}
	}

	return
}
Exemple #13
0
func (self *table) getCacheNode(key uint32) *db.CachePool {

	var index = 0
	for k, v := range self.cacheNode {
		if key < v {
			index = k
			break
		}
	}

	node, ok := self.caches[self.cacheVirNode[self.cacheNode[index]]]
	if !ok {
		logger.Fatal("getCacheNode error: no find (%d)", key)
	}
	return node
}
Exemple #14
0
func main() {
	logger.Info("start game server")

	var cfg config.SvrConfig
	if err := config.ReadConfig(*svrConfigFile, &cfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
		return
	}

	server.CreateConnectorServerForClient(cfg)

	common.WatchSystemSignal()
	//script.DefaultLuaScript().ExecuteScriptFile("script/runtime/gameserver/main.lua")

	logger.Info("stop game server")
}
Exemple #15
0
func CreateServices(cfg config.DBConfig) *DBServer {

	pDbServices = NewDBServer(cfg)
	go func() {
		tsock, err := net.Listen("tcp", cfg.DBHost)
		if err != nil {
			logger.Fatal("net.Listen: %s", err.Error())
		}
		StartServices(pDbServices, tsock)

		WaitForExit(pDbServices)

		tsock.Close()
	}()

	return pDbServices
}
Exemple #16
0
func (server *Server) ListenAndServe(tcpAddr string, httpAddr string) {
	//logger.Debug("ListenAndServe :[%s] - [%s]", tcpAddr, httpAddr)
	listener, err := net.Listen("tcp", tcpAddr)
	if err != nil {
		logger.Fatal("net.Listen: %s", err.Error())
	}

	go func() {
		for {
			//For Client/////////////////////////////
			time.Sleep(time.Millisecond * 5)
			conn, err := listener.Accept()
			if err != nil {
				logger.Error("gateserver StartServices %s", err.Error())
				break
			}
			go func() {
				rpcConn := NewTCPSocketConn(server, conn, 4, 30, 1)
				defer func() {
					if r := recover(); r != nil {
						logger.Error("player rpc runtime error begin:", r)
						debug.PrintStack()
						rpcConn.Close()

						logger.Error("player rpc runtime error end ")
					}
				}()
				server.ServeConn(rpcConn)
			}()
		}
	}()

	go func() {
		http.HandleFunc("/", server.wsServeConnHandler)
		http.ListenAndServe(httpAddr, nil)
	}()
}
Exemple #17
0
func NewTable(name string, cfg config.TableConfig, server *DBServer) (t *table) {
	var (
		caches       cacheGroup
		cacheNode    []uint32
		dbs          dbGroup
		dbNode       []uint32
		dbVirNode    map[uint32]uint32
		cacheVirNode map[uint32]uint32
	)
	if cfg.CacheProfile != "" {
		var exist bool
		if caches, exist = server.cacheGroups[cfg.CacheProfile]; !exist {
			logger.Fatal("NewTable: table cache profile not found: %s", cfg.CacheProfile)
		}
		cacheNode, _ = server.cacheNodes[cfg.CacheProfile]
		cacheVirNode, _ = server.cacheVirNodes[cfg.CacheProfile]
	}

	if cfg.DBProfile != "" {
		var exist bool
		if dbs, exist = server.dbGroups[cfg.DBProfile]; !exist {
			logger.Fatal("NewTable: table db profile not found: %s", cfg.DBProfile)
		}
		dbNode, _ = server.dbNodes[cfg.DBProfile]
		dbVirNode, _ = server.dbVirNodes[cfg.DBProfile]
		for _, dbpool := range dbs {
			db := dbpool.Get()
			defer db.Recycle()
			/*
				query := fmt.Sprintf(`
						CREATE TABLE IF NOT EXISTS %s (
					    added_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
					    id BINARY(32) NOT NULL,
					    body MEDIUMBLOB,
					    updated TIMESTAMP NOT NULL,
					    UNIQUE KEY (id),
					    KEY (updated)
					) ENGINE=InnoDB;
					`, name)
			*/

			query := fmt.Sprintf(`
					CREATE TABLE IF NOT EXISTS %s (
				    id BINARY(64) NOT NULL PRIMARY KEY,
					auto_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
				    body MEDIUMBLOB,
				    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				    KEY (updated),
					key (auto_id)
				) ENGINE=InnoDB;
				`, name)

			logger.Info("CreateQuery :%s", query)
			rst, err := db.Exec(
				query,
			)

			if err != nil {
				logger.Fatal("NewTable: db %v create table %s faild! %s", dbpool, name, err.Error())
			}

			logger.Info("NewTable: db %v init %s: %v", dbpool, name, rst)

		}
	}

	if caches == nil && dbs == nil {
		logger.Fatal("NewTable: table %s need a save func", name)
	}

	queryStats := stats.NewTimings("")
	qpsRates := stats.NewRates("", queryStats, 20, 10e9)
	return &table{
		name, caches, dbs,
		cfg.DeleteExpiry,
		queryStats,
		qpsRates,
		cacheNode,
		dbNode,
		dbVirNode,
		cacheVirNode,
	}
}
Exemple #18
0
func (self *LuaScript) ExecuteString(codes string) {
	if err := self.state.DoString(codes); err != nil {
		logger.Fatal("script: ExecuteScriptFile %s, Err : %s", codes, err.Error())
	}
}
Exemple #19
0
func (self *LuaScript) ExecuteScriptFile(file string) {
	if err := self.state.DoFile(file); err != nil {
		logger.Fatal("script: ExecuteScriptFile %s, Err : %s", file, err.Error())
	}
}
Exemple #20
0
func CreateConnectorServerForClient(cfg config.SvrConfig) *Connector {

	db.Init()

	var authCfg config.AuthConfig
	if err := config.ReadConfig("etc/authserver.json", &authCfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
	}
	authConn, err := net.Dial("tcp", authCfg.AuthHost)
	if err != nil {
		logger.Fatal("connect logserver failed %s", err.Error())
	}

	var gsCfg config.LoginConfig
	if err = config.ReadConfig("etc/loginserver.json", &gsCfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
	}
	gsConn, err := net.Dial("tcp", gsCfg.LoginHost)
	if err != nil {
		logger.Fatal("%s", err.Error())
	}

	pConnector = &Connector{
		m:           make(map[uint32]serverInfo),
		authserver:  rpc.NewClient(authConn),
		loginserver: rpc.NewClient(gsConn),
		rpcServer:   server.NewServer(),
		players:     make(map[uint64]*Player),
		playersbyid: make(map[string]*Player),
	}

	//初始化cache
	logger.Info("Init Cache %v", authCfg.MainCacheProfile)
	pConnector.maincache = db.NewCachePool(authCfg.MainCacheProfile)

	pConnector.rpcServer.ApplyProtocol(protobuf.CS_Protocol_value)
	pConnector.rpcServer.Register(pConnector)

	pConnector.rpcServer.RegCallBackOnConn(
		func(conn server.RpcConn) {
			pConnector.onConn(conn)
		},
	)

	pConnector.rpcServer.RegCallBackOnDisConn(
		func(conn server.RpcConn) {
			pConnector.onDisConn(conn)
		},
	)

	pConnector.rpcServer.RegCallBackOnCallBefore(
		func(conn server.RpcConn) {
			conn.Lock()
		},
	)

	pConnector.rpcServer.RegCallBackOnCallAfter(
		func(conn server.RpcConn) {
			conn.Unlock()
		},
	)

	//开始对fightserver的RPC服务
	pConnector.FsMgr.Init(pConnector.rpcServer, cfg)

	listener, err := net.Listen("tcp", cfg.TcpHost)
	if err != nil {
		logger.Fatal("net.Listen: %s", err.Error())
	}

	pConnector.id = cfg.ServerID
	pConnector.listenTcpIp = cfg.TcpHost
	pConnector.listenHttpIp = cfg.HttpHost

	pConnector.sendPlayerCountToGateServer()

	go func() {
		for {
			//For Client/////////////////////////////
			time.Sleep(time.Millisecond * 5)
			conn, err := listener.Accept()

			if err != nil {
				logger.Error("cns StartServices %s", err.Error())
				break
			}

			go func() {
				rpcConn := server.NewTCPSocketConn(pConnector.rpcServer, conn, 128, 45, 1)
				defer func() {
					if r := recover(); r != nil {
						logger.Error("player rpc runtime error begin:", r)
						debug.PrintStack()
						rpcConn.Close()

						logger.Error("player rpc runtime error end ")
					}
				}()

				pConnector.rpcServer.ServeConn(rpcConn)
			}()
		}
	}()

	http.HandleFunc("/", wsServeConnHandler)
	http.ListenAndServe(cfg.HttpHost, nil)

	return pConnector
}
Exemple #21
0
func testLogin() {

	var cfg config.LoginConfig
	if err := config.ReadConfig(*gateConfigFile, &cfg); err != nil {
		logger.Fatal("load config failed, error is: %v", err)
		return
	}

	conn, err := net.Dial("tcp", cfg.TcpHostForClient)
	if err != nil {
		logger.Fatal("%s", err.Error())
	}

	rpcConn := server.NewTCPSocketConn(nil, conn, 4, 0, 1)

	login := &protobuf.CL_CheckAccount{}
	login.SetAccount("account")
	login.SetPassword("password")
	rpcConn.Call("LoginServer.CL_CheckAccount", login)

	rst := new(server.RequestWrap)
	err = rpcConn.ReadRequest(&rst.Request)

	// argv guaranteed to be a pointer now.
	argv := reflect.New(reflect.TypeOf(protobuf.LC_CheckAccountResult{}))
	rpcConn.GetRequestBody(&rst.Request, argv.Interface())

	info := argv.Interface().(*protobuf.LC_CheckAccountResult)

	logger.Info("LoginServer Info : %v", argv.Interface())
	logger.Info("                 %v", &rst.Request)
	logger.Info("                 %v", info.GetSessionKey())

	rpcConn.Close()

	time.Sleep(time.Millisecond * 1000)

	conn, err = net.Dial("tcp", info.GetGameServerIp())
	if err != nil {
		logger.Fatal("%s", err.Error())
	}

	rpcConn = server.NewTCPSocketConn(nil, conn, 4, 0, 1)

	check := &protobuf.CS_CheckSession{}
	check.SetUid(info.GetUid())
	check.SetSessionKey(info.GetSessionKey())
	check.SetTimestamp(uint32(time.Now().Unix()))
	rpcConn.Call("GameServer.CS_CheckSession", check)

	rst = new(server.RequestWrap)
	err = rpcConn.ReadRequest(&rst.Request)

	// argv guaranteed to be a pointer now.
	argv = reflect.New(reflect.TypeOf(protobuf.SC_CheckSessionResult{}))
	rpcConn.GetRequestBody(&rst.Request, argv.Interface())
	logger.Info("GameServer.CS_CheckSession : %v", argv.Interface())
	logger.Info("                 %v", &rst.Request)

	for i := 0; i < 100; i++ {
		time.Sleep(time.Millisecond * 1000)
		req := &protobuf.CS_Ping{}
		rpcConn.Call("GameServer.CS_Ping", req)

		rst = new(server.RequestWrap)
		err = rpcConn.ReadRequest(&rst.Request)

		// argv guaranteed to be a pointer now.
		argv = reflect.New(reflect.TypeOf(protobuf.SC_PingResult{}))
		rpcConn.GetRequestBody(&rst.Request, argv.Interface())
		logger.Info("GameServer.CS_Ping : %v", argv.Interface())
		logger.Info("                 %v", &rst.Request)
	}

	rpcConn.Close()
}