init.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package baseserver
  2. import (
  3. "rocommon"
  4. _ "rocommon/rpc"
  5. "rocommon/service"
  6. "rocommon/socket"
  7. "rocommon/util"
  8. "roserver/baseserver/model"
  9. "roserver/serverproto"
  10. "runtime"
  11. "sort"
  12. "strconv"
  13. "time"
  14. )
  15. var Queue rocommon.NetEventQueue
  16. type ServiceParam struct {
  17. ServiceName string
  18. ServiceType string //tcpAcceptor /tcpConnector
  19. ProcName string
  20. LisAddr string
  21. DiscoveryServiceName string //用于服务器发现
  22. DiscoveryServiceZone int //用于服务器发现
  23. }
  24. //loadConfig是否需要加载配置文件, update是否有主循环
  25. func Init(serverName string, loadConfig func(), update rocommon.UpdateModule) {
  26. //设置携程使用的线程数量(不会强制性生效)
  27. //The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously.
  28. // There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count
  29. // against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit.
  30. runtime.GOMAXPROCS(runtime.NumCPU() / 2)
  31. //dgnet -> init.go
  32. service.Init(serverName)
  33. util.InfoF("////////////////////////Service GameVersion=%v DebugMode=%v",
  34. int32(serverproto.GameVersion_GameVersion_Main), service.DebugMode)
  35. if loadConfig != nil {
  36. loadConfig()
  37. }
  38. //事件回调队列
  39. Queue = service.NewEventQueue()
  40. //设置更新操作
  41. if update != nil {
  42. Queue.AttachUpdateModule(update)
  43. }
  44. Queue.StartQueue()
  45. //链接服务器发现 etcd 在service.Init中已经实现
  46. //log.Printf("server init ok...")
  47. util.InfoF("server init ok...")
  48. }
  49. func Wait() {
  50. //todo...
  51. //监听退出信号
  52. service.WaitExitSignal()
  53. Queue.StopQueue()
  54. Queue.Wait()
  55. }
  56. func Exit(node rocommon.ServerNode) {
  57. //todo... 停止所有在监听的协程
  58. util.InfoF("exit...")
  59. //停止etcd
  60. if node != nil {
  61. node.Stop()
  62. service.ETCDUnregister(node)
  63. }
  64. service.GetServiceDiscovery().Close()
  65. }
  66. var idxMap = map[int]*model.PerformKVTimeSt{}
  67. var performTime uint64 = 0
  68. func KVTimeTest(nowTime uint64) {
  69. var printfList []model.PerformKVTimeSt
  70. if performTime <= 0 {
  71. performTime = nowTime
  72. } else if nowTime-performTime >= 1000 {
  73. performTime = nowTime
  74. for _, val := range idxMap {
  75. printfList = append(printfList, *val)
  76. }
  77. }
  78. if len(printfList) > 0 {
  79. sort.Slice(printfList, func(i, j int) bool {
  80. return printfList[i].AckMsgId < printfList[j].AckMsgId
  81. })
  82. printfListStr := ""
  83. for idx := 0; idx < len(printfList); idx++ {
  84. //msgIdStr := strconv.Itoa(int(printfList[idx].AckMsgId))
  85. tmpTime := float64(printfList[idx].TotalTime) / float64(printfList[idx].TotalNum)
  86. tmpPerNum := printfList[idx].NowTime - printfList[idx].BeginTime
  87. if tmpPerNum > 0 {
  88. tmpPerNum = uint64(printfList[idx].TotalNum) * 1000 / tmpPerNum
  89. } else {
  90. tmpPerNum = uint64(printfList[idx].TotalNum)
  91. }
  92. printfListStr += " \n" + printfList[idx].MsgName + ":" +
  93. strconv.FormatInt(int64(tmpTime), 10) + "(ms) | " +
  94. strconv.FormatInt(int64(tmpPerNum), 10) + "(req-ack/s) | " +
  95. strconv.Itoa(int(printfList[idx].TotalNum)) + "(total)"
  96. }
  97. util.DebugF("printfListStr=%v", printfListStr)
  98. }
  99. }
  100. func CreateAcceptor(param ServiceParam, serverConfig service.ConfigServerNode) rocommon.ServerNode {
  101. if param.ServiceType == "" {
  102. param.ServiceType = "tcpAcceptor"
  103. }
  104. node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, Queue)
  105. //消息处理函数,根据给定的服务器类型来获取,例如gate,game,db,auth
  106. msgPrcFunc := serverproto.GetMessageHandler(param.ServiceName)
  107. //通过QueueEventCall函数加入直接函数的回调队列中
  108. socket.SetProcessorRPC(node, param.ProcName, func(e rocommon.ProcEvent) {
  109. if msgPrcFunc != nil {
  110. msgPrcFunc(e)
  111. //nowTime := util.GetTimeMilliseconds()
  112. //msgPrcFunc(e)
  113. //nowTime1 := util.GetTimeMilliseconds()
  114. //switch in := e.(type) {
  115. //case *model.RecvGateMsgEvent:
  116. // //tmpInfo := rocommon.MessageInfoByMsg(in.Msg())
  117. // //if tmpInfo != nil && tmpInfo.ID == 1066 {
  118. // // delTime := nowTime1 - nowTime
  119. // // recvTime := nowTime - in.KvTime
  120. // // util.DebugF("kvtime cid=%v idx=%v msg=%v deltime=%v recvtime=%v",
  121. // // in.ClientID, idxMap[in.ClientID], tmpInfo.ID, delTime, recvTime)
  122. // // //if delTime > 0 {
  123. // // // util.DebugF("kvtime cid=%v idx=%v deltime=%v msg=%T", in.ClientID, idxMap[in.ClientID], delTime, tmpInfo.ID)
  124. // // //}
  125. // //}
  126. // tmpInfo := rocommon.MessageInfoByMsg(in.Msg())
  127. // if tmpInfo != nil {
  128. // gateGameTime := nowTime - in.KvTime
  129. // gateGameProcTime := nowTime1 - in.KvTime
  130. // idxItem, ok := idxMap[tmpInfo.ID]
  131. // if ok {
  132. // idxItem.TotalNum++
  133. // idxItem.TotalTime += gateGameProcTime + gateGameTime
  134. // idxItem.NowTime = nowTime1
  135. // } else {
  136. // idxItem = &model.PerformKVTimeSt{
  137. // TotalNum: 1,
  138. // TotalTime: gateGameProcTime + gateGameTime,
  139. // MsgName: tmpInfo.Type.Name(),
  140. // BeginTime: nowTime1,
  141. // NowTime: nowTime1,
  142. // AckMsgId: int32(tmpInfo.ID),
  143. // }
  144. // }
  145. // idxMap[tmpInfo.ID] = idxItem
  146. // KVTimeTest(nowTime1)
  147. // }
  148. //}
  149. }
  150. })
  151. if opt, ok := node.(rocommon.TCPSocketOption); ok {
  152. opt.SetSocketBuff(40960*1024, 40960*1024, true)
  153. }
  154. property := node.(rocommon.ServerNodeProperty)
  155. //服务器类型节点,区号,区号中的当前编号
  156. property.SetServerType(serverConfig.Node.Type)
  157. property.SetZone(serverConfig.Node.Zone)
  158. property.SetIndex(serverConfig.Node.Id)
  159. //session uuid 创建时的key
  160. node.(rocommon.SessionMagExport).SetUuidCreateKey(serverConfig.Node.Id)
  161. node.Start()
  162. //注册到服务器发现etcd中
  163. service.ETCDRegister(node)
  164. //todo...添加到总的服务器管理中
  165. return node
  166. }
  167. func CreateConnector(param ServiceParam) rocommon.ServerNode {
  168. if param.ServiceType == "" {
  169. param.ServiceType = "tcpConnector"
  170. }
  171. //通过服务器发现ETCD来实现连接
  172. service.DiscoveryService(param.DiscoveryServiceName, param.DiscoveryServiceZone,
  173. func(mn service.MultiServerNode, sd *service.ETCDServiceDesc) {
  174. //不连接自己
  175. serviceCfg := service.GetServiceConfig()
  176. if sd.Type == serviceCfg.Node.Type && sd.Zone == serviceCfg.Node.Zone && sd.Index == serviceCfg.Node.Id {
  177. return
  178. }
  179. node := socket.NewServerNode(param.ServiceType, param.ServiceName, sd.Host, Queue)
  180. msgPrcFunc := serverproto.GetMessageHandler(param.ServiceName)
  181. socket.SetProcessorRPC(node, param.ProcName, func(e rocommon.ProcEvent) {
  182. if msgPrcFunc != nil {
  183. msgPrcFunc(e)
  184. //nowTime := util.GetTimeMilliseconds()
  185. //msgPrcFunc(e)
  186. //delTime := util.GetTimeMilliseconds() - nowTime
  187. //if delTime > 5 {
  188. // log.Printf("deltime=%v msg=%T", util.GetTimeMilliseconds()-nowTime, e.(rocommon.ProcEvent).Msg())
  189. //}
  190. }
  191. })
  192. if opt, ok := node.(rocommon.TCPSocketOption); ok {
  193. opt.SetSocketBuff(40960*1024, 40960*1024, true)
  194. //15s无读写断开,服务器之间已经添加心跳来位置读写(非调试模式启动)
  195. if !service.DebugMode {
  196. opt.SetSocketDeadline(time.Second*15, time.Second*15)
  197. }
  198. }
  199. //通过etcd服务器发现来处理,如果发现重复的节点会解除当前正在重连或者执行的节点
  200. node.(rocommon.TCPConnector).SetReconnectTime(3 * time.Second)
  201. //如果连接的是服务器的节点那么需要加入当前本节点的信息,用来处理服务器节点之间的身份验证
  202. // ServerTCPEventHook中会使用
  203. node.(rocommon.ContextSet).SetContextData("sid", sd, "sid")
  204. //添加到服务器发现管理器中
  205. mn.AddNode(sd, node)
  206. //util.DebugF("NewServerNode:%v", node.TypeOfName())
  207. node.Start()
  208. //todo...添加到总的服务器管理中
  209. })
  210. if param.ServiceName != model.SERVICE_NODE_TYPE_CROSSROUTER_STR &&
  211. param.ServiceName != model.SERVICE_NODE_TYPE_CROSSSERVER_STR {
  212. service.InitServiceStartupTime(param.DiscoveryServiceZone)
  213. }
  214. return nil
  215. }
  216. //gate监听客户端处理
  217. func CreateClientAcceptor(param ServiceParam, serverConfig service.ConfigServerNode) rocommon.ServerNode {
  218. if param.ServiceType == "" {
  219. param.ServiceType = "tcpAcceptor"
  220. }
  221. //不需要要消息处理队列
  222. //node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, nil)
  223. node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, Queue)
  224. //没有具体的消息处理逻辑
  225. //socket.SetProcessorRPC(node, param.ProcName, nil)
  226. msgPrcFunc := serverproto.GetMessageHandler(param.ServiceName)
  227. socket.SetProcessorRPC(node, param.ProcName, func(e rocommon.ProcEvent) {
  228. if msgPrcFunc != nil {
  229. msgPrcFunc(e)
  230. }
  231. })
  232. if opt, ok := node.(rocommon.TCPSocketOption); ok {
  233. opt.SetSocketBuff(40960, 40960, true)
  234. //40秒无读,30秒无写断开 如果没有心跳了超时直接断开,调试期间可以不加
  235. // 通过该方法来模拟心跳保持连接
  236. if serverConfig.Node.Reconnect > 0 {
  237. opt.SetSocketDeadline(time.Second*40, time.Second*40)
  238. //读/写协程没有过滤超时事件,发生了操时操作就断开连接
  239. }
  240. }
  241. property := node.(rocommon.ServerNodeProperty)
  242. //服务器类型节点,区号,区号中的当前编号
  243. property.SetServerType(serverConfig.Node.Type)
  244. property.SetZone(serverConfig.Node.Zone)
  245. property.SetIndex(serverConfig.Node.Id)
  246. //session uuid 创建时的key
  247. node.(rocommon.SessionMagExport).SetUuidCreateKey(serverConfig.Node.Id)
  248. node.Start()
  249. //外层通过该对象来获取监听器上接收的链接
  250. model.ClientSessionMag = node.(socket.SessionManager)
  251. //注册到服务器发现etcd中
  252. service.ETCDRegister(node)
  253. //todo...添加到总的服务器管理中
  254. return node
  255. }
  256. func CreateHttpConnector(param ServiceParam) rocommon.ServerNode {
  257. if param.ServiceType == "" {
  258. param.ServiceType = "httpConnector"
  259. }
  260. node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, nil)
  261. return node
  262. }
  263. //func CreateHttpAcceptor(param ServiceParam, serverConfig service.ConfigServerNode) rocommon.ServerNode {
  264. // if param.ServiceType == "" {
  265. // param.ServiceType = "httpAcceptor"
  266. // }
  267. // node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, Queue)
  268. //
  269. // msgPrcFunc := serverproto.GetMessageHandler(param.ServiceName)
  270. // socket.SetProcessorRPC(node, param.ProcName, func(e rocommon.ProcEvent) {
  271. // if matcher, ok := e.Session().(http.RequestProc); ok {
  272. // msg.WebGMMsgProcess(matcher, e)
  273. // } else {
  274. // msgPrcFunc(e)
  275. // }
  276. // })
  277. //
  278. // node.Start()
  279. //
  280. // return node
  281. //}
  282. //gate监听客户端处理
  283. func CreateWebSocketAcceptor(param ServiceParam, serverConfig service.ConfigServerNode) rocommon.ServerNode {
  284. if param.ServiceType == "" {
  285. param.ServiceType = "wsAcceptor"
  286. }
  287. //不需要要消息处理队列
  288. //node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, nil)
  289. node := socket.NewServerNode(param.ServiceType, param.ServiceName, param.LisAddr, Queue)
  290. //没有具体的消息处理逻辑
  291. //socket.SetProcessorRPC(node, param.ProcName, nil)
  292. msgPrcFunc := serverproto.GetMessageHandler(param.ServiceName)
  293. socket.SetProcessorRPC(node, param.ProcName, func(e rocommon.ProcEvent) {
  294. if msgPrcFunc != nil {
  295. msgPrcFunc(e)
  296. }
  297. })
  298. if opt, ok := node.(rocommon.TCPSocketOption); ok {
  299. opt.SetSocketBuff(11264, 11264, true)
  300. //40秒无读,30秒无写断开 如果没有心跳了超时直接断开,调试期间可以不加
  301. // 通过该方法来模拟心跳保持连接
  302. if serverConfig.Node.Reconnect > 0 {
  303. opt.SetSocketDeadline(time.Second*40, time.Second*40)
  304. //读/写协程没有过滤超时事件,发生了操时操作就断开连接
  305. }
  306. }
  307. property := node.(rocommon.ServerNodeProperty)
  308. //服务器类型节点,区号,区号中的当前编号
  309. property.SetServerType(serverConfig.Node.Type)
  310. property.SetZone(serverConfig.Node.Zone)
  311. property.SetIndex(serverConfig.Node.Id)
  312. //session uuid 创建时的key
  313. node.(rocommon.SessionMagExport).SetUuidCreateKey(serverConfig.Node.Id)
  314. node.Start()
  315. //外层通过该对象来获取监听器上接收的链接
  316. model.ClientSessionMag = node.(socket.SessionManager)
  317. //注册到服务器发现etcd中
  318. service.ETCDRegister(node)
  319. //todo...添加到总的服务器管理中
  320. return node
  321. }