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

import (
	"context"
hujiebin's avatar
hujiebin committed
5
	"errors"
hujiebin's avatar
hujiebin committed
6 7
	"flag"
	"fmt"
hujiebin's avatar
hujiebin committed
8
	"github.com/golang/protobuf/proto"
hujiebin's avatar
hujiebin committed
9
	"gorm.io/gorm/schema"
hujiebin's avatar
hujiebin committed
10 11 12 13 14 15 16 17 18 19 20 21 22
	"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
23
	appConfig "hilo-userCenter/common/config"
hujiebin's avatar
hujiebin committed
24 25 26 27 28 29 30 31
	"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
32 33
	port          = 50040
	redis_section = 1
hujiebin's avatar
hujiebin committed
34 35 36 37
)

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

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

type KickChanMsg struct {
	userId    uint64
	proxyAddr string
}

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

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

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

hujiebin's avatar
hujiebin committed
75 76 77
var (
	userManager *manager.UserManager     = nil
	termManager *manager.TerminalManager = nil
hujiebin's avatar
hujiebin committed
78
	roomManager *manager.RoomManager     = nil
hujiebin's avatar
hujiebin committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
)

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) {
hujiebin's avatar
hujiebin committed
94
	//mylogrus.MyLog.Infof("Received loginMsg: %s, from proxy %s, client %s\n", in.Token, in.ProxyAddr, in.ClientAddr)
hujiebin's avatar
hujiebin committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

	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 {
hujiebin's avatar
hujiebin committed
111
			//mylogrus.MyLog.Infof("%d has existing value %s", claim.UserId, *proxyAddr)
hujiebin's avatar
hujiebin committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
			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)
		}
hujiebin's avatar
hujiebin committed
132
		//mylogrus.MyLog.Infof("adding user %d", claim.UserId)
hujiebin's avatar
hujiebin committed
133 134 135 136 137 138 139 140 141 142 143 144

		// 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
145
	//mylogrus.MyLog.Infof("Received logoutMsg: %s, %d\n", in.GetClientAddr(), in.GetUid())
hujiebin's avatar
hujiebin committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

	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
171
	//mylogrus.MyLog.Infof("Multicasting msgType = %d to %v, size = %d\n", in.MsgType, in.Uids, len(in.PayLoad))
hujiebin's avatar
hujiebin committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

	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)
		}
	}
hujiebin's avatar
hujiebin committed
195 196 197
	//if len(failed) > 0 {
	//mylogrus.MyLog.Infof("Multicast failed for %v\n", failed)
	//}
hujiebin's avatar
hujiebin committed
198 199 200
	return &userCenter.MulticastMessageRsp{FailedUids: failed}, nil
}

hujiebin's avatar
hujiebin committed
201
func (s *server) BroadcastOld(ctx context.Context, in *userCenter.BroadcastMessage) (*userCenter.BroadcastMessageRsp, error) {
hujiebin's avatar
hujiebin committed
202
	//mylogrus.MyLog.Infof("Broadcasting msgType = %d, size = %d\n", in.MsgType, len(in.PayLoad))
hujiebin's avatar
hujiebin committed
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 229 230

	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
231 232 233 234
			//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
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

			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
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
func (s *server) Broadcast(ctx context.Context, in *userCenter.BroadcastMessage) (*userCenter.BroadcastMessageRsp, error) {
	redisKey := "service:userSocket"
	ipPorts, err := rdbCluster.ZRangeByScore(context.Background(), redisKey, &redis.ZRangeBy{
		Min: fmt.Sprintf("%d", time.Now().Add(-time.Second*15).Unix()), // 3倍心跳
		Max: "+inf",
	}).Result()
	if err != nil {
		failMsg := fmt.Sprintf("get service fail,svc:%v,err:%v", "userSocket", err)
		mylogrus.MyLog.Errorf(failMsg)
		_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
		return nil, err
	}
	if len(ipPorts) <= 0 {
		failMsg := fmt.Sprintf("get service empty,svc:%v,err:%v", "userSocket", err)
		mylogrus.MyLog.Errorf(failMsg)
		_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
		return nil, errors.New(failMsg)
	}
	data, _ := proto.Marshal(in)
	for _, ip := range ipPorts {
		queue := "broadcast:" + ip
		rdbCluster.RPush(context.Background(), queue, data)
	}
	return &userCenter.BroadcastMessageRsp{FailedUids: nil}, nil
}

hujiebin's avatar
hujiebin committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
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
330 331 332 333 334 335 336 337 338 339
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)
			}
		}
340 341
		// 处理等级用户
		levelUserIds, userIds := userManager.GetLevelUsers(uids, in.Level)
hujiebin's avatar
hujiebin committed
342 343 344
		if len(levelUserIds) <= 0 {
			return &userCenter.LevelMessageRsp{FailedUids: failed}, nil
		}
345 346 347 348 349 350 351
		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
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
		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
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
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
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
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
443
func realBroadcast(addr string, uids []uint64, msg *userCenter.BroadcastMessage) {
hujiebin's avatar
hujiebin committed
444
	//mylogrus.MyLog.Infof("Broadcasting: Addr %s: users: %v", addr, uids)
hujiebin's avatar
hujiebin committed
445 446 447 448 449 450 451 452 453

	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
454 455 456
			if err != nil {
				mylogrus.MyLog.Errorf("routeMessage uid = %d, msgType = %d, status = %d, %v", uid, msg.MsgType, status, err)
			}
hujiebin's avatar
hujiebin committed
457 458 459 460
		}
	}
}

hujiebin's avatar
hujiebin committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
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
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
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
493 494 495 496 497 498 499 500 501 502 503
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
504
		//mylogrus.MyLog.Infof("Route message to user %d, status = %d", uid, r.Status)
hujiebin's avatar
hujiebin committed
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
		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 {
hujiebin's avatar
hujiebin committed
527
	//mylogrus.MyLog.Infof("sendKickMessage %s", msg.String())
hujiebin's avatar
hujiebin committed
528 529 530 531 532 533 534 535 536 537 538 539 540
	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
541 542 543 544
func RegisterToRedis(RedisClusterClient *redis.Client, port int, init bool) {
	// 本地不注册
	if appConfig.AppIsLocal() {
		return
hujiebin's avatar
hujiebin committed
545
	}
hujiebin's avatar
hujiebin committed
546 547 548 549 550
	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
551
	}
hujiebin's avatar
hujiebin committed
552 553
	redisKey := "service:" + RegisterName
	ip, err := common.GetClientIpV2()
hujiebin's avatar
hujiebin committed
554
	if err != nil {
hujiebin's avatar
hujiebin committed
555 556 557 558
		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
559
	}
hujiebin's avatar
hujiebin committed
560 561 562 563 564 565 566 567
	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
568
	}
hujiebin's avatar
hujiebin committed
569 570 571 572 573 574 575 576 577 578
	// 初始化注册自我检查 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
579
			}
hujiebin's avatar
hujiebin committed
580
		}()
hujiebin's avatar
hujiebin committed
581 582 583
	}
}

hujiebin's avatar
hujiebin committed
584
type HiloConfigs struct {
hujiebin's avatar
hujiebin committed
585 586 587 588
	Name  string `gorm:"primary_key"`
	Value string
}

hujiebin's avatar
hujiebin committed
589 590
var rdbCluster *redis.Client

hujiebin's avatar
hujiebin committed
591 592 593
func main() {
	flag.Parse()

hujiebin's avatar
hujiebin committed
594
	// init redis cluster
hujiebin's avatar
hujiebin committed
595
	rdbCluster = redis.NewClient(&redis.Options{
hujiebin's avatar
hujiebin committed
596 597 598 599 600
		Addr:     appConfig.GetConfigRedis().REDIS_CLUSTER_HOST,
		Password: appConfig.GetConfigRedis().REDIS_CLUSTER_PASSWORD,
	})
	// 注册到redis
	RegisterToRedis(rdbCluster, port, true)
hujiebin's avatar
hujiebin committed
601 602 603

	// init redis
	rdb := redis.NewClient(&redis.Options{
hujiebin's avatar
hujiebin committed
604 605
		Addr:     appConfig.GetConfigRedis().REDIS_HOST,
		Password: appConfig.GetConfigRedis().REDIS_PASSWORD,
hujiebin's avatar
hujiebin committed
606 607 608
		DB:       redis_section,
	})
	if rdb == nil {
hujiebin's avatar
hujiebin committed
609
		mylogrus.MyLog.Fatalf("failed to connect redis %s\n", appConfig.GetConfigRedis().REDIS_HOST)
hujiebin's avatar
hujiebin committed
610 611 612 613 614 615 616 617 618 619 620 621
	}
	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
622
	dsn := appConfig.GetConfigMysql().MYSQL_USERNAME + ":" + appConfig.GetConfigMysql().MYSQL_PASSWORD + "@(" + appConfig.GetConfigMysql().MYSQL_HOST + ")/" + appConfig.GetConfigMysql().MYSQL_DB
hujiebin's avatar
hujiebin committed
623 624
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
hujiebin's avatar
hujiebin committed
625 626 627
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
hujiebin's avatar
hujiebin committed
628 629 630 631 632 633 634
	})
	if err != nil {
		mylogrus.MyLog.Fatal("mysql connect error %v", err)
	} else {
		mylogrus.MyLog.Infof("mysql connect success")
	}

hujiebin's avatar
hujiebin committed
635
	var jwtConfig = HiloConfigs{}
hujiebin's avatar
hujiebin committed
636 637 638 639 640 641 642 643 644 645
	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
646
		MysqlDB:     db,
hujiebin's avatar
hujiebin committed
647
	}
hujiebin's avatar
hujiebin committed
648 649 650 651 652 653 654
	go func() {
		for {
			// 同步区域
			userManager.SyncArea()
			time.Sleep(time.Minute * 15)
		}
	}()
hujiebin's avatar
hujiebin committed
655 656 657 658
	termManager = &manager.TerminalManager{
		Ctx:         context.Background(),
		RedisClient: rdb,
	}
hujiebin's avatar
hujiebin committed
659 660 661 662
	roomManager = &manager.RoomManager{
		Ctx:         context.Background(),
		RedisClient: rdb,
	}
hujiebin's avatar
hujiebin committed
663 664 665 666 667 668 669

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

		for {
			select {
hujiebin's avatar
hujiebin committed
670 671
			case <-ticker.C:
				//mylogrus.MyLog.Infof("Tick at %s", a.String())
hujiebin's avatar
hujiebin committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
				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
688
	areacastChan = make(chan AreaChanMsg, areacastChanSize)
hujiebin's avatar
hujiebin committed
689
	levelcastChan = make(chan LevelChanMsg, levelcastChanSize)
hujiebin's avatar
hujiebin committed
690 691 692 693 694 695 696 697 698 699 700
	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
701 702 703 704 705
	for i := 0; i < areacastChanSize; i++ {
		go func(n int) {
			areacast(n)
		}(i)
	}
hujiebin's avatar
hujiebin committed
706 707 708 709 710
	for i := 0; i < levelcastChanSize; i++ {
		go func(n int) {
			levelcast(n)
		}(i)
	}
hujiebin's avatar
hujiebin committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725

	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 {
hujiebin's avatar
hujiebin committed
726
		//mylogrus.MyLog.Infof("handling kick in:%d,msg:%+v", n, msg)
hujiebin's avatar
hujiebin committed
727 728
		clientAddr := termManager.GetTerminal(msg.userId)
		if clientAddr == nil {
hujiebin's avatar
hujiebin committed
729
			//mylogrus.MyLog.Errorf("No terminal found for %d", msg.userId)
hujiebin's avatar
hujiebin committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
		} 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
748
		//mylogrus.MyLog.Infof("handling broadcast in:%d,msg:%+v", n, msg)
hujiebin's avatar
hujiebin committed
749 750 751 752
		realBroadcast(msg.ProxyAddr, msg.UserIds, msg.in) // fixme: 这里还有优化空间,广播能否在proxy层做批量
	}
}

hujiebin's avatar
hujiebin committed
753 754 755 756 757 758
func areacast(n int) {
	for msg := range areacastChan {
		realAreacast(msg.ProxyAddr, msg.UserIds, msg.in)
	}
}

hujiebin's avatar
hujiebin committed
759 760 761 762 763 764
func levelcast(n int) {
	for msg := range levelcastChan {
		realLevelcast(msg.ProxyAddr, msg.UserIds, msg.in)
	}
}

hujiebin's avatar
hujiebin committed
765 766 767 768 769 770 771 772 773 774
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
775 776
			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
777 778
				if time.Now().Sub(lastDingTime).Minutes() > dingIntervalMin {
					go func() {
hujiebin's avatar
hujiebin committed
779 780
						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
781 782 783 784 785 786 787 788 789 790 791 792 793
							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)
			}
		}
	}
}