Ejemplo n.º 1
0
func (s *Session) Send(msg interface{}, sync ...bool) bool {
	if s.quit || s.shutSend {
		return false
	}
	if len(sync) > 0 && sync[0] {
		select {
		case s.sendBuffer <- msg:
		case <-time.After(time.Duration(s.sc.WriteTimeout)):
			logger.Warn(s.Id, " send buffer full(", len(s.sendBuffer), "),data be droped(asyn), IsInnerLink ", s.sc.IsInnerLink)
			if s.sc.IsInnerLink == false {
				s.Close()
			}
			return false
		}
	} else {
		select {
		case s.sendBuffer <- msg:
		default:
			logger.Warn(s.Id, " send buffer full(", len(s.sendBuffer), "),data be droped(sync), IsInnerLink ", s.sc.IsInnerLink)
			if s.sc.IsInnerLink == false {
				s.Close()
			}
			return false
		}
	}

	return true
}
Ejemplo n.º 2
0
func init() {
	netlib.RegisterFactory(int(protocol.MmoPacketID_PACKET_SC_GATEINFO), netlib.PacketFactoryWrapper(func() interface{} {
		return &protocol.SCGateInfo{}
	}))
	netlib.RegisterHandler(int(protocol.MmoPacketID_PACKET_SC_GATEINFO), netlib.HandlerWrapper(func(s *netlib.Session, pack interface{}) error {
		logger.Trace("receive gateinfo==", pack)
		if sr, ok := pack.(*protocol.SCGateInfo); ok {
			sc := &netlib.SessionConfig{
				Id:           int(sr.GetSrvId()),
				Type:         int(sr.GetSrvType()),
				Ip:           sr.GetIp(),
				Port:         int(sr.GetPort()),
				AuthKey:      sr.GetAuthKey(),
				WriteTimeout: 30,
				ReadTimeout:  30,
				IdleTimeout:  30,
				MaxDone:      20,
				MaxPend:      20,
				MaxPacket:    1024,
				RcvBuff:      1024,
				SndBuff:      1024,
				IsClient:     true,
				NoDelay:      true,
				FilterChain:  []string{"session-filter-trace", "session-filter-auth"},
			}
			sc.Init()
			err := netlib.Connect(core.CoreObject(), sc)
			if err != nil {
				logger.Warn("connect server failed err:", err)
			}
		}
		return nil
	}))
}
Ejemplo n.º 3
0
func (af *AuthenticationFilter) OnPacketReceived(s *netlib.Session, packetid int, packet interface{}) bool {
	if s.GetAttribute(SessionAttributeAuth) == nil {
		if auth, ok := packet.(*protocol.SSPacketAuth); ok {
			h := md5.New()
			rawText := fmt.Sprintf("%v;%v", auth.GetTimestamp(), s.GetSessionConfig().AuthKey)
			logger.Tracef("AuthenticationFilter rawtext=%v IsInnerLink(%v)", rawText, s.GetSessionConfig().IsInnerLink)
			h.Write([]byte(rawText))
			expectKey := hex.EncodeToString(h.Sum(nil))
			if expectKey != auth.GetAuthKey() {
				if af.SessionAuthHandler != nil {
					af.SessionAuthHandler(s, false)
				}
				s.Close()
				logger.Tracef("AuthenticationFilter AuthKey error[expect:%v get:%v]", expectKey, auth.GetAuthKey())
				return false
			}
			s.SetAttribute(SessionAttributeAuth, true)
			if af.SessionAuthHandler != nil {
				af.SessionAuthHandler(s, true)
			}
			return false
		} else {
			s.Close()
			logger.Warn("AuthenticationFilter packet not expect")
			return false
		}
	}
	return true
}
Ejemplo n.º 4
0
func (this *transactCoordinater) createTransNode(tnp *TransNodeParam, ud interface{}, timeout time.Duration) *TransNode {
	if this == nil || tnp == nil {
		logger.Warn("transactCoordinater.createTransNode failed, Null Pointer")
		return nil
	}
	if this.quit {
		logger.Warn("transactCoordinater.createTransNode failed, module shutdowning")
		return nil
	}
	transHandler := GetHandler(tnp.Tt)
	if transHandler == nil {
		logger.Warn("transactCoordinater.createTransNode failed, TransNodeParam=%v", *tnp)
		return nil
	}

	if tnp.TId == TransNodeIDNil {
		tnp.TId = this.spawnTransNodeID()
	}

	if Config.tcs != nil {
		tnp.SkeletonID = Config.tcs.GetSkeletonID()
		tnp.AreaID = Config.tcs.GetAreaID()
	}
	tnp.TimeOut = timeout
	tnode := &TransNode{
		MyTnp:    tnp,
		handler:  transHandler,
		owner:    this,
		TransRep: &TransResult{},
		TransEnv: NewTransCtx(),
		ud:       ud,
	}

	this.addTransNode(tnode)

	if h, ok := timer.StartTimer(tta, tnode, timeout, 1); ok {
		tnode.timeHandle = h
	} else {
		return nil
	}
	return tnode
}
Ejemplo n.º 5
0
func (a *TcpAcceptor) acceptRoutine() {

	a.waitor.Add(1)
	defer a.waitor.Done()

	for !a.quit {
		conn, err := a.listener.Accept()
		if err != nil {
			logger.Warn(err)
			continue
		}
		a.connChan <- conn
	}
}
Ejemplo n.º 6
0
func (this *BroadcastPacketFactory) CreateBroadcastPacket(sp *protocol.BCSessionUnion, data interface{}) proto.Message {
	pack := &protocol.SSPacketBroadcast{SessParam: sp}
	if byteData, ok := data.([]byte); ok {
		pack.Data = byteData
	} else {
		byteData, err := netlib.MarshalPacket(data)
		if err == nil {
			pack.Data = byteData
		} else {
			logger.Warn("BroadcastPacketFactory.CreateBroadcastPacket err:", err)
		}
	}
	proto.SetDefaults(pack)
	return pack
}
Ejemplo n.º 7
0
func (this *transactCoordinater) ProcessTransStart(parentTnp, myTnp *TransNodeParam, ud interface{}, timeout time.Duration) bool {
	if this.quit {
		logger.Warn("transactCoordinater.processTransStart find shutdowning, parent=", parentTnp, " selfparam=", myTnp)
		return false
	}
	tnode := this.createTransNode(myTnp, ud, timeout)
	if tnode == nil {
		return false
	}

	tnode.ParentTnp = parentTnp
	tnode.ownerObj = core.CoreObject()
	ret := tnode.execute(ud)
	if ret != TransExeResult_Success {
		return false
	}
	return true
}
Ejemplo n.º 8
0
//	Dequeue command and process it.
func (o *Object) ProcessCommand() {
	var (
		c        Command
		ok       bool
		tickMode bool
	)

	//wait for active
	<-o.waitActive

	//deamon or no
	if o.Waitor != nil {
		o.Waitor.Add(1)
		defer o.Waitor.Done()
	}

	if o.opt.Interval > 0 && o.sinker != nil && o.timer == nil {
		o.timer = time.NewTicker(o.opt.Interval)
		defer o.timer.Stop()
		tickMode = true
		o.tLastTick = time.Now()
	}

	//There is a small defect;
	//when the queue enlarging, there may be a command sequence can not be guaranteed
	//Because enlarging may occur in other goroutine
	for !o.terminated {
		if !atomic.CompareAndSwapInt32(&o.enlargingQue, 0, 0) {
			//wait enlarge queue
			runtime.Gosched()
			continue
		}
		if tickMode {
			select {
			case c, ok = <-o.que:
				if c != nil {
					o.safeDone(c)
				}
				if !ok {
					if o.terminated {
						return
					} else {
						continue
					}
				}
			case <-o.timer.C:
			}
		} else {
			select {
			case c, ok = <-o.que:
				if c != nil {
					o.safeDone(c)
				}
				if !ok {
					if o.terminated {
						return
					} else {
						continue
					}
				}
			}
		}

		if tickMode && time.Now().After(o.tLastTick.Add(o.opt.Interval)) {
			o.safeTick()
			o.tLastTick = time.Now()
			if len(o.que) > o.opt.MaxDone {
				logger.Warn("(", o.Name, ") object queue cmd count(", len(o.que), ") maxdone(", o.opt.MaxDone, ")")
			}
		}
	}
}
Ejemplo n.º 9
0
func init() {

	// service registe
	netlib.RegisterFactory(int(protocol.SrvlibPacketID_PACKET_SS_SERVICE_REGISTE), netlib.PacketFactoryWrapper(func() interface{} {
		return &protocol.SSServiceRegiste{}
	}))
	netlib.RegisterHandler(int(protocol.SrvlibPacketID_PACKET_SS_SERVICE_REGISTE), netlib.HandlerWrapper(func(s *netlib.Session, pack interface{}) error {
		if sr, ok := pack.(*protocol.SSServiceRegiste); ok {
			ServiceMgr.RegisteService(s, sr.GetServices())
		}
		return nil
	}))

	// service info
	netlib.RegisterFactory(int(protocol.SrvlibPacketID_PACKET_SS_SERVICE_INFO), netlib.PacketFactoryWrapper(func() interface{} {
		return &protocol.SSServiceInfo{}
	}))
	netlib.RegisterHandler(int(protocol.SrvlibPacketID_PACKET_SS_SERVICE_INFO), netlib.HandlerWrapper(func(s *netlib.Session, pack interface{}) error {
		if sr, ok := pack.(*protocol.SSServiceInfo); ok {
			service := sr.GetService()
			if service != nil {
				sc := &netlib.SessionConfig{
					Id:              int(service.GetSrvId()),
					Type:            int(service.GetSrvType()),
					AreaId:          int(service.GetAreaId()),
					Name:            service.GetSrvName(),
					Ip:              service.GetIp(),
					Port:            int(service.GetPort()),
					WriteTimeout:    time.Duration(service.GetWriteTimeOut()),
					ReadTimeout:     time.Duration(service.GetReadTimeOut()),
					IdleTimeout:     time.Duration(service.GetIdleTimeOut()),
					MaxDone:         int(service.GetMaxDone()),
					MaxPend:         int(service.GetMaxPend()),
					MaxPacket:       int(service.GetMaxPacket()),
					RcvBuff:         int(service.GetRcvBuff()),
					SndBuff:         int(service.GetSndBuff()),
					IsClient:        true,
					IsAutoReconn:    true,
					AuthKey:         service.GetAuthKey(),
					SoLinger:        int(service.GetSoLinger()),
					KeepAlive:       service.GetKeepAlive(),
					NoDelay:         service.GetNoDelay(),
					IsInnerLink:     service.GetIsInnerLink(),
					SupportFragment: service.GetSupportFragment(),
					AllowMultiConn:  service.GetAllowMultiConn(),
					EncoderName:     service.GetEncoderName(),
					DecoderName:     service.GetDecoderName(),
					FilterChain:     service.GetFilterChain(),
					HandlerChain:    service.GetHandlerChain(),
					Protocol:        service.GetProtocol(),
					Path:            service.GetPath(),
				}
				sc.Init()
				err := netlib.Connect(sc)
				if err != nil {
					logger.Warn("connect server failed err:", err)
				}
			}
		}
		return nil
	}))

	// service shutdown
	netlib.RegisterFactory(int(protocol.SrvlibPacketID_PACKET_SS_SERVICE_SHUT), netlib.PacketFactoryWrapper(func() interface{} {
		return &protocol.SSServiceShut{}
	}))
	netlib.RegisterHandler(int(protocol.SrvlibPacketID_PACKET_SS_SERVICE_SHUT), netlib.HandlerWrapper(func(s *netlib.Session, pack interface{}) error {
		if sr, ok := pack.(*protocol.SSServiceShut); ok {
			service := sr.GetService()
			if service != nil {
				netlib.ShutConnector(service.GetIp(), int(service.GetPort()))
			}
		}
		return nil
	}))

	ServerSessionMgrSington.SetListener(ServiceMgr)
}