Example #1
0
func StartAppBlance(m *Master) {
	for k, v := range m.AppArgs {
		json, err := simplejson.NewJson(v)
		if err != nil {
			log.LogFatalf(err)
		}
		idx := 0

		for {
			app := json.GetIndex(idx)
			if app.Interface() == nil {
				break
			}

			appargs, _ := app.MarshalJSON()
			appid, err := app.Get("id").String()
			if err != nil {
				log.LogFatalf("app id not set")
				return
			}

			context.CreateApp("", appid, GetAppUid(), k, string(appargs), 0)

			idx++
		}
	}
}
Example #2
0
func StartApp(m *Master) {

	for k, v := range m.AppArgs {
		json, err := simplejson.NewJson(v)
		if err != nil {
			log.LogFatalf(err)
		}
		idx := 0

		startapp, ok := m.AppDef.Apps[k]
		if !ok {
			log.LogFatalf(errors.New("app not found"))
		}
		for {
			app := json.GetIndex(idx)
			if app.Interface() == nil {
				break
			}

			appargs, _ := app.MarshalJSON()
			name, err := app.Get("name").String()
			if err != nil {
				log.LogFatalf("app name not set")
				return
			}

			Start(startapp, name, GetAppUid(), k, string(appargs))
			idx++
		}
	}
}
Example #3
0
File: rpc.go Project: mysll/flynet
func RegisterRemote(name string, remote interface{}) {
	if remote == nil {
		log.LogFatalf("rpc: Register remote is nil")
	}
	if _, dup := remotes[name]; dup {
		log.LogFatalf("rpc: Register called twice for remote " + name)
	}
	remotes[name] = remote
}
Example #4
0
File: rpc.go Project: mysll/flynet
func RegisterHandler(name string, handler interface{}) {
	if handler == nil {
		log.LogFatalf("rpc: Register handler is nil")
	}
	if _, dup := handlers[name]; dup {
		log.LogFatalf("rpc: Register called twice for handler " + name)
	}
	handlers[name] = handler
}
Example #5
0
func (mp *master_peer) Handle(id uint16, msgbody []byte) error {
	switch id {
	case share.M_ADD_SERVER:
		var as share.AddApp
		if err := share.DecodeMsg(msgbody, &as); err != nil {
			return err
		}
		AddApp(as.Type, as.Id, as.Name, as.Host, as.Port, as.ClientHost, as.ClientPort, as.Ready, as.EnableGlobalData)
	case share.M_REMOVE_SERVER:
		var rs share.RemoveApp
		if err := share.DecodeMsg(msgbody, &rs); err != nil {
			return err
		}
		RemoveAppById(rs.Id)
	case share.M_SERVER_LIST:
		var sl share.AppInfo
		if err := share.DecodeMsg(msgbody, &sl); err != nil {
			return err
		}
		for _, a := range sl.Apps {
			AddApp(a.Type, a.Id, a.Name, a.Host, a.Port, a.ClientHost, a.ClientPort, a.Ready, a.EnableGlobalData)
		}
	case share.M_HEARTBEAT:
		data, err := util.CreateMsg(nil, []byte{}, share.M_HEARTBEAT)
		if err != nil {
			log.LogFatalf(err)
		}
		core.noder.Send(data)
	case share.M_READY:
		var ready share.AppReady
		if err := share.DecodeMsg(msgbody, &ready); err != nil {
			return err
		}
		app := GetAppById(ready.Id)
		if app != nil {
			app.SetReady(true)
		} else {
			log.LogFatalf("app not found")
		}
	case share.M_MUSTAPPREADY:
		{
			log.LogMessage("must app ready")
			core.MustReady()
		}
	case share.M_SHUTDOWN:
		core.Closing = true
		close(core.exitChannel)
		return nil
	}

	core.Emitter.Push(MASERTINMSG, map[string]interface{}{"msg": MasterMsg{id, msgbody}}, false)
	return nil

}
Example #6
0
func Start(startapp string, name string, appuid int32, typ string, startargs string) error {
	ferr, err := os.Create(fmt.Sprintf("log/%s_err.log", name))
	if err != nil {
		log.LogError(err)
		return err
	}
	fout, err := os.Create(fmt.Sprintf("log/%s_trace.log", name))
	if err != nil {
		log.LogError(err)
		return err
	}

	cmd := exec.Command(startapp, "-m", fmt.Sprintf("%s:%d", context.Host, context.Port), "-l", context.LocalIP, "-o", context.OuterIP, "-d", strconv.Itoa(int(appuid)), "-t", typ, "-s", startargs)
	cmd.Stdout = fout
	cmd.Stderr = ferr

	err = cmd.Start()
	if err != nil {
		log.LogFatalf(err)
		return err
	}

	log.TraceInfo("master", "app start ", typ, ",", strconv.Itoa(int(appuid)))

	atomic.AddInt32(&Load, 1)
	context.waitGroup.Wrap(func() {
		cmd.Wait()
		ferr.Close()
		fout.Close()
		log.LogMessage(name, " is quit")
		atomic.AddInt32(&Load, -1)
	})
	return nil
}
Example #7
0
func (m *Master) Start() {
	context = m

	if !m.Agent {
		log.TraceInfo("master", "start")
		tcpListener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", m.Host, m.Port))
		if err != nil {
			log.LogError(err)
			log.LogFatalf(err)
		}
		m.tcpListener = tcpListener

		tcpserver := &tcp_server{}
		m.waitGroup.Wrap(func() { util.TCPServer(m.tcpListener, tcpserver) })
	}

	if !m.Agent && m.ConsolePort != 0 {
		StartConsoleServer(m)
		log.LogMessage("console start at:", m.ConsolePort)
	}

	if m.Agent {
		log.TraceInfo("master agent", "start")
		m.agent = &Agent{}
		m.agent.Connect(m.Host, m.Port, true, m.ConnectToMaster)
	} else {
		m.agentlist = NewAgentList()
		m.waitfor = true
		if m.WaitAgents == 0 {
			m.waitfor = false
			StartApp(m)
		}
	}
}
Example #8
0
File: area.go Project: mysll/flynet
func (a *AreaBridge) AddPlayerBak(mailbox rpc.Mailbox, msg *rpc.Message) (errcode int32, reply *rpc.Message) {
	r := server.NewMessageReader(msg)
	res, err := r.ReadString()
	if server.Check(err) {
		return 0, nil
	}
	if res == "ok" {
		player := App.Players.GetPlayer(mailbox.Id)
		if player == nil {
			log.LogFatalf("can not be nil")
			return 0, nil
		}

		if player.State != STATE_ENTERAREA { //可能客户端已经断开了,则让玩家下线
			player.Leave()
			return 0, nil
		}

		player.EnterScene()
		return 0, nil
	} else {
		err := &s2c.Error{}
		err.ErrorNo = proto.Int32(share.ERROR_ROLE_ENTERAREA_ERROR)
		server.Check(server.MailTo(nil, &mailbox, "error", err))
		return 0, nil
	}

}
Example #9
0
File: app.go Project: mysll/flynet
func (app *app) Check() {
	app.lastcheck = time.Now()
	heartbeat := time.NewTicker(5 * time.Second)
	updatelist := time.NewTicker(time.Minute) //每分钟同步一下app列表
	for !app.Shutdown {
		select {
		case <-heartbeat.C: //send heartbeat pkg
			if time.Now().Sub(app.lastcheck).Seconds() > TIMEOUTSECS {
				app.conn.Close()
				return
			}
			data, err := util.CreateMsg(nil, []byte{}, share.M_HEARTBEAT)
			if err != nil {
				log.LogFatalf(err)
			}
			app.conn.Write(data)
		case <-updatelist.C:
			app.SendList()
		case <-app.exit:
			return
		}
	}
	heartbeat.Stop()
	updatelist.Stop()
}
Example #10
0
func (this *Config) load() {
	ids := helper.GetConfigIds("conf_configuration.csv")

	if len(ids) == 0 {
		log.LogWarning("conf_configuration.csv file load failed")
		return
	}

	this.configMap = make(map[string]*KeyVal, len(ids))

	for _, id := range ids {
		conf := &KeyVal{}

		if err := helper.LoadStructByFile("conf_configuration.csv", id, conf); err != nil {
			log.LogFatalf(err)
			continue
		}

		this.configMap[conf.UniqueName] = conf
	}

	log.LogMessage("conf_configuration.csv file load ok")

	ids = helper.GetConfigIds("conf_bp_ratio.csv")

	if len(ids) == 0 {
		log.LogWarning("conf_bp_ratio.csv file load failed")
		return
	}

	for _, id := range ids {
		conf := &KeyVal{}
		tmp := &PropRatio{}
		if err := helper.LoadStructByFile("conf_bp_ratio.csv", id, tmp); err != nil {
			log.LogFatalf(err)
			continue
		}

		conf.UniqueName = "bp_" + tmp.ID
		conf.Value = tmp.BTRatio
		this.configMap[conf.UniqueName] = conf
	}

	log.LogMessage("conf_bp_ratio.csv file load ok")

}
Example #11
0
func Ready(app *app) {
	applock.Lock()
	defer applock.Unlock()

	out, err := share.CreateReadyMsg(app.id)
	if err != nil {
		log.LogFatalf(err)
	}

	ismustapp := false
	for _, v := range context.AppDef.MustApps {
		if app.typ == v {
			mustapps[app.typ] = app.name
			ismustapp = true

			if len(mustapps) == len(context.AppDef.MustApps) {
				log.LogMessage("must app ready")
			}
			break
		}
	}

	var out1 []byte
	if len(mustapps) == len(context.AppDef.MustApps) {
		out1, err = share.CreateMustAppReadyMsg()
		if err != nil {
			log.LogFatalf(err)
		}
	}

	for _, v := range context.app {
		if v.id != app.id {
			v.conn.Write(out)
		}
		if len(out1) > 0 { //mustapp 已经都启动了
			if ismustapp { //当前是mustapp的ready,则给所有的app发送mustappready消息。
				v.conn.Write(out1)
			} else if v.id == app.id { //当前是其它应用的ready,而且mustapp都启动了,则只需要给当前的app发送mustappready就可以了
				v.conn.Write(out1)
			}

		}
	}

}
Example #12
0
File: area.go Project: mysll/flynet
func (a *AreaBridge) RemovePlayerBak(mailbox rpc.Mailbox, msg *rpc.Message) (errcode int32, reply *rpc.Message) {
	player := App.Players.GetPlayer(mailbox.Id)
	if player == nil {
		log.LogFatalf("can not be nil", mailbox)
		return 0, nil
	}
	player.LeaveArea()
	return 0, nil
}
Example #13
0
func parseInclude(obj *Object) {
	if obj.Include != "" {
		if obj.Include == obj.Name {
			log.LogFatalf(obj.Name, " include self")
		}

		parent := Defs[obj.Include]
		if parent == nil {
			log.LogFatalf(obj.Name, " include ", obj.Include, " not found")
		}

		if !parent.flag {
			parseInclude(parent)
		}

		obj.Propertys = append(parent.Propertys, obj.Propertys...)
		obj.Records = append(parent.Records, obj.Records...)
	}
	obj.flag = true
}
Example #14
0
func (a *Agent) Register(agentid string, nobalance bool) error {
	out, err := share.CreateRegisterAgent(agentid, nobalance)
	if err != nil {
		log.LogFatalf(err)
	}

	if _, err := a.rwc.Write(out); err != nil {
		return err
	}

	return nil
}
Example #15
0
File: peer.go Project: mysll/flynet
func (p *peer) Ready() error {
	out, err := util.CreateMsg(nil, []byte{}, share.M_READY)
	if err != nil {
		log.LogFatalf(err)
	}

	if _, err := p.rwc.Write(out); err != nil {
		return err
	}

	return nil
}
Example #16
0
func (m *Master) CreateApp(reqid string, appid string, appuid int32, typ string, startargs string, callbackapp int32) {
	if appuid == 0 {
		appuid = GetAppUid()
	}

	if m.agentlist != nil {
		agent := m.agentlist.GetMinLoadAgent()
		if agent != nil {
			if agent.load < Load {
				//远程创建
				err := agent.CreateApp(reqid, appid, appuid, typ, startargs, callbackapp)
				if err != nil && callbackapp != 0 {
					data, err := share.CreateAppBakMsg(reqid, appuid, err.Error())
					if err != nil {
						log.LogFatalf(err)
					}

					m.SendToApp(callbackapp, data)
				}
				return
			}
		}
	}

	//本地创建
	err := CreateApp(appid, appuid, typ, startargs)
	res := "ok"
	if err != nil {
		res = err.Error()
	}

	if callbackapp != 0 {
		data, err := share.CreateAppBakMsg(reqid, appuid, res)
		if err != nil {
			log.LogFatalf(err)
		}

		m.SendToApp(callbackapp, data)
	}
}
Example #17
0
func (tcp *tcp_server) Handle(clientconn net.Conn) {

	buff := make([]byte, 2048)
	id, msgbody, err := util.ReadPkg(clientconn, buff)
	if err != nil {
		log.LogError(err)
		clientconn.Close()
		return
	}

	switch id {
	case share.M_REGISTER_APP:
		var reg share.RegisterApp
		if err := share.DecodeMsg(msgbody, &reg); err != nil {
			clientconn.Close()
			log.LogFatalf(err)
		}
		app := &app{typ: reg.Type, id: reg.Id, name: reg.Name, conn: clientconn, host: reg.Host, port: reg.Port, clienthost: reg.ClientHost, clientport: reg.ClientPort, enableglobaldata: reg.EnableGlobalData}
		log.LogMessage(app.id, ":", app.conn.RemoteAddr().String())
		app.SendList()
		AddApp(app)
		app.Loop()
	case share.M_REGISTER_AGENT:
		var reg share.RegisterAgent
		if err := share.DecodeMsg(msgbody, &reg); err != nil {
			clientconn.Close()
			log.LogFatalf(err)
		}

		agent := &AgentNode{id: reg.AgentId, nobalance: reg.NoBalance}
		agent.Handle(clientconn)
		context.agentlist.AddAgent(agent)
		log.LogMessage("agent add:", reg.AgentId)
	default:
		log.LogError("first message must reg app")
		return
	}

}
Example #18
0
File: peer.go Project: mysll/flynet
func (p *peer) Reg(server *Server) error {

	out, err := share.CreateRegisterAppMsg(server.Type, server.AppId, server.Name, server.Host, server.Port, server.ClientHost, server.ClientPort, server.enableglobaldata)
	if err != nil {
		log.LogFatalf(err)
	}

	if _, err := p.rwc.Write(out); err != nil {
		return err
	}

	return nil
}
Example #19
0
File: rpc.go Project: mysll/flynet
func createRpc(ch chan *rpc.RpcCall) *rpc.Server {
	rpc, err := rpc.CreateRpcService(remotes, handlers, ch)
	if err != nil {
		log.LogFatalf(err)
	}
	id := 0
	var collection RpcCollection
	for service, _ := range handlers {
		if service != "C2SHelper" {
			id++
			sid := id * 100
			info := rpc.GetRpcInfo("C2S" + service)
			for _, m := range info {
				sid++
				rinfo := RpcInfo{service, m, int16(sid)}
				collection.Infos = append(collection.Infos, rinfo)
			}
		}
	}
	if len(collection.Infos) > 0 {
		t, err := template.New("maker").Parse(tpl)
		if err != nil {
			log.LogError(err.Error())
		}

		if err != nil {
			log.LogError("template", err)
		}

		//save file
		file, err := os.Create("interface/" + core.Name + "_rpc.xml")
		if err != nil {
			log.LogError("writer", err)
			return rpc
		}
		defer file.Close()

		writer := bufio.NewWriter(file)

		err = t.Execute(writer, collection)
		if err != nil {
			log.LogError("writer", err)
		}

		writer.Flush()
	}
	return rpc
}
Example #20
0
File: app.go Project: mysll/flynet
func (app *app) Close() {
	if !app.Shutdown {
		data, err := util.CreateMsg(nil, []byte{}, share.M_SHUTDOWN)
		if err != nil {
			log.LogFatalf(err)
		}

		_, err = app.conn.Write(data)
		if err != nil {
			log.LogInfo(app.id, " closed")
		} else {
			log.LogInfo(app.id, " send shutdown")
		}
		app.Shutdown = true
	}

}
Example #21
0
func AddApp(app *app) {
	if _, ok := context.app[app.id]; ok {
		RemoveApp(app.id)
	}

	applock.Lock()
	defer applock.Unlock()

	out, err := share.CreateAddServerMsg(app.typ, app.id, app.name, app.host, app.port, app.clienthost, app.clientport, app.ready, app.enableglobaldata)
	if err != nil {
		log.LogFatalf(err)
	}
	for _, v := range context.app {
		v.conn.Write(out)
	}

	context.app[app.id] = app
}
Example #22
0
func (al *AgentList) CloseAll() {
	al.Lock()
	defer al.Unlock()

	data, err := util.CreateMsg(nil, []byte{}, share.M_SHUTDOWN)
	if err != nil {
		log.LogFatalf(err)
	}

	for k, agent := range al.agents {
		_, err = agent.rwc.Write(data)
		if err != nil {
			log.LogInfo(k, " closed")
		} else {
			log.LogInfo(k, " send shutdown")
		}
	}
}
Example #23
0
func RemoveApp(id int32) {
	applock.Lock()
	defer applock.Unlock()
	if _, ok := context.app[id]; !ok {
		return
	}

	app := context.app[id]
	app.Close()
	delete(context.app, id)

	out, err := share.CreateRemoveServerMsg(id)
	if err != nil {
		log.LogFatalf(err)
	}
	for _, v := range context.app {
		v.conn.Write(out)
	}

}
Example #24
0
File: app.go Project: mysll/flynet
func (app *app) SendList() {
	applock.RLock()
	defer applock.RUnlock()

	size := len(context.app)
	if size == 0 {
		return
	}

	rs := make([]share.AddApp, 0, size)
	for _, v := range context.app {
		rs = append(rs, share.AddApp{v.typ, v.id, v.name, v.host, v.port, v.clienthost, v.clientport, v.ready, v.enableglobaldata})
	}

	outmsg, err := share.CreateServerListMsg(rs)
	if err != nil {
		log.LogFatalf(err)
	}

	app.conn.Write(outmsg)
}
Example #25
0
func (p *csvparser) Parse(f string) error {
	file, err := os.Open(f)
	if err != nil {
		return err
	}

	defer file.Close()

	p.infos = make(map[string][]string)
	reader := csv.NewReader(file)
	head := false
	for {
		line, err := reader.Read()
		if err == io.EOF {
			break
		} else if err != nil {
			return err
		}

		if len(line) == 0 {
			continue
		}

		if strings.HasPrefix(line[0], "//") {
			continue
		}

		if !head {
			if line[0] == "ID" {
				p.heads = make([]header, 0, len(line))
				for k, h := range line {
					if strings.HasPrefix(h, "//") {
						continue
					}
					p.headindex[h] = len(p.heads)
					p.heads = append(p.heads, header{h, k})
					if h == "Entity" {
						p.entity = len(p.heads)
					}
				}
				head = true
			}
		} else {
			id := line[0]
			if id == "" {
				continue
			}
			if _, ok := p.infos[id]; ok {
				log.LogFatalf("config file ", f, " id repeat ", id)
				continue
			}

			lineinfo := make([]string, len(p.heads))
			for k, hi := range p.heads {
				lineinfo[k] = line[hi.index]
				if strings.HasSuffix(hi.name, "_script") {
					if p.entity != 0 && lineinfo[p.entity-1] != "" {
						p.ParseOp(id, hi.name, lineinfo[k])
					}

				}
			}
			p.infos[id] = lineinfo
		}

	}

	return nil
}
Example #26
0
func main() {
	_, err := os.Stat("log")
	if err != nil {
		os.Mkdir("log", os.ModePerm)
	}

	if _, err := os.Stat("log/master.log"); err == nil {
		os.Remove("log/master.log")
	}

	log.WriteToFile("log/master.log")

	defer func() {
		if e := recover(); e != nil {
			log.LogFatalf(e)
			time.Sleep(1 * time.Second)
		}
	}()

	flag.Parse()
	if *config == "" {
		flag.PrintDefaults()
		return
	}

	m := master.NewMaster()
	apps := *config + "/app.json"
	appdata, e := ioutil.ReadFile(apps)
	if e != nil {
		panic(e)
	}

	var app master.App
	if err := json.Unmarshal(appdata, &app); err != nil {
		panic(err)
	}

	m.AppDef = app
	servers := *config + "/servers.json"
	json, err := readConfig(servers)
	if err != nil {
		panic(err)
	}

	def, err1 := json.Map()
	if err1 != nil {
		panic(err1)
	}
	for key := range def {
		if key == "master" {
			mst := json.Get(key)
			if host, ok := mst.CheckGet("host"); ok {
				v, err := host.String()
				if err != nil {
					panic(err)
				}

				m.Host = v
			} else {
				m.Host = "127.0.0.1"
			}

			if localip, ok := mst.CheckGet("localip"); ok {
				v, err := localip.String()
				if err != nil {
					panic(err)
				}

				m.LocalIP = v
			} else {
				m.LocalIP = "127.0.0.1"
			}

			if outerip, ok := mst.CheckGet("outerip"); ok {
				v, err := outerip.String()
				if err != nil {
					panic(err)
				}

				m.OuterIP = v
			} else {
				m.OuterIP = "127.0.0.1"
			}

			if port, ok := mst.CheckGet("port"); ok {
				v, err := port.Int()
				if err != nil {
					panic(err)
				}

				m.Port = v
			} else {
				m.Port = 5100
			}

			if agent, ok := mst.CheckGet("agent"); ok {
				v, err := agent.Bool()
				if err != nil {
					panic(err)
				}

				m.Agent = v
			}

			if agentid, ok := mst.CheckGet("agentid"); ok {
				v, err := agentid.String()
				if err != nil {
					panic(err)
				}

				m.AgentId = v
			}

			if cp, ok := mst.CheckGet("consoleport"); ok {
				v, err := cp.Int()
				if err != nil {
					panic(err)
				}

				m.ConsolePort = v
			}

			if tpl, ok := mst.CheckGet("consoleroot"); ok {
				v, err := tpl.String()
				if err != nil {
					panic(err)
				}
				log.LogMessage("path:", v)
				m.Template = v
			}

			if waits, ok := mst.CheckGet("waitagents"); ok {
				v, err := waits.Int()
				if err != nil {
					panic(err)
				}

				m.WaitAgents = v
			}

			if startuid, ok := mst.CheckGet("startuid"); ok {
				v, err := startuid.Int()
				if err != nil {
					panic(err)
				}

				master.AppUid = int32(v)
			}

			if nobalance, ok := mst.CheckGet("nobalance"); ok {
				v, err := nobalance.Bool()
				if err != nil {
					panic(err)
				}

				m.NoBalance = v
			}

			continue

		}

		m.AppArgs[key], _ = json.Get(key).MarshalJSON()
	}

	exitChan := make(chan int)
	signalChan := make(chan os.Signal, 1)
	go func() {
		<-signalChan
		exitChan <- 1
	}()
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	m.Start()
	m.Wait(exitChan)
	m.Exit()
	log.CloseLogger()
}
Example #27
0
File: db.go Project: mysll/flynet
func parseArgs() {
	args := App.StartArgs

	if typ, ok := args.CheckGet("type"); ok {
		v, err := typ.String()
		if err != nil {
			log.LogFatalf(err)
		}
		App.typ = v
	} else {
		log.LogFatalf("type not defined")
	}

	if ds, ok := args.CheckGet("datasource"); ok {
		v, err := ds.String()
		if err != nil {
			log.LogFatalf(err)
		}
		App.ds = v
	} else {
		log.LogFatalf("datasource not defined")
	}

	if role, ok := args.CheckGet("role"); ok {
		v, err := role.String()
		if err != nil {
			log.LogFatalf(err)
		}
		App.roleEntity = v
	}

	if dname, ok := args.CheckGet("db"); ok {
		v, err := dname.String()
		if err != nil {
			log.LogFatalf(err)
		}
		App.dbname = v
	} else {
		log.LogFatalf("db not defined")
	}

	if entity, ok := args.CheckGet("entity"); ok {
		v, err := entity.String()
		if err != nil {
			log.LogFatalf(err)
		}
		App.entity = v
	} else {
		log.LogFatalf("entity not defined")
	}

	App.pools = 1
	if p, ok := args.CheckGet("pools"); ok {
		v, err := p.Int()
		if err != nil {
			log.LogFatalf(err)
		}
		if v > 0 {
			App.pools = v
		}

	}

	App.rolelimit = 1
	if l, ok := args.CheckGet("rolelimit"); ok {
		v, err := l.Int()
		if err != nil {
			log.LogFatalf(err)
		}
		if v > 1 {
			App.rolelimit = v
		}
	}

	App.nameunique = true
	if l, ok := args.CheckGet("rolenameunique"); ok {
		v, err := l.Int()
		if err != nil {
			log.LogFatalf(err)
		}
		if v == 0 {
			App.nameunique = false
		}
	}
}
Example #28
0
func (svr *Server) Start(master string, localip string, outerip string, typ string, argstr string) bool {
	svr.startTime = time.Now()
	defer func() {
		if e := recover(); e != nil {
			log.LogFatalf(e)
		}
	}()

	args, err := simplejson.NewJson([]byte(argstr))
	if err != nil {
		panic(err)
	}
	svr.Type = typ
	svr.StartArgs = args
	if name, ok := args.CheckGet("name"); ok {
		v, err := name.String()
		if err != nil {
			panic(err)
		}
		svr.Name = v
	} else {
		panic("app id not defined")
	}
	svr.MailBox = rpc.NewMailBox(0, 0, svr.AppId)

	//now := time.Now()
	//log.WriteToFile(fmt.Sprintf("log/%s_%d_%d_%d_%d_%d_%d.log", svr.Name, now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()))

	log.LogMessage("id:", svr.AppId, ", name:", svr.Name)

	svr.Host = localip
	if svr.Host == "" {
		if host, ok := args.CheckGet("host"); ok {
			v, err := host.String()
			if err != nil {
				panic(err)
			}
			svr.Host = v
		} else {
			panic(svr.Name + " host not defined")
		}
	}

	if port, ok := args.CheckGet("port"); ok {
		v, err := port.Int()
		if err != nil {
			panic(err)
		}
		svr.Port = v
	} else {
		panic(svr.Name + "port not defined")
	}

	svr.ClientHost = outerip
	if svr.ClientHost == "" {
		if clienthost, ok := args.CheckGet("clienthost"); ok {
			v, err := clienthost.String()
			if err != nil {
				panic(err)
			}
			svr.ClientHost = v
		}
	}

	if clientport, ok := args.CheckGet("clientport"); ok {
		v, err := clientport.Int()
		if err != nil {
			panic(err)
		}
		svr.ClientPort = v
	}

	if fronted, ok := args.CheckGet("fronted"); ok {
		v, err := fronted.Bool()
		if err != nil {
			panic(err)
		}

		svr.Fronted = v
	}

	svr.Sockettype = "native"
	if Sockettype, ok := args.CheckGet("sockettype"); ok {
		v, err := Sockettype.String()
		if err != nil {
			panic(err)
		}

		svr.Sockettype = v
	}

	//rpc端口
	r, err := net.Listen("tcp", fmt.Sprintf("%s:%d", svr.Host, svr.Port))
	if err != nil {
		panic(err)
	}
	svr.rpcListener = r
	if svr.Port == 0 {
		svr.Port = r.Addr().(*net.TCPAddr).Port
	}

	if svr.Fronted && !svr.apper.RawSock() {
		log.TraceInfo(svr.Name, "init link")
		listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", svr.ClientHost, svr.ClientPort))
		if err != nil {
			panic(err)
		}

		svr.clientListener = listener
		if svr.ClientPort == 0 {
			svr.ClientPort = listener.Addr().(*net.TCPAddr).Port
		}

		switch svr.Sockettype {
		case "websocket":
			svr.WaitGroup.Wrap(func() { util.WSServer(svr.clientListener, &WSClientHandler{}) })
		default:
			svr.WaitGroup.Wrap(func() { util.TCPServer(svr.clientListener, &ClientHandler{}) })
		}

		log.TraceInfo(svr.Name, "start link complete")
	}

	master_peer := &master_peer{}
	peer := &peer{addr: master, h: master_peer}
	if err := peer.Connect(); err != nil {
		panic(err)
	}

	svr.noder = peer

	signalChan := make(chan os.Signal, 1)
	go func() {
		for {
			if _, ok := <-signalChan; !ok {
				return
			}
		}

	}()

	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	if debug, ok := args.CheckGet("debug"); ok {
		v, err := debug.Bool()
		if err == nil {
			svr.Debug = v
		}
	}

	if pfport, ok := args.CheckGet("pprof"); ok {
		v, err := pfport.Int()
		if err == nil {
			svr.PProfPort = v
		}
	}

	if assets, ok := args.CheckGet("assets"); ok {
		v, err := assets.String()
		if err == nil {
			svr.AssetPath = v
		}
	}

	if loglevel, ok := args.CheckGet("loglevel"); ok {
		v, err := loglevel.Int()
		if err == nil {
			log.SetLogLevel("stdout", v)
		}
	}

	svr.globalset = "GlobalSet"
	if gs, ok := args.CheckGet("globalset"); ok {
		v, err := gs.String()
		if err == nil {
			svr.globalset = v
		}
	}

	svr.globaldataserver = false
	if enable, ok := args.CheckGet("globaldataserver"); ok {
		v, err := enable.Bool()
		if err == nil {
			svr.globaldataserver = v
		}
	}

	svr.enableglobaldata = false
	if enable, ok := args.CheckGet("enableglobaldata"); ok {
		v, err := enable.Bool()
		if err == nil {
			svr.enableglobaldata = v
		}
	}

	svr.maxglobalentry = 10
	if max, ok := args.CheckGet("maxglobalentry"); ok {
		v, err := max.Int()
		if err == nil {
			svr.maxglobalentry = v
		}
	}

	log.LogMessage("global data status is ", svr.enableglobaldata)

	if svr.globaldataserver {
		svr.globalHelper.SetServer()
		log.LogMessage("promote to global data server")
	}

	serial := (uint64(time.Now().Unix()%0x80000000) << 32) | (uint64(svr.AppId) << 24)
	svr.setSerial(serial)
	log.LogMessage("start serial:", fmt.Sprintf("%X", serial))
	if !svr.apper.OnPrepare() {
		return false
	}
	svr.CurrentInBase(svr.apper.IsBase())
	if svr.AssetPath != "" {
		helper.LoadAllConfig(svr.AssetPath)
	}

	//内部rpc注册
	svr.rpcCh = make(chan *rpc.RpcCall, RPCBUFFER)
	svr.rpcServer = createRpc(svr.rpcCh)
	svr.WaitGroup.Wrap(func() { rpc.CreateService(svr.rpcServer, svr.rpcListener) })

	svr.rpcProto = codec
	if svr.rpcProto == nil {
		panic("proto not set")
	}
	log.LogMessage("client proto:", svr.rpcProto.GetCodecInfo())
	svr.Ready()

	return true
}
Example #29
0
func (hd *handler) Handle(conn net.Conn) {

	log.LogInfo("new client: ", conn.RemoteAddr())

	if !App.MustAppReady {
		log.LogError("must app not ready")
		conn.Close()
		return
	}

	r := &s2c.Rpc{}
	r.Sender = proto.String(App.Name)

	h, p, err := GetLogin()
	if err != nil {
		e := &s2c.Error{}
		e.ErrorNo = proto.Int32(share.ERROR_NOLOGIN)
		b, err := proto.Marshal(e)
		if err != nil {
			conn.Close()
			log.LogFatalf(err)
		}

		r.Servicemethod = proto.String("Login.Error")
		r.Data = b
		data, err := proto.Marshal(r)
		if err != nil {
			log.LogFatalf(err)
			return
		}
		out, _ := util.CreateMsg(nil, data, share.S2C_RPC)
		_, err = conn.Write(out)
		if err != nil {
			conn.Close()
			log.LogError(err)
			return
		}
	} else {
		l := &s2c.Login{}
		l.Host = proto.String(h)
		l.Port = proto.Int32(int32(p))
		b, err := proto.Marshal(l)
		if err != nil {
			conn.Close()
			log.LogFatalf(err)
		}
		log.LogInfo("client choose login:"******":", p)

		r.Servicemethod = proto.String("Login.LoginInfo")
		r.Data = b
		data, err := proto.Marshal(r)
		if err != nil {
			log.LogFatalf(err)
			return
		}
		out, _ := util.CreateMsg(nil, data, share.S2C_RPC)
		_, err = conn.Write(out)
		if err != nil {
			conn.Close()
			log.LogError(err)
			return
		}
	}
	conn.SetReadDeadline(time.Now().Add(time.Second * 10))
	conn.Read(hd.ignore[:])
	log.LogMessage("client close: ", conn.RemoteAddr())
	conn.Close()
}