main.go 22.8 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
	"github.com/go-redis/redis/v8"
hujiebin's avatar
hujiebin committed
8
	"hilo-userProxy/common"
hujiebin's avatar
hujiebin committed
9
	"hilo-userProxy/common/config"
hujiebin's avatar
hujiebin committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
	"net"
	"net/http"
	_ "net/http/pprof"
	"runtime/debug"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"hilo-userProxy/common/mylogrus"
	"hilo-userProxy/protocol/userCenter"
	"hilo-userProxy/protocol/userProxy"

	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	uuid "github.com/satori/go.uuid"
	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/peer"
	"google.golang.org/grpc/resolver"
)

// 序号号,一个进程一个
var serialNum uint64 = 0

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin:     checkOrigin,
}

type ProtoData struct {
	MsgType uint32
	Data    []byte
}

var myAddress = ""
var m sync.RWMutex
var userChan = make(map[uint64]map[string]chan ProtoData)

/*  其中CheckOringin是一个函数,该函数用于拦截或放行跨域请求。函数返回值为bool类型,即true放行,false拦截。
如果请求不是跨域请求可以不赋值,我这里是跨域请求并且为了方便直接返回true
*/
func checkOrigin(r *http.Request) bool {
	return true
}

const (
	notLoginLimit      = 10.0
	heartBeatLossLimit = 30.0
)

type ConnectionInfo struct {
	RemoteAddr    string `json:"remote_addr"`
	ConnectTime   time.Time
	HeartbeatTime time.Time
	IsLogin       bool
	Uid           uint64 `json:"uid"`
	MsgId         uint64 `json:"msg_id"`
	ExternalId    string `json:"external_id"`
	Token         string `json:"token"`
}

func setupRoutes() {
	http.HandleFunc("/", homePage)
	http.HandleFunc("/ws", serverWebsocket)
}

func getShortToken(token string) string {
	s := strings.Split(token, ".")
	if len(s) == 0 {
		return token
	} else {
		return s[len(s)-1]
	}
}
hujiebin's avatar
hujiebin committed
88

hujiebin's avatar
hujiebin committed
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 143 144 145 146 147 148 149 150 151 152 153 154 155
func serverWebsocket(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		mylogrus.MyLog.Errorf("upgrade err:%v", err)
		return
	}

	now := time.Now()
	ci := ConnectionInfo{
		RemoteAddr:    ws.RemoteAddr().String(),
		ConnectTime:   now,
		HeartbeatTime: now,
		IsLogin:       false,
		Uid:           0,
		MsgId:         0,
		ExternalId:    "",
		Token:         "",
	}
	traceId := uuid.NewV4().String()
	logger := mylogrus.MyLog.WithFields(log.Fields{
		"addr":    ci.RemoteAddr,
		"token":   ci.Token,
		"traceId": traceId,
	})
	logger.Infof("Websocket client successfully Connected at %s", ci.ConnectTime.String())

	done := make(chan struct{})
	writeChan := make(chan ProtoData, 1000)

	ticker := time.NewTicker(time.Second * 2)
	defer ticker.Stop()

	go func() {
		defer common.CheckGoPanic()
		defer ws.Close()
		defer close(done)
		//defer close(writeChan) // 读断了就把写也断了
		for {
			messageType, message, err := ws.ReadMessage()
			if err != nil {
				logger.Infof("read error:%v", err)
				logger = logger.WithFields(log.Fields{
					"read_err": err.Error(),
				})
				break
			}

			if messageType != websocket.BinaryMessage {
				logger.Errorf("Unexpected messageType %d", messageType)
				continue
			}

			msgType, msgId, timeStamp, pbData, err := common.DecodeMessage(message)
			if err != nil {
				logger.Errorf("Decode error %s", err.Error())
				continue
			}

			if msgId <= ci.MsgId {
				logger.Infof("Discard outdated message msgId = %d <= %d, msgType = %d", msgId, ci.MsgId, msgType)
			} else {
				ci.MsgId = msgId

				// 统计时延
				now := time.Now()
				us := now.UnixNano()/1000 - int64(timeStamp)
				if us > 200000 {
hujiebin's avatar
hujiebin committed
156
					//logger.Infof("Message take %d us to come here.", us)
hujiebin's avatar
hujiebin committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
				}

				if msgType == common.MsgTypeLogin {
					if ci.IsLogin {
						logger.Infof("Connection already logged in %+v", ci)
					} else {
						var rsp *userProxy.LoginRsp
						ci.Token, ci.Uid, rsp, err = processLogin(logger, ci.RemoteAddr, pbData)
						if err == nil && rsp != nil {
							logger = logger.WithFields(log.Fields{
								"addr":   ci.RemoteAddr,
								"userId": ci.Uid,
								"sToken": getShortToken(ci.Token),
							})

							if buffer, err := proto.Marshal(rsp); err == nil {
								writeChan <- ProtoData{
									MsgType: common.MsgTypeLoginRsp,
									Data:    buffer,
								}
							}
							if rsp.Status == common.Login_success {
								ci.IsLogin = true
								ci.HeartbeatTime = now

hujiebin's avatar
hujiebin committed
182
								//logger.Infof("Bind to channel %v", writeChan)
hujiebin's avatar
hujiebin committed
183 184 185 186 187 188
								setUserChan(ci.Uid, ci.RemoteAddr, writeChan)
							}
						}
					}
				} else if msgType == common.MsgTypeHeartBeat {
					status, extUid, err := processHeartBeat(pbData)
hujiebin's avatar
hujiebin committed
189
					//logger.Infof("heartbeat")
hujiebin's avatar
hujiebin committed
190 191 192
					if err == nil {
						ci.HeartbeatTime = time.Now()
						if len(ci.ExternalId) == 0 {
hujiebin's avatar
hujiebin committed
193
							//logger.Infof("Received first heartbeat")
hujiebin's avatar
hujiebin committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

							ci.ExternalId = extUid

							logger = logger.WithFields(log.Fields{
								"addr":       ci.RemoteAddr,
								"userId":     ci.Uid,
								"sToken":     getShortToken(ci.Token),
								"externalId": ci.ExternalId,
							})
						}
						msg := &userProxy.HeartBeatRsp{
							Status: status,
						}
						if buffer, err := proto.Marshal(msg); err == nil {
							writeChan <- ProtoData{
								MsgType: common.MsgTypeHeartBeatRsp,
								Data:    buffer,
							}
						}
					}
				} else if msgType == common.MsgTypeGlobalGiftBannerRsp {
					logger = logger.WithFields(log.Fields{
						"addr":       ci.RemoteAddr,
						"userId":     ci.Uid,
						"sToken":     getShortToken(ci.Token),
						"externalId": ci.ExternalId,
					})
					rsp := &userProxy.GlobalGiftBannerRsp{}
					err := proto.Unmarshal(pbData, rsp)
					if err == nil {
hujiebin's avatar
hujiebin committed
224
						//logger.Infof("GlobalGiftBannerRsp, msgType = %d, %v", msgType, rsp)
hujiebin's avatar
hujiebin committed
225 226 227 228 229 230 231 232 233 234
					} else {
						logger.Errorf("Unmarshal error")
					}
				} else if msgType == common.MsgTypeBiz {
					logger = logger.WithFields(log.Fields{
						"addr":   ci.RemoteAddr,
						"userId": ci.Uid,
					})
					rsp, err := processBizRequest(logger, ci.Uid, pbData)
					if err == nil && rsp != nil {
hujiebin's avatar
hujiebin committed
235
						//logger.Infof("processBizRequest rsp %+v", rsp)
hujiebin's avatar
hujiebin committed
236 237 238 239 240 241 242 243

						if buffer, err := proto.Marshal(rsp); err == nil {
							writeChan <- ProtoData{
								MsgType: common.MsgTypeBizRsp,
								Data:    buffer,
							}
						}
					}
hujiebin's avatar
hujiebin committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
				} else if msgType == common.MsgTypeEnterRoom {
					if err := processEnterRoom(logger, ci.Uid, pbData); err != nil {
						logger.Errorf("processEnterRoom fail:%v", err)
					}
				} else if msgType == common.MsgTypeLeaveRoom {
					if err := processLeaveRoom(logger, ci.Uid, pbData); err != nil {
						logger.Errorf("processLeaveRoom fail:%v", err)
					}
				} else if msgType == common.MsgTypeRoomHeartbeat {
					if err := processRoomHeartbeat(logger, ci.Uid, pbData); err != nil {
						logger.Errorf("processRoomHeartbeat fail:%v", err)
					}
				} else if msgType == common.MsgTypeGroupMicChangeRsp {
					if err := processGroupMicChangeRsp(logger, ci.Uid, pbData); err != nil {
						logger.Errorf("processGroupMicChangeRsp fail:%v", err)
					}
hujiebin's avatar
hujiebin committed
260 261 262 263 264 265 266 267 268 269
				} else {
					logger.Warnf("Unknown message type %d", msgType)
				}

				if err != nil {
					logger.Infof("process message error %s", err.Error())
				}
			}
		}
		logger.Infof("exiting read loop for token %s, user %d", ci.Token, ci.Uid)
hujiebin's avatar
hujiebin committed
270
		removeUserChan(ci.Uid, ci.RemoteAddr)
hujiebin's avatar
hujiebin committed
271

hujiebin's avatar
hujiebin committed
272 273
		//b, _ := json.Marshal(ci)
		//logger.Infof("exiting read loop for %s, size = %d", string(b), sz)
hujiebin's avatar
hujiebin committed
274 275

		if ci.IsLogin {
hujiebin's avatar
hujiebin committed
276
			err, _ := doLogout(ci.RemoteAddr, ci.Uid)
hujiebin's avatar
hujiebin committed
277
			if err == nil {
hujiebin's avatar
hujiebin committed
278
				//logger.Printf("logout result %d", status)
hujiebin's avatar
hujiebin committed
279 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 330 331 332 333 334 335 336 337 338 339 340 341 342 343
			} else {
				logger.Printf("Logout failed, %s", err.Error())
			}
			ci.IsLogin = false
		}
	}()

Loop:
	for {
		select {
		case <-done:
			break Loop
		case <-ticker.C:
			timeDiff := time.Since(ci.HeartbeatTime)
			if ci.IsLogin {
				if timeDiff.Seconds() > heartBeatLossLimit/2 {
					logger.Infof("Heartbeat lost for %f seconds", timeDiff.Seconds())
				}

				if timeDiff.Seconds() > heartBeatLossLimit {
					logger.Warnln("Heartbeat lost, terminate!")

					err := ws.WriteControl(websocket.CloseMessage,
						websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "heartbeat loss"),
						time.Now().Add(time.Second))
					if err != nil {
						logger.Println("write close:", err)
					}
					ws.Close()
					break Loop
				}
			} else {
				if timeDiff.Seconds() > notLoginLimit {
					logger.Infof("Not loggined for %f seconds, kick!", timeDiff.Seconds())

					err := ws.WriteControl(websocket.CloseMessage,
						websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "no login"),
						time.Now().Add(time.Second))
					if err != nil {
						logger.Println("write close:", err)
					}
					_ = ws.Close()
					break Loop
				}
			}
		case d := <-writeChan:
			if d.MsgType == common.MsgTypeKickUser {
				// 特殊消息,用于踢走用户
				logger.Infof("Login from another device, kick!")

				// 取消登录态,避免readloop结束时发logout消息,把新记录也清了
				ci.IsLogin = false

				err := ws.WriteControl(websocket.CloseMessage,
					websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "double login"),
					time.Now().Add(time.Second*3))
				if err != nil {
					logger.Println("write close:", err)
					break
				}
				_ = ws.Close()
				break Loop
			}

			atomic.AddUint64(&serialNum, 1)
hujiebin's avatar
hujiebin committed
344
			//logger.Infof("About to send msgType = %d, size = %d", d.MsgType, len(d.Data))
hujiebin's avatar
hujiebin committed
345 346 347 348 349 350 351
			data := common.EncodeMessage(d.MsgType, serialNum, d.Data)
			err = ws.WriteMessage(websocket.BinaryMessage, data)
			if err != nil {
				logger.Println("write close:", err)
			}
		}
	}
hujiebin's avatar
hujiebin committed
352 353
	//b, _ := json.Marshal(ci)
	//logger.Infof("exiting write loop:%s", string(b))
hujiebin's avatar
hujiebin committed
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 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 415 416 417 418 419
}

func processLogin(logger *log.Entry, clientAddr string, pbData []byte) (string, uint64, *userProxy.LoginRsp, error) {
	rsp := &userProxy.LoginRsp{}
	//logger := log.WithFields(log.Fields{
	//	"addr": clientAddr,
	//})

	loginMsg := &userProxy.Login{}
	var loginUid uint64 = 0
	err := proto.Unmarshal(pbData, loginMsg)

	if err == nil {
		logger := logger.WithFields(log.Fields{
			"addr":  clientAddr,
			"token": loginMsg.Token,
		})
		logger.Info(loginMsg.String())

		err, rsp.Status, loginUid = doLogin(loginMsg.Token, clientAddr)
		if err == nil {
			logger.Infof("login status = %d, uid = %d,proxyAddr:%s,clientAddr:%s", rsp.Status, loginUid, myAddress, clientAddr)
		} else {
			logger.Warnf("login RPC failed for %d, %v", rsp.Status, err)
		}
		return loginMsg.Token, loginUid, rsp, err
	} else {
		logger.Warn("unmarshal error")
		return loginMsg.Token, 0, rsp, err
	}
}

func processHeartBeat(pbData []byte) (uint32, string, error) {
	heartBeat := &userProxy.HeartBeat{}
	err := proto.Unmarshal(pbData, heartBeat)
	if err == nil {
		// FIXME: 增加heartbeat过频控制
		return 0, heartBeat.ExternalUid, err
	}
	return 0, "", err
}

func processBizRequest(logger *log.Entry, uid uint64, pbData []byte) (*userProxy.BizResponse, error) {
	//logger := log.WithFields(log.Fields{
	//	"uid": uid,
	//})

	rsp := &userProxy.BizResponse{}

	msg := &userProxy.BizRequest{}
	err := proto.Unmarshal(pbData, msg)

	if err == nil {
		logger.Infof("doBizRequest msgType = %d, msg: %s", msg.Type, msg.PayLoad)

		rsp.Status, err = doBizRequest(uid, msg.Type, msg.PayLoad)
		if err != nil {
			logger.Warnf("doBizRequest RPC failed for %d, %v, uid = %d", uid, rsp.Status, err)
		}
		return rsp, err
	} else {
		logger.Warn("unmarshal error")
		return rsp, err
	}
}

hujiebin's avatar
hujiebin committed
420 421 422 423 424 425
func processEnterRoom(logger *log.Entry, uid uint64, pbData []byte) error {
	msg := &userProxy.EnterRoom{}
	err := proto.Unmarshal(pbData, msg)
	if err == nil {
		err, status := doEnterRoom(uid, msg.GroupId)
		if err == nil && status == common.Login_success {
hujiebin's avatar
hujiebin committed
426
			//logger.Infof("enter room success,uid:%v,group:%v", uid, msg.GroupId)
hujiebin's avatar
hujiebin committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
		} else {
			logger.Warnf("login RPC failed for %d, %v", status, err)
		}
		return err
	} else {
		return err
	}
}

func processLeaveRoom(logger *log.Entry, uid uint64, pbData []byte) error {
	msg := &userProxy.LeaveRoom{}
	err := proto.Unmarshal(pbData, msg)
	if err == nil {
		err, status := doLeaveRoom(uid, msg.GroupId)
		if err == nil && status == common.Login_success {
hujiebin's avatar
hujiebin committed
442
			//logger.Infof("leave room success,uid:%v,group:%v", uid, msg.GroupId)
hujiebin's avatar
hujiebin committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
		} else {
			logger.Warnf("login RPC failed for %d, %v", status, err)
		}
		return err
	} else {
		return err
	}
}

func processRoomHeartbeat(logger *log.Entry, uid uint64, pbData []byte) error {
	msg := &userProxy.RoomHeartBeat{}
	err := proto.Unmarshal(pbData, msg)
	if err == nil {
		err, status := doRoomHeartbeat(uid, msg.GroupId)
		if err == nil && status == common.Login_success {
hujiebin's avatar
hujiebin committed
458
			//logger.Infof("room heartbeat success,uid:%v,group:%v", uid, msg.GroupId)
hujiebin's avatar
hujiebin committed
459 460 461 462 463 464 465 466 467 468 469 470 471
		} else {
			logger.Warnf("login RPC failed for %d, %v", status, err)
		}
		return err
	} else {
		return err
	}
}

func processGroupMicChangeRsp(logger *log.Entry, uid uint64, pbData []byte) error {
	msg := &userProxy.GroupMicChangeRsp{}
	err := proto.Unmarshal(pbData, msg)
	if err == nil {
hujiebin's avatar
hujiebin committed
472
		//logger.Infof("groupMicChangeRsp,uid:%v,seqId:%v", uid, msg.SeqId)
hujiebin's avatar
hujiebin committed
473 474 475 476 477 478
	} else {
		return err
	}
	return err
}

hujiebin's avatar
hujiebin committed
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 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
// 直接发匹配成功消息,调试用
func homePage(w http.ResponseWriter, r *http.Request) {
	rsp := "Home Page"
	var targetUserId uint64 = 0
	fromUserId := ""
	toUserId := ""
	if r.ParseForm() == nil {
		targetUserId, _ = strconv.ParseUint(r.FormValue("target"), 10, 64)
		fromUserId = r.FormValue("from")
		toUserId = r.FormValue("to")
	}

	if targetUserId == 0 || len(fromUserId) == 0 || len(toUserId) == 0 {
		rsp = "targetUserId or fromUserId or toUserId is missing."
	} else {
		m := getChans(targetUserId)
		if m == nil {
			rsp = "User not found"
		} else {
			for i, c := range m {
				rsp += fmt.Sprintf("address %d bound to channel %v", i, c)
			}
		}
	}
	fmt.Fprint(w, rsp)
}

func setUserChan(uid uint64, addr string, c chan ProtoData) {
	m.Lock()
	defer m.Unlock()
	if userChan[uid] == nil {
		userChan[uid] = make(map[string]chan ProtoData)
	}
	userChan[uid][addr] = c
}

func getUserChan(uid uint64, addr string) chan ProtoData {
	m.RLock()
	defer m.RUnlock()
	if userChan[uid] == nil {
		return nil
	} else {
		return userChan[uid][addr]
	}
}

func getChans(uid uint64) map[string]chan ProtoData {
	m.RLock()
	defer m.RUnlock()
	return userChan[uid]
}

func removeUserChan(uid uint64, addr string) int {
	m.Lock()
	defer m.Unlock()
	if chs, ok := userChan[uid]; ok {
		delete(chs, addr)
		if len(chs) == 0 {
			delete(userChan, uid)
		}
	}
	return len(userChan)
}

const (
	rpcListenPortBase = 50050
)

type server struct {
	userCenter.UnimplementedRouterServer
}

func (s *server) Route(ctx context.Context, in *userCenter.RouteMessage) (*userCenter.RouteMessageRsp, error) {
	defer func() {
		if r := recover(); r != nil {
			//打印错误堆栈信息
			mylogrus.MyLog.Errorf("Route SYSTEM ACTION PANIC: %v, stack: %v", r, string(debug.Stack()))
		}
	}()
558 559 560
	//peerInfo, _ := peer.FromContext(ctx)
	//mylogrus.MyLog.Infof("Received Route request from %s: msgType = %d, uid = %d, payload size = %d",
	//	peerInfo.Addr.String(), in.GetMsgType(), in.GetUid(), len(in.GetPayLoad()))
hujiebin's avatar
hujiebin committed
561 562 563 564

	var status uint32 = common.ROUTE_SUCCESS
	m := getChans(in.GetUid())
	if len(m) > 0 {
565 566
		for _, c := range m {
			//mylogrus.MyLog.Infof("Route to user %d, addr %s, channel %v", in.Uid, i, c)
hujiebin's avatar
hujiebin committed
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
			c <- ProtoData{
				MsgType: in.GetMsgType(),
				Data:    in.GetPayLoad(),
			}
		}
	} else {
		status = common.ROUTE_CHANNEL_NOT_FOUND
		mylogrus.MyLog.Warnf("No write channel for user %d", in.GetUid())
	}
	return &userCenter.RouteMessageRsp{Status: status}, nil
}

func (s *server) KickUser(ctx context.Context, in *userCenter.KickMessage) (*userCenter.KickMessageRsp, error) {
	peerInfo, _ := peer.FromContext(ctx)
	logger := mylogrus.MyLog.WithFields(log.Fields{
		"uid":  in.Uid,
		"addr": in.Addr,
	})
	logger.Infof("Received KickUser request from %s", peerInfo.Addr.String())

	c := getUserChan(in.Uid, in.Addr)
	if c == nil {
		logger.Infof("No write channel")
	} else {
		c <- ProtoData{
			MsgType: common.MsgTypeKickUser,
		}
	}
	return &userCenter.KickMessageRsp{Status: 0}, nil
}

var userClient userCenter.UserClient

func doLogin(token string, clientAddr string) (error, uint32, uint64) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	r, err := userClient.Login(ctx, &userCenter.LoginMessage{
		Token:      token,
		ProxyAddr:  myAddress,
		ClientAddr: clientAddr,
	})
	if err == nil && r != nil {
		return err, r.Status, r.Uid
	} else {
		return err, 0, 0
	}
}

func doLogout(addr string, uid uint64) (error, uint32) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	r, err := userClient.Logout(ctx, &userCenter.LogoutMessage{
		ClientAddr: addr,
		Uid:        uid,
	})
	if err == nil && r != nil {
		return err, r.Status
	} else {
		return err, 0
	}
}

func doBizRequest(uid uint64, msgType uint32, payLoad string) (uint32, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	r, err := userClient.Transmit(ctx, &userCenter.BizMessage{
		Uid:     uid,
		MsgType: msgType,
		PayLoad: payLoad,
	})
	if err == nil && r != nil {
		return r.Status, err
	} else {
		return 0, err
	}
}

hujiebin's avatar
hujiebin committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
func doEnterRoom(uid uint64, groupId string) (error, uint32) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	r, err := userClient.EnterRoom(ctx, &userCenter.EnterRoomMessage{
		Uid:     uid,
		GroupId: groupId,
	})
	if err == nil && r != nil {
		return err, r.Status
	} else {
		return err, 0
	}
}

func doLeaveRoom(uid uint64, groupId string) (error, uint32) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	r, err := userClient.LeaveRoom(ctx, &userCenter.LeaveRoomMessage{
		Uid:     uid,
		GroupId: groupId,
	})
	if err == nil && r != nil {
		return err, r.Status
	} else {
		return err, 0
	}
}

func doRoomHeartbeat(uid uint64, groupId string) (error, uint32) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()

	r, err := userClient.RoomHeartbeat(ctx, &userCenter.RoomHeartbeatMessage{
		Uid:     uid,
		GroupId: groupId,
	})
	if err == nil && r != nil {
		return err, r.Status
	} else {
		return err, 0
	}
}

hujiebin's avatar
hujiebin committed
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 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
var kacp = keepalive.ClientParameters{
	Time:                10 * time.Second, // send pings every 10 seconds if there is no activity
	Timeout:             time.Second,      // wait 1 second for ping ack before considering the connection dead
	PermitWithoutStream: true,             // send pings even without active streams
}

var (
	defaultUserCenterAddr = "127.0.0.1:50040" // userCenter default addr
	userCenterAddr        = defaultUserCenterAddr
	userCenterConsulName  = "userCenter"
)

// grpc服务发现
type Builder struct {
	addrs map[string][]string

	cc resolver.ClientConn
}

func (b *Builder) Scheme() string {
	return "uc" // userCenter
}

type Resolver struct {
}

func (r Resolver) ResolveNow(options resolver.ResolveNowOptions) {}

func (r Resolver) Close() {}

func (b *Builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
	r := &Resolver{}
	paths := b.addrs[target.URL.Path]
	addrs := make([]resolver.Address, len(paths))
	for i, s := range paths {
		addrs[i] = resolver.Address{Addr: s}
	}
	cc.UpdateState(resolver.State{Addresses: addrs})
	b.cc = cc
	return r, nil
}

func (b *Builder) UpdateState(addrs []string) {
	as := make([]resolver.Address, len(addrs))
	for i, s := range addrs {
		as[i] = resolver.Address{Addr: s}
	}
	b.cc.UpdateState(resolver.State{Addresses: as})
}

var certFile = flag.String("certFile", "ws.faceline.live.pem", "cert file")
var keyFile = flag.String("keyFile", "ws.faceline.live.key", "key file")
var listenPort = flag.String("port", "8081", "listen port")

func main() {
	flag.Parse()

hujiebin's avatar
hujiebin committed
748 749 750 751 752
	// init redis cluster
	rdbCluster := redis.NewClient(&redis.Options{
		Addr:     config.GetConfigRedis().REDIS_CLUSTER_HOST,
		Password: config.GetConfigRedis().REDIS_CLUSTER_PASSWORD,
	})
hujiebin's avatar
hujiebin committed
753 754 755 756 757 758 759

	myLocalIp, err := common.GetClientIpV2()
	if err != nil {
		mylogrus.MyLog.Fatal(err)
	}

	bd := &Builder{addrs: map[string][]string{"/api": {userCenterAddr}}}
hujiebin's avatar
hujiebin committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773
	if rdbCluster != nil {
		redisKey := fmt.Sprintf("service:userCenter")
		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", "userCenter", err)
			mylogrus.MyLog.Errorf(failMsg)
		} else if len(ipPorts) > 0 {
			bd = &Builder{addrs: map[string][]string{"/api": ipPorts}}
			userCenterAddr = "uc:///api"
			mylogrus.MyLog.Infof("userCenterAddr:%v,addr:%v", userCenterAddr, ipPorts)
		}
hujiebin's avatar
hujiebin committed
774 775 776 777
	}
	// 服务发现
	resolver.Register(bd)
	go func() {
hujiebin's avatar
hujiebin committed
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
		//consul.RegisterWatcher(userCenterConsulName, func(addr []string) {
		//	if len(addr) > 0 {
		//		bd.UpdateState(addr) // 更新新的注册名
		//	}
		//})
		ticker := time.NewTicker(time.Minute)
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				redisKey := fmt.Sprintf("service:userCenter")
				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", "userCenter", err)
					mylogrus.MyLog.Errorf(failMsg)
					break
				}
				if len(ipPorts) <= 0 {
					failMsg := fmt.Sprintf("get service empty,svc:%v,err:%v", "userCenter", err)
					mylogrus.MyLog.Errorf(failMsg)
					break
				} else {
					bd.UpdateState(ipPorts) // 更新新的注册名
				}
hujiebin's avatar
hujiebin committed
805
			}
hujiebin's avatar
hujiebin committed
806
		}
hujiebin's avatar
hujiebin committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	}()

	// Set up a connection to the userCenter.
	conn, err := grpc.Dial(userCenterAddr, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithKeepaliveParams(kacp),
		grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy":"%s"}`, "round_robin")))
	if err != nil {
		mylogrus.MyLog.Fatalf("did not connect: %v", err)
	}
	//defer conn.Close()
	userClient = userCenter.NewUserClient(conn)
	if userClient == nil {
		mylogrus.MyLog.Fatalln("userClient null")
	}

	go func() {
		var i int
		var lis net.Listener
		var err error
		for i = 0; i < 10; i++ {
			addr := ":" + strconv.Itoa(rpcListenPortBase+i)
			lis, err = net.Listen("tcp", addr)
			if err == nil {
				mylogrus.MyLog.Infof("Go RPC listening on %s", lis.Addr().String())
				break
			}
		}
		if i >= 10 {
			mylogrus.MyLog.Fatalln("No RPC Listen port available.")
		}
		myAddress = myLocalIp + ":" + strconv.Itoa(rpcListenPortBase+i)

		mylogrus.MyLog.Infof("My address is %s", myAddress)

		s := grpc.NewServer()
		userCenter.RegisterRouterServer(s, &server{})
		if err := s.Serve(lis); err != nil {
			mylogrus.MyLog.Fatalf("failed to serve: %v", err)
		}
	}()

	setupRoutes()

	addr := ":" + *listenPort
	mylogrus.MyLog.Infof("Go Websocket listening on %s", addr)
	// http ws
	mux := http.NewServeMux()
	mux.HandleFunc("/ws", serverWebsocket)
	go http.ListenAndServe(":8082", mux)

	// https wss
	mylogrus.MyLog.Infof("certFile = %s, keyFile = %s", *certFile, *keyFile)
	mylogrus.MyLog.Printf("%s", http.ListenAndServeTLS(addr, *certFile, *keyFile, nil).Error())
}