main.go 22.1 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6
package main

import (
	"context"
	"flag"
	"fmt"
hujiebin's avatar
hujiebin committed
7
	"gorm.io/gorm/schema"
hujiebin's avatar
hujiebin committed
8 9 10 11 12 13 14 15 16 17 18 19 20
	"net"
	"net/url"
	"strconv"
	"time"

	"github.com/go-redis/redis/v8"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"

	"hilo-userCenter/common"
hujiebin's avatar
hujiebin committed
21
	appConfig "hilo-userCenter/common/config"
hujiebin's avatar
hujiebin committed
22 23 24 25 26 27 28 29
	"hilo-userCenter/common/dingding"
	"hilo-userCenter/common/mylogrus"
	"hilo-userCenter/manager"
	"hilo-userCenter/protocol/biz"
	"hilo-userCenter/protocol/userCenter"
)

const (
hujiebin's avatar
hujiebin committed
30 31
	port          = 50040
	redis_section = 1
hujiebin's avatar
hujiebin committed
32 33 34 35
)

// 控制异步消息协程
const (
hujiebin's avatar
hujiebin committed
36
	monitorLength     = 3500 // 队列告警数量
hujiebin's avatar
hujiebin committed
37 38
	kickChanSize      = 500
	broadcastChanSize = 3500
hujiebin's avatar
hujiebin committed
39
	areacastChanSize  = 3500
hujiebin's avatar
hujiebin committed
40
	levelcastChanSize = 3500
hujiebin's avatar
hujiebin committed
41 42 43 44 45
)

var (
	kickChan      chan KickChanMsg
	broadcastChan chan BroadcastChanMsg
hujiebin's avatar
hujiebin committed
46
	areacastChan  chan AreaChanMsg
hujiebin's avatar
hujiebin committed
47
	levelcastChan chan LevelChanMsg
hujiebin's avatar
hujiebin committed
48 49 50 51 52 53 54 55 56 57 58 59 60
)

type KickChanMsg struct {
	userId    uint64
	proxyAddr string
}

type BroadcastChanMsg struct {
	ProxyAddr string
	UserIds   []uint64
	in        *userCenter.BroadcastMessage
}

hujiebin's avatar
hujiebin committed
61 62 63 64 65 66
type AreaChanMsg struct {
	ProxyAddr string
	UserIds   []uint64
	in        *userCenter.AreaMessage
}

hujiebin's avatar
hujiebin committed
67 68 69 70 71 72
type LevelChanMsg struct {
	ProxyAddr string
	UserIds   []uint64
	in        *userCenter.LevelMessage
}

hujiebin's avatar
hujiebin committed
73 74 75
var (
	userManager *manager.UserManager     = nil
	termManager *manager.TerminalManager = nil
hujiebin's avatar
hujiebin committed
76
	roomManager *manager.RoomManager     = nil
hujiebin's avatar
hujiebin committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
)

type server struct {
	userCenter.UnimplementedUserServer
}

var kasp = keepalive.ServerParameters{
	MaxConnectionIdle:     15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY
	MaxConnectionAge:      30 * time.Second, // If any connection is alive for more than 30 seconds, send a GOAWAY
	MaxConnectionAgeGrace: 5 * time.Second,  // Allow 5 seconds for pending RPCs to complete before forcibly closing connections
	Time:                  5 * time.Second,  // Ping the client if it is idle for 5 seconds to ensure the connection is still active
	Timeout:               1 * time.Second,  // Wait 1 second for the ping ack before assuming the connection is dead
}

func (s *server) Login(ctx context.Context, in *userCenter.LoginMessage) (*userCenter.LoginMessageRsp, error) {
	mylogrus.MyLog.Infof("Received loginMsg: %s, from proxy %s, client %s\n", in.Token, in.ProxyAddr, in.ClientAddr)

	var loginStatus uint32 = common.Login_success
	claim, err := common.ParseToken(in.GetToken())
	if err != nil {
		mylogrus.MyLog.Errorf("Invalid token %s\n", in.GetToken())
		loginStatus = common.Login_valid_token
	} else if time.Now().Unix() > claim.ExpiresAt {
		loginStatus = common.Login_token_expired
	}

	if loginStatus != common.Login_success || claim == nil {
		return &userCenter.LoginMessageRsp{Status: loginStatus, Uid: 0}, nil
	} else {
		// FIXME: 发现用户已经登录,要踢走旧连接
		proxyAddr := userManager.GetUser(claim.UserId)
		if proxyAddr != nil {
			mylogrus.MyLog.Infof("%d has existing value %s", claim.UserId, *proxyAddr)
			kickChan <- KickChanMsg{
				userId:    claim.UserId,
				proxyAddr: *proxyAddr,
			}
			//clientAddr := termManager.GetTerminal(claim.UserId)
			//if clientAddr == nil {
			//	mylogrus.MyLog.Infof("No terminal found for %d", claim.UserId)
			//} else {
			//	client := manager.UserProxyMgr.GetClient(*proxyAddr)
			//	if client == nil {
			//		mylogrus.MyLog.Infof("No userProxy found for %d, %s\n", claim.UserId, *proxyAddr)
			//	} else {
			//		toRouterClient := userCenter.NewRouterClient(client)
			//		msg := &userCenter.KickMessage{Uid: claim.UserId, Addr: *clientAddr}
			//		go sendKickMessage(toRouterClient, msg)
			//	}
			//}
		} else {
			mylogrus.MyLog.Errorf("wrong user %d", claim.UserId)
		}
		mylogrus.MyLog.Infof("adding user %d", claim.UserId)

		// save to redis
		userManager.AddUser(claim.UserId, in.ProxyAddr)
		termManager.SetTerminal(claim.UserId, in.ClientAddr)

		// 为登录用户建立反向连接,如果需要的话
		go manager.UserProxyMgr.MakeClient(in.ProxyAddr)
	}
	return &userCenter.LoginMessageRsp{Status: loginStatus, Uid: claim.UserId}, nil
}

func (s *server) Logout(ctx context.Context, in *userCenter.LogoutMessage) (*userCenter.LogoutMessageRsp, error) {
hujiebin's avatar
hujiebin committed
143
	//mylogrus.MyLog.Infof("Received logoutMsg: %s, %d\n", in.GetClientAddr(), in.GetUid())
hujiebin's avatar
hujiebin committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

	addr := termManager.GetTerminal(in.Uid)
	if addr != nil && *addr == in.ClientAddr {
		termManager.RemoveTerminal(in.Uid)
	}

	// 去掉队列push
	//msg := protocol.LogoutMsg{
	//	UserId:    in.Uid,
	//	Timestamp: time.Now().Unix(),
	//}
	//buf, err := json.Marshal(msg)
	//if err == nil {
	//r, err := termManager.RedisClient.RPush(context.Background(), protocol.LogoutMsgQueue, string(buf)).Result()
	//if err == nil {
	//	mylogrus.MyLog.Infof("RPush OK, length = %v ", r)
	//} else {
	//	mylogrus.MyLog.Infof("RPush failed %v", err)
	//}
	//}

	return &userCenter.LogoutMessageRsp{Status: 0}, nil
}

func (s *server) Multicast(ctx context.Context, in *userCenter.MulticastMessage) (*userCenter.MulticastMessageRsp, error) {
hujiebin's avatar
hujiebin committed
169
	//mylogrus.MyLog.Infof("Multicasting msgType = %d to %v, size = %d\n", in.MsgType, in.Uids, len(in.PayLoad))
hujiebin's avatar
hujiebin committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

	failed := []uint64{}
	for _, uid := range in.Uids {
		ok := false
		addr := userManager.GetUser(uid)
		if addr == nil {
			mylogrus.MyLog.Errorf("Unknown user %d\n", uid)
		} else {
			client := manager.UserProxyMgr.MakeClient(*addr)
			if client == nil {
				mylogrus.MyLog.Infof("Failed in making client for %d, %s\n", uid, *addr)
			} else {
				toRouterClient := userCenter.NewRouterClient(client)
				status, err := routeMessage(toRouterClient, uid, in.MsgType, in.PayLoad)
				if err == nil && status == common.ROUTE_SUCCESS {
					ok = true
				}
			}
		}
		if !ok {
			failed = append(failed, uid)
		}
	}
	if len(failed) > 0 {
		mylogrus.MyLog.Infof("Multicast failed for %v\n", failed)
	}
	return &userCenter.MulticastMessageRsp{FailedUids: failed}, nil
}

func (s *server) Broadcast(ctx context.Context, in *userCenter.BroadcastMessage) (*userCenter.BroadcastMessageRsp, error) {
hujiebin's avatar
hujiebin committed
200
	//mylogrus.MyLog.Infof("Broadcasting msgType = %d, size = %d\n", in.MsgType, len(in.PayLoad))
hujiebin's avatar
hujiebin committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

	failed := []uint64{}
	terminals := termManager.GetAll()
	if terminals != nil {
		m := make(map[string][]uint64, 0)
		for u, _ := range *terminals {
			uid, err := strconv.ParseUint(u, 10, 64)
			ok := false
			if err == nil {
				addr := userManager.GetUser(uid)
				if addr != nil {
					if _, ok := m[*addr]; !ok {
						m[*addr] = make([]uint64, 0)
					}
					m[*addr] = append(m[*addr], uid)
					ok = true
				} else {
					mylogrus.MyLog.Errorf("Unknown user %d\n", uid)
				}
			} else {
				mylogrus.MyLog.Infof("Invalid user str: %s\n", u)
			}
			if !ok {
				failed = append(failed, uid)
			}
		}
		for addr, users := range m {
			//addr = strings.Replace(addr, "47.91.121.73", "172.26.95.24", -1)
hujiebin's avatar
hujiebin committed
229 230 231 232
			//mylogrus.MyLog.Infof("Broadcasting: Addr %s: %d users", addr, len(users))
			//if !strings.Contains(addr, "172.26.95.48:50050") && !strings.Contains(addr, "172.26.95.24:50050") {
			//	mylogrus.MyLog.Errorf("Broadcasting: Addr error %s: %d users", addr, len(users))
			//}
hujiebin's avatar
hujiebin committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

			const sendBatchSize = 5
			for i := 0; i < len(users); i += sendBatchSize {
				end := i + sendBatchSize
				if end > len(users) {
					end = len(users)
				}
				broadcastChan <- BroadcastChanMsg{
					ProxyAddr: addr,
					UserIds:   users[i:end],
					in:        in,
				}
				//go realBroadcast(addr, users[i:end], in)
			}
		}
	}
	return &userCenter.BroadcastMessageRsp{FailedUids: failed}, nil
}

hujiebin's avatar
hujiebin committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
func (s *server) Areacast(ctx context.Context, in *userCenter.AreaMessage) (*userCenter.AreaMessageRsp, error) {
	var failed []uint64
	terminals := termManager.GetAll()
	if terminals != nil {
		var uids []uint64
		for uidStr := range *terminals {
			if uid, _ := strconv.ParseUint(uidStr, 10, 64); uid > 0 {
				uids = append(uids, uid)
			}
		}
		// 处理分区用户
		areaUids := userManager.GetAreaUsers(uids, int8(in.Area))
		if len(areaUids) <= 0 {
			return &userCenter.AreaMessageRsp{FailedUids: failed}, nil
		}
		m := make(map[string][]uint64, 0)
		for uid := range areaUids {
			ok := false
			addr := userManager.GetUser(uid)
			if addr != nil {
				if _, ok := m[*addr]; !ok {
					m[*addr] = make([]uint64, 0)
				}
				m[*addr] = append(m[*addr], uid)
				ok = true
			} else {
				mylogrus.MyLog.Errorf("Unknown user %d\n", uid)
			}
			if !ok {
				failed = append(failed, uid)
			}
		}
		for addr, users := range m {
			const sendBatchSize = 5
			for i := 0; i < len(users); i += sendBatchSize {
				end := i + sendBatchSize
				if end > len(users) {
					end = len(users)
				}
				areacastChan <- AreaChanMsg{
					ProxyAddr: addr,
					UserIds:   users[i:end],
					in:        in,
				}
			}
		}
	}
	return &userCenter.AreaMessageRsp{FailedUids: failed}, nil
}

hujiebin's avatar
hujiebin committed
302 303 304 305 306 307 308 309 310 311
func (s *server) Levelcast(ctx context.Context, in *userCenter.LevelMessage) (*userCenter.LevelMessageRsp, error) {
	var failed []uint64
	terminals := termManager.GetAll()
	if terminals != nil {
		var uids []uint64
		for uidStr := range *terminals {
			if uid, _ := strconv.ParseUint(uidStr, 10, 64); uid > 0 {
				uids = append(uids, uid)
			}
		}
312 313
		// 处理等级用户
		levelUserIds, userIds := userManager.GetLevelUsers(uids, in.Level)
hujiebin's avatar
hujiebin committed
314 315 316
		if len(levelUserIds) <= 0 {
			return &userCenter.LevelMessageRsp{FailedUids: failed}, nil
		}
317 318 319 320 321 322 323
		if in.Area > 0 {
			// 处理分区用户
			levelUserIds = userManager.GetAreaUsers(userIds, int8(in.Area))
			if len(levelUserIds) <= 0 {
				return &userCenter.LevelMessageRsp{FailedUids: failed}, nil
			}
		}
hujiebin's avatar
hujiebin committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
		m := make(map[string][]uint64, 0)
		for uid := range levelUserIds {
			ok := false
			addr := userManager.GetUser(uid)
			if addr != nil {
				if _, ok := m[*addr]; !ok {
					m[*addr] = make([]uint64, 0)
				}
				m[*addr] = append(m[*addr], uid)
				ok = true
			} else {
				mylogrus.MyLog.Errorf("Unknown user %d\n", uid)
			}
			if !ok {
				failed = append(failed, uid)
			}
		}
		for addr, users := range m {
			const sendBatchSize = 5
			for i := 0; i < len(users); i += sendBatchSize {
				end := i + sendBatchSize
				if end > len(users) {
					end = len(users)
				}
				levelcastChan <- LevelChanMsg{
					ProxyAddr: addr,
					UserIds:   users[i:end],
					in:        in,
				}
			}
		}
	}
	return &userCenter.LevelMessageRsp{FailedUids: failed}, nil
}

hujiebin's avatar
hujiebin committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
func (s *server) Transmit(ctx context.Context, in *userCenter.BizMessage) (*userCenter.BizMessageRsp, error) {
	mylogrus.MyLog.Infof("Transmiting msgType = %d, uid = %d, payLoad: %s\n", in.MsgType, in.Uid, in.PayLoad)

	// fixme:
	addr := "localhost:50060"

	rsp := &userCenter.BizMessageRsp{}
	client := manager.BizMgr.MakeClient(addr)
	if client == nil {
		mylogrus.MyLog.Errorf("Failed in making client for %d, %s\n", in.Uid, addr)
	} else {
		transmitterClient := biz.NewTransmitterClient(client)
		status, err := transmitMessage(transmitterClient, in.MsgType, in.PayLoad)
		mylogrus.MyLog.Infof("transmit uid = %d, msgType = %d, status = %d, %v", in.Uid, in.MsgType, status, err)
	}

	return rsp, nil
}

hujiebin's avatar
hujiebin committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
func (s *server) EnterRoom(ctx context.Context, in *userCenter.EnterRoomMessage) (*userCenter.EnterRoomMessageRsp, error) {
	if err := roomManager.AddRoomUser(in.GetUid(), in.GetGroupId()); err != nil {
		return nil, err
	}
	return &userCenter.EnterRoomMessageRsp{
		Status: 0,
	}, nil
}

func (s *server) LeaveRoom(ctx context.Context, in *userCenter.LeaveRoomMessage) (*userCenter.LeaveRoomMessageRsp, error) {
	if err := roomManager.DelRoomUser(in.GetUid(), in.GetGroupId()); err != nil {
		return nil, err
	}
	return &userCenter.LeaveRoomMessageRsp{
		Status: 0,
	}, nil
}

func (s *server) RoomHeartbeat(ctx context.Context, in *userCenter.RoomHeartbeatMessage) (*userCenter.RoomHeartbeatMessageRsp, error) {
	if err := roomManager.UpdateRoomUser(in.GetUid(), in.GetGroupId()); err != nil {
		return nil, err
	}
	return &userCenter.RoomHeartbeatMessageRsp{
		Status: 0,
	}, nil
}

func (s *server) GetLastRoomHeartbeat(ctx context.Context, in *userCenter.GetLastRoomHeartbeatMessage) (*userCenter.GetLastRoomHeartbeatMessageResp, error) {
	ts, err := roomManager.GetLastRoomUserHeartbeat(in.GetUid(), in.GetGroupId())
	if err != nil {
		return nil, err
	}
	return &userCenter.GetLastRoomHeartbeatMessageResp{
		Timestamp: ts,
	}, nil
}

hujiebin's avatar
hujiebin committed
415
func realBroadcast(addr string, uids []uint64, msg *userCenter.BroadcastMessage) {
hujiebin's avatar
hujiebin committed
416
	//mylogrus.MyLog.Infof("Broadcasting: Addr %s: users: %v", addr, uids)
hujiebin's avatar
hujiebin committed
417 418 419 420 421 422 423 424 425

	for _, uid := range uids {
		client := manager.UserProxyMgr.MakeClient(addr)
		if client == nil {
			mylogrus.MyLog.Errorf("Failed in making client for %d, %s\n", uid, addr)
		} else {

			toRouterClient := userCenter.NewRouterClient(client)
			status, err := routeMessage(toRouterClient, uid, msg.MsgType, msg.PayLoad)
hujiebin's avatar
hujiebin committed
426 427 428
			if err != nil {
				mylogrus.MyLog.Errorf("routeMessage uid = %d, msgType = %d, status = %d, %v", uid, msg.MsgType, status, err)
			}
hujiebin's avatar
hujiebin committed
429 430 431 432
		}
	}
}

hujiebin's avatar
hujiebin committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
func realAreacast(addr string, uids []uint64, msg *userCenter.AreaMessage) {
	for _, uid := range uids {
		client := manager.UserProxyMgr.MakeClient(addr)
		if client == nil {
			mylogrus.MyLog.Errorf("Failed in making client for %d, %s\n", uid, addr)
		} else {

			toRouterClient := userCenter.NewRouterClient(client)
			status, err := routeMessage(toRouterClient, uid, msg.MsgType, msg.PayLoad)
			if err != nil {
				mylogrus.MyLog.Errorf("routeMessage uid = %d, msgType = %d, status = %d, %v", uid, msg.MsgType, status, err)
			}
		}
	}
}

hujiebin's avatar
hujiebin committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
func realLevelcast(addr string, uids []uint64, msg *userCenter.LevelMessage) {
	for _, uid := range uids {
		client := manager.UserProxyMgr.MakeClient(addr)
		if client == nil {
			mylogrus.MyLog.Errorf("Failed in making client for %d, %s\n", uid, addr)
		} else {

			toRouterClient := userCenter.NewRouterClient(client)
			status, err := routeMessage(toRouterClient, uid, msg.MsgType, msg.PayLoad)
			if err != nil {
				mylogrus.MyLog.Errorf("routeMessage uid = %d, msgType = %d, status = %d, %v", uid, msg.MsgType, status, err)
			}
		}
	}
}

hujiebin's avatar
hujiebin committed
465 466 467 468 469 470 471 472 473 474 475
func routeMessage(c userCenter.RouterClient, uid uint64, msgType uint32, data []byte) (uint32, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	r, err := c.Route(ctx, &userCenter.RouteMessage{
		Uid:     uid,
		MsgType: msgType,
		PayLoad: data,
	})
	if err != nil {
		mylogrus.MyLog.Errorf("Route message to user %d, err: %s\n", uid, err.Error())
	} else if r != nil {
hujiebin's avatar
hujiebin committed
476
		//mylogrus.MyLog.Infof("Route message to user %d, status = %d", uid, r.Status)
hujiebin's avatar
hujiebin committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
		return r.Status, err
	}
	return 0, err
}

func transmitMessage(c biz.TransmitterClient, msgType uint32, data string) (uint32, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	r, err := c.Process(ctx, &biz.BizMessage{
		Type:    msgType,
		PayLoad: data,
	})
	if err != nil {
		mylogrus.MyLog.Errorf("Transmit message type %d, err: %s\n", msgType, err.Error())
	} else if r != nil {
		mylogrus.MyLog.Infof("Transmit message type %d, status = %d", msgType, r.Status)
		return r.Status, err
	}
	return 0, err
}

func sendKickMessage(c userCenter.RouterClient, msg *userCenter.KickMessage) error {
	mylogrus.MyLog.Infof("sendKickMessage %s", msg.String())
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	r, err := c.KickUser(ctx, msg)
	if err != nil && r != nil {
		mylogrus.MyLog.Errorf("sendKickMessage message status = %d", r.Status)
	}
	return err
}

const (
	RegisterName = "userCenter"
)

hujiebin's avatar
hujiebin committed
513 514 515 516
func RegisterToRedis(RedisClusterClient *redis.Client, port int, init bool) {
	// 本地不注册
	if appConfig.AppIsLocal() {
		return
hujiebin's avatar
hujiebin committed
517
	}
hujiebin's avatar
hujiebin committed
518 519 520 521 522
	if RedisClusterClient == nil {
		failMsg := fmt.Sprintf("RegisterToRedis fail,redisClusterNotInit,serviceName:%v", RegisterName)
		_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
		mylogrus.MyLog.Errorf(failMsg)
		return
hujiebin's avatar
hujiebin committed
523
	}
hujiebin's avatar
hujiebin committed
524 525
	redisKey := "service:" + RegisterName
	ip, err := common.GetClientIpV2()
hujiebin's avatar
hujiebin committed
526
	if err != nil {
hujiebin's avatar
hujiebin committed
527 528 529 530
		failMsg := fmt.Sprintf("RegisterToRedis fail,ip fail,err:%v,serviceName:%v", err, RegisterName)
		mylogrus.MyLog.Errorf(failMsg)
		_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
		return
hujiebin's avatar
hujiebin committed
531
	}
hujiebin's avatar
hujiebin committed
532 533 534 535 536 537 538 539
	ipPort := fmt.Sprintf("%s:%d", ip, port)
	if err := RedisClusterClient.ZAdd(context.Background(), redisKey, &redis.Z{
		Score:  float64(time.Now().Unix()),
		Member: ipPort,
	}).Err(); err != nil {
		failMsg := fmt.Sprintf("RegisterToRedis fail,redis fail,err:%v,serviceName:%v", err, RegisterName)
		mylogrus.MyLog.Errorf(failMsg)
		_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
hujiebin's avatar
hujiebin committed
540
	}
hujiebin's avatar
hujiebin committed
541 542 543 544 545 546 547 548 549 550
	// 初始化注册自我检查 selfCheck
	if init {
		go func() {
			ticker := time.NewTicker(time.Second * 5)
			defer ticker.Stop()
			for {
				select {
				case <-ticker.C:
					RegisterToRedis(RedisClusterClient, port, false) // 刷新注册
				}
hujiebin's avatar
hujiebin committed
551
			}
hujiebin's avatar
hujiebin committed
552
		}()
hujiebin's avatar
hujiebin committed
553 554 555
	}
}

hujiebin's avatar
hujiebin committed
556
type HiloConfigs struct {
hujiebin's avatar
hujiebin committed
557 558 559 560 561 562 563
	Name  string `gorm:"primary_key"`
	Value string
}

func main() {
	flag.Parse()

hujiebin's avatar
hujiebin committed
564 565 566 567 568 569 570
	// init redis cluster
	rdbCluster := redis.NewClient(&redis.Options{
		Addr:     appConfig.GetConfigRedis().REDIS_CLUSTER_HOST,
		Password: appConfig.GetConfigRedis().REDIS_CLUSTER_PASSWORD,
	})
	// 注册到redis
	RegisterToRedis(rdbCluster, port, true)
hujiebin's avatar
hujiebin committed
571 572 573

	// init redis
	rdb := redis.NewClient(&redis.Options{
hujiebin's avatar
hujiebin committed
574 575
		Addr:     appConfig.GetConfigRedis().REDIS_HOST,
		Password: appConfig.GetConfigRedis().REDIS_PASSWORD,
hujiebin's avatar
hujiebin committed
576 577 578
		DB:       redis_section,
	})
	if rdb == nil {
hujiebin's avatar
hujiebin committed
579
		mylogrus.MyLog.Fatalf("failed to connect redis %s\n", appConfig.GetConfigRedis().REDIS_HOST)
hujiebin's avatar
hujiebin committed
580 581 582 583 584 585 586 587 588 589 590 591
	}
	result, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		mylogrus.MyLog.Fatal(err)
	} else if result != "PONG" {
		mylogrus.MyLog.Fatalf("Invalid ping response %s", result)
	}

	// init db
	options := "?charset=utf8mb4&parseTime=True&loc=Local&time_zone=" + url.QueryEscape("'+8:00'")
	fmt.Println("options = ", options)

hujiebin's avatar
hujiebin committed
592
	dsn := appConfig.GetConfigMysql().MYSQL_USERNAME + ":" + appConfig.GetConfigMysql().MYSQL_PASSWORD + "@(" + appConfig.GetConfigMysql().MYSQL_HOST + ")/" + appConfig.GetConfigMysql().MYSQL_DB
hujiebin's avatar
hujiebin committed
593 594
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
hujiebin's avatar
hujiebin committed
595 596 597
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
hujiebin's avatar
hujiebin committed
598 599 600 601 602 603 604
	})
	if err != nil {
		mylogrus.MyLog.Fatal("mysql connect error %v", err)
	} else {
		mylogrus.MyLog.Infof("mysql connect success")
	}

hujiebin's avatar
hujiebin committed
605
	var jwtConfig = HiloConfigs{}
hujiebin's avatar
hujiebin committed
606 607 608 609 610 611 612 613 614 615
	db.First(&jwtConfig, "name = 'jwt_secret'")
	if len(jwtConfig.Value) == 0 {
		mylogrus.MyLog.Fatalln("Empty jwt secret")
	}
	mylogrus.MyLog.Infof("jwt secret is %s", jwtConfig.Value)
	common.SetJWTSecret(jwtConfig.Value)

	userManager = &manager.UserManager{
		Ctx:         context.Background(),
		RedisClient: rdb,
hujiebin's avatar
hujiebin committed
616
		MysqlDB:     db,
hujiebin's avatar
hujiebin committed
617
	}
hujiebin's avatar
hujiebin committed
618 619 620 621 622 623 624
	go func() {
		for {
			// 同步区域
			userManager.SyncArea()
			time.Sleep(time.Minute * 15)
		}
	}()
hujiebin's avatar
hujiebin committed
625 626 627 628
	termManager = &manager.TerminalManager{
		Ctx:         context.Background(),
		RedisClient: rdb,
	}
hujiebin's avatar
hujiebin committed
629 630 631 632
	roomManager = &manager.RoomManager{
		Ctx:         context.Background(),
		RedisClient: rdb,
	}
hujiebin's avatar
hujiebin committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

	go func() {
		ticker := time.NewTicker(time.Second * 30)
		defer ticker.Stop()

		for {
			select {
			case a := <-ticker.C:
				mylogrus.MyLog.Infof("Tick at %s", a.String())
				terminals := termManager.GetAll()
				if terminals != nil {
					if len(*terminals) <= 100 {
						mylogrus.MyLog.Infof("%v", *terminals)
					}
					if len(*terminals) >= 2 {
						mylogrus.MyLog.Infof("%d on-line users found", len(*terminals))
					}
				}
			}
		}
	}()

	// 初始化协程chan
	kickChan = make(chan KickChanMsg, kickChanSize)
	broadcastChan = make(chan BroadcastChanMsg, broadcastChanSize)
hujiebin's avatar
hujiebin committed
658
	areacastChan = make(chan AreaChanMsg, areacastChanSize)
hujiebin's avatar
hujiebin committed
659
	levelcastChan = make(chan LevelChanMsg, levelcastChanSize)
hujiebin's avatar
hujiebin committed
660 661 662 663 664 665 666 667 668 669 670
	go check() // 检查长度
	for i := 0; i < kickChanSize; i++ {
		go func(n int) {
			kick(n)
		}(i)
	}
	for i := 0; i < broadcastChanSize; i++ {
		go func(n int) {
			broadcast(n)
		}(i)
	}
hujiebin's avatar
hujiebin committed
671 672 673 674 675
	for i := 0; i < areacastChanSize; i++ {
		go func(n int) {
			areacast(n)
		}(i)
	}
hujiebin's avatar
hujiebin committed
676 677 678 679 680
	for i := 0; i < levelcastChanSize; i++ {
		go func(n int) {
			levelcast(n)
		}(i)
	}
hujiebin's avatar
hujiebin committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717

	fmt.Println("Go RPC listening on ", port)
	lis, err := net.Listen("tcp4", ":"+strconv.Itoa(port))
	if err != nil {
		mylogrus.MyLog.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer(grpc.KeepaliveParams(kasp))
	userCenter.RegisterUserServer(s, &server{})
	if err := s.Serve(lis); err != nil {
		mylogrus.MyLog.Fatalf("failed to serve: %v", err)
	}
}

func kick(n int) {
	for msg := range kickChan {
		mylogrus.MyLog.Infof("handling kick in:%d,msg:%+v", n, msg)
		clientAddr := termManager.GetTerminal(msg.userId)
		if clientAddr == nil {
			mylogrus.MyLog.Errorf("No terminal found for %d", msg.userId)
		} else {
			client := manager.UserProxyMgr.GetClient(msg.proxyAddr)
			if client == nil {
				mylogrus.MyLog.Errorf("No userProxy found for %d, %s\n", msg.userId, msg.proxyAddr)
			} else {
				toRouterClient := userCenter.NewRouterClient(client)
				in := &userCenter.KickMessage{Uid: msg.userId, Addr: *clientAddr}
				if err := sendKickMessage(toRouterClient, in); err != nil {
					mylogrus.MyLog.Errorf("sendKickMessage fail,uid:%v,proxyAddr:%v,clientAddr:%v,err:%v",
						msg.userId, msg.proxyAddr, clientAddr, err)
				}
			}
		}
	}
}

func broadcast(n int) {
	for msg := range broadcastChan {
hujiebin's avatar
hujiebin committed
718
		//mylogrus.MyLog.Infof("handling broadcast in:%d,msg:%+v", n, msg)
hujiebin's avatar
hujiebin committed
719 720 721 722
		realBroadcast(msg.ProxyAddr, msg.UserIds, msg.in) // fixme: 这里还有优化空间,广播能否在proxy层做批量
	}
}

hujiebin's avatar
hujiebin committed
723 724 725 726 727 728
func areacast(n int) {
	for msg := range areacastChan {
		realAreacast(msg.ProxyAddr, msg.UserIds, msg.in)
	}
}

hujiebin's avatar
hujiebin committed
729 730 731 732 733 734
func levelcast(n int) {
	for msg := range levelcastChan {
		realLevelcast(msg.ProxyAddr, msg.UserIds, msg.in)
	}
}

hujiebin's avatar
hujiebin committed
735 736 737 738 739 740 741 742 743 744
var lastDingTime time.Time
var dingIntervalMin float64 = 5 // 5min 告警间隔

func check() {
	lastDingTime = time.Now()
	tick := time.NewTicker(time.Second * 3)
	defer tick.Stop()
	for {
		select {
		case <-tick.C:
hujiebin's avatar
hujiebin committed
745 746
			l, l2, l3, l4 := len(kickChan), len(broadcastChan), len(areacastChan), len(levelcastChan)
			if l >= monitorLength || l2 >= monitorLength || l3 >= monitorLength || l4 >= monitorLength {
hujiebin's avatar
hujiebin committed
747 748
				if time.Now().Sub(lastDingTime).Minutes() > dingIntervalMin {
					go func() {
hujiebin's avatar
hujiebin committed
749 750
						if sErr := dingding.SendDingRobot(dingding.ROBOTWEBHOOK, fmt.Sprintf("userCenter通知延迟,队列长度:kickChan:%d,broadcastChan:%d,areacastChan:%d,levelcastChan:%d",
							l, l2, l3, l4), true); sErr != nil {
hujiebin's avatar
hujiebin committed
751 752 753 754 755 756 757 758 759 760 761 762 763
							mylogrus.MyLog.Errorf("dingding msg fail:%v", sErr)
						} else {
							lastDingTime = time.Now()
						}
					}()
				}
			}
			if l > 0 || l2 > 0 {
				mylogrus.MyLog.Infof("userCenter msg,left kick:%v,broadcast:%v", l, l2)
			}
		}
	}
}