public void Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { lock (_decoder) { _decoder.Decode(session, input, output); } }
public bool IsResponse(IoSession session, object message) { var isResponse = false; var heartbeat = message as DuplexMessage; if (heartbeat != null) isResponse = heartbeat.Header.MessageType == MessageType.Heartbeat; return isResponse; }
public void FinishDecode(IoSession session, IProtocolDecoderOutput output) { lock (_decoder) { _decoder.FinishDecode(session, output); } }
public bool IsRequest(IoSession session, object message) { var isRequest = false; var heartbeat = message as DuplexMessage; if (heartbeat != null) isRequest = heartbeat.Header.CommandCode == CommandCode.Heartbeat; return isRequest; }
/// <inheritdoc/> public virtual void ExceptionCaught(IoSession session, Exception cause) { if (log.IsWarnEnabled) { log.WarnFormat("EXCEPTION, please implement {0}.ExceptionCaught() for proper handling: {1}", GetType().Name, cause); } }
public SampleCommand( IoSession session, TimeoutNotifyProducerConsumer<AbstractAsyncCommand> producer) :base(session, CommandCode.Test, producer) { }
public void Encode(IoSession session, Object message, IProtocolEncoderOutput output) { lock (_encoder) { _encoder.Encode(session, message, output); } }
public void Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { if (_session == null) _session = session; else if (_session != session) throw new InvalidOperationException(GetType().Name + " is a stateful decoder. " + "You have to create one per session."); _undecodedBuffers.Enqueue(input); while (true) { IoBuffer b; if (!_undecodedBuffers.TryPeek(out b)) break; Int32 oldRemaining = b.Remaining; _state.Decode(b, output); Int32 newRemaining = b.Remaining; if (newRemaining != 0) { if (oldRemaining == newRemaining) throw new InvalidOperationException(_state.GetType().Name + " must consume at least one byte per decode()."); } else { _undecodedBuffers.TryDequeue(out b); } } }
public MessageDecoderResult Decodable(IoSession session, IoBuffer input) { if ((MessageType)input.Get() != MessageType.Update_ZipFiles) { return MessageDecoderResult.NotOK; } var zipFileInfo = JsonConvert.DeserializeObject<TransferingZipFileInfo>(input.GetString(Encoding.UTF8)); var fileSize = zipFileInfo.FileSize; var hashBytes = zipFileInfo.HashBytes; if (input.Remaining < fileSize) { return MessageDecoderResult.NeedData; } var filesBytes = new byte[fileSize]; input.Get(filesBytes, 0, (int)fileSize); if (FileHashHelper.CompareHashValue(FileHashHelper.ComputeFileHash(filesBytes), hashBytes)) { _zipFileInfoMessage = new TransferingZipFile(filesBytes); return MessageDecoderResult.OK; } return MessageDecoderResult.NotOK; }
protected override AbstractMessage DecodeBody(IoSession session, IoBuffer input) { if (!_readCode) { if (input.Remaining < Constants.RESULT_CODE_LEN) { return null; // Need more data. } _code = input.GetInt16(); _readCode = true; } if (_code == Constants.RESULT_OK) { if (input.Remaining < Constants.RESULT_VALUE_LEN) { return null; } ResultMessage m = new ResultMessage(); m.OK = true; m.Value = input.GetInt32(); _readCode = false; return m; } else { ResultMessage m = new ResultMessage(); m.OK = false; _readCode = false; return m; } }
public void Dispose(IoSession session) { lock (_encoder) { _encoder.Dispose(session); } }
private void Write(IoSession session, IoBuffer data, IoBuffer buf) { try { Int32 len = data.Remaining; if (len >= buf.Capacity) { /* * If the request length exceeds the size of the output buffer, * flush the output buffer and then write the data directly. */ INextFilter nextFilter = session.FilterChain.GetNextFilter(this); InternalFlush(nextFilter, session, buf); nextFilter.FilterWrite(session, new DefaultWriteRequest(data)); return; } if (len > (buf.Limit - buf.Position)) { InternalFlush(session.FilterChain.GetNextFilter(this), session, buf); } lock (buf) { buf.Put(data); } } catch (Exception e) { session.FilterChain.FireExceptionCaught(e); } }
public MessageDecoderResult Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { // Try to skip header if not read. if (!_readHeader) { input.GetInt16(); // Skip 'type'. _sequence = input.GetInt32(); // Get 'sequence'. _readHeader = true; } // Try to decode body AbstractMessage m = DecodeBody(session, input); // Return NEED_DATA if the body is not fully read. if (m == null) { return MessageDecoderResult.NeedData; } else { _readHeader = false; // reset readHeader for the next decode } m.Sequence = _sequence; output.Write(m); return MessageDecoderResult.OK; }
public void Put(IoSession session) { _sessionMap.StartExpiring(); EndPoint key = session.RemoteEndPoint; if (!_sessionMap.ContainsKey(key)) _sessionMap.Add(key, session); }
/// <summary> /// Method responsible for deciding if a connection is OK to continue. /// </summary> /// <param name="session">the new session that will be verified</param> /// <returns>true if the session meets the criteria, otherwise false</returns> public Boolean IsConnectionOk(IoSession session) { IPEndPoint ep = session.RemoteEndPoint as IPEndPoint; if (ep != null) { String addr = ep.Address.ToString(); DateTime now = DateTime.Now; DateTime? lastConnTime = null; _clients.AddOrUpdate(addr, now, (k, v) => { if (log.IsDebugEnabled) log.Debug("This is not a new client"); lastConnTime = v; return now; }); if (lastConnTime.HasValue) { // if the interval between now and the last connection is // less than the allowed interval, return false if ((now - lastConnTime.Value).TotalMilliseconds < _allowedInterval) { if (log.IsWarnEnabled) log.Warn("Session connection interval too short"); return false; } } return true; } return false; }
/// <inheritdoc/> public override void MessageReceived(INextFilter nextFilter, IoSession session, Object message) { //if (log.IsDebugEnabled) // log.DebugFormat("Processing a MESSAGE_RECEIVED for session {0}", session.Id); IoBuffer input = message as IoBuffer; if (input == null) { nextFilter.MessageReceived(session, message); return; } IProtocolDecoder decoder = _factory.GetDecoder(session); IProtocolDecoderOutput decoderOutput = GetDecoderOut(session, nextFilter); // Loop until we don't have anymore byte in the buffer, // or until the decoder throws an unrecoverable exception or // can't decoder a message, because there are not enough // data in the buffer while (input.HasRemaining) { Int32 oldPos = input.Position; try { // TODO may not need lock on UDP lock (session) { // Call the decoder with the read bytes decoder.Decode(session, input, decoderOutput); } // Finish decoding if no exception was thrown. decoderOutput.Flush(nextFilter, session); } catch (Exception ex) { ProtocolDecoderException pde = ex as ProtocolDecoderException; if (pde == null) pde = new ProtocolDecoderException(null, ex); if (pde.Hexdump == null) { // Generate a message hex dump Int32 curPos = input.Position; input.Position = oldPos; pde.Hexdump = input.GetHexDump(); input.Position = curPos; } decoderOutput.Flush(nextFilter, session); nextFilter.ExceptionCaught(session, pde); // Retry only if the type of the caught exception is // recoverable and the buffer position has changed. // We check buffer position additionally to prevent an // infinite loop. if (!(ex is RecoverableProtocolDecoderException) || input.Position == oldPos) break; } } }
public IoFilterEvent(INextFilter nextFilter, IoEventType eventType, IoSession session, Object parameter) : base(eventType, session, parameter) { if (nextFilter == null) throw new ArgumentNullException("nextFilter"); _nextFilter = nextFilter; }
/// <inheritdoc/> public override void FilterWrite(INextFilter nextFilter, IoSession session, IWriteRequest writeRequest) { IoBuffer buf = writeRequest.Message as IoBuffer; if (buf == null) throw new ArgumentException("This filter should only buffer IoBuffer objects"); else Write(session, buf); }
/// <inheritdoc/> public override void SessionClosed(INextFilter nextFilter, IoSession session) { if (IsBlocked(session)) BlockSession(session); else // forward if not blocked base.SessionClosed(nextFilter, session); }
/// <inheritdoc/> public override void SessionIdle(INextFilter nextFilter, IoSession session, IdleStatus status) { if (IsBlocked(session)) BlockSession(session); else // forward if not blocked base.SessionIdle(nextFilter, session, status); }
/// <inheritdoc/> public override void MessageReceived(INextFilter nextFilter, IoSession session, Object message) { if (IsBlocked(session)) BlockSession(session); else // forward if not blocked base.MessageReceived(nextFilter, session, message); }
/// <inheritdoc/> public override void MessageSent(INextFilter nextFilter, IoSession session, IWriteRequest writeRequest) { if (IsBlocked(session)) BlockSession(session); else // forward if not blocked base.MessageSent(nextFilter, session, writeRequest); }
public AbstractBlockCommand( IoSession session, CommandCode commandCode, TimeoutNotifyProducerConsumer<AbstractAsyncCommand> producer) :base(session, commandCode, producer) { Callback += BlockCommand_Callback; }
/// <summary> /// </summary> public IoEvent(IoEventType eventType, IoSession session, Object parameter) { if (session == null) throw new ArgumentNullException("session"); _eventType = eventType; _session = session; _parameter = parameter; }
/// <inheritdoc/> protected override Boolean DoDecode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { if (!input.PrefixedDataAvailable(4, _maxObjectSize)) return false; input.GetInt32(); output.Write(input.GetObject()); return true; }
public override void SessionCreated(INextFilter nextFilter, IoSession session) { foreach (KeyValuePair<String, Object> pair in _attributes) { session.SetAttribute(pair.Key, pair.Value); } base.SessionCreated(nextFilter, session); }
public MessageDecoderResult Decodable(IoSession session, IoBuffer input) { if ((MessageType)input.Get() != MessageType.Update_UpdateInfo) { return MessageDecoderResult.NotOK; } _appUdateInfo = (IClientInfo)JsonConvert.DeserializeObject(input.GetString(Encoding.UTF8)); return MessageDecoderResult.OK; }
public override void SessionCreated(INextFilter nextFilter, IoSession session) { if (!IsConnectionOk(session)) { Debug.WriteLine("Connections coming in too fast; closing."); session.Close(true); } base.SessionCreated(nextFilter, session); }
public void Encode(IoSession session, object message, IProtocolEncoderOutput output) { Message msg = (Message)message; IoBuffer buffer = IoBuffer.Allocate(1024); buffer.AutoExpand = true; buffer.PutMessage(msg); buffer.Flip(); output.Write(buffer); }
public void Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { Context ctx = GetContext(session); if (LineDelimiter.Auto.Equals(_delimiter)) DecodeAuto(ctx, session, input, output); else DecodeNormal(ctx, session, input, output); }
public void InputClosed(IoSession session) { }
public void SessionCreated(IoSession session) { // Do nothing }
public void SessionIdle(IoSession session, IdleStatus status) { // Do nothing }
public void InputClosed(IoSession session) { // Do nothing }
public void FilterClose(IoSession session) { // Do nothing }
public void Dispose(IoSession session) { }
public void TestSessionIdle() { int READER_IDLE_TIME = 3; //seconds int WRITER_IDLE_TIME = READER_IDLE_TIME + 2; //seconds int BOTH_IDLE_TIME = WRITER_IDLE_TIME + 2; //seconds AsyncDatagramAcceptor acceptor = new AsyncDatagramAcceptor(); acceptor.SessionConfig.SetIdleTime(IdleStatus.BothIdle, BOTH_IDLE_TIME); acceptor.SessionConfig.SetIdleTime(IdleStatus.ReaderIdle, READER_IDLE_TIME); acceptor.SessionConfig.SetIdleTime(IdleStatus.WriterIdle, WRITER_IDLE_TIME); IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); acceptor.SessionIdle += (s, e) => { if (e.IdleStatus == IdleStatus.BothIdle) { bothIdleReceived = true; } else if (e.IdleStatus == IdleStatus.ReaderIdle) { readerIdleReceived = true; } else if (e.IdleStatus == IdleStatus.WriterIdle) { writerIdleReceived = true; } lock (mutex) { System.Threading.Monitor.PulseAll(mutex); } }; acceptor.Bind(ep); IoSession session = acceptor.NewSession(new IPEndPoint(IPAddress.Loopback, 1024), ep); //check properties to be copied from acceptor to session Assert.AreEqual(BOTH_IDLE_TIME, session.Config.BothIdleTime); Assert.AreEqual(READER_IDLE_TIME, session.Config.ReaderIdleTime); Assert.AreEqual(WRITER_IDLE_TIME, session.Config.WriterIdleTime); //verify that IDLE events really received by handler DateTime startTime = DateTime.Now; lock (mutex) { while (!readerIdleReceived && (DateTime.Now - startTime).TotalMilliseconds < (READER_IDLE_TIME + 1) * 1000) { try { System.Threading.Monitor.Wait(mutex, READER_IDLE_TIME * 1000); } catch (Exception e) { Console.WriteLine(e); } } } Assert.IsTrue(readerIdleReceived); lock (mutex) { while (!writerIdleReceived && (DateTime.Now - startTime).TotalMilliseconds < (WRITER_IDLE_TIME + 1) * 1000) { try { System.Threading.Monitor.Wait(mutex, (WRITER_IDLE_TIME - READER_IDLE_TIME) * 1000); } catch (Exception e) { Console.WriteLine(e); } } } Assert.IsTrue(writerIdleReceived); lock (mutex) { while (!bothIdleReceived && (DateTime.Now - startTime).TotalMilliseconds < (BOTH_IDLE_TIME + 1) * 1000) { try { System.Threading.Monitor.Wait(mutex, (BOTH_IDLE_TIME - WRITER_IDLE_TIME) * 1000); } catch (Exception e) { Console.WriteLine(e); } } } Assert.IsTrue(bothIdleReceived); }
public void MessageSent(IoSession session, object message) { }
/// <inheritdoc/> public override void Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output) { if (!session.TransportMetadata.HasFragmentation) { while (input.HasRemaining) { if (!DoDecode(session, input, output)) { break; } } return; } Boolean usingSessionBuffer = true; IoBuffer buf = session.GetAttribute <IoBuffer>(BUFFER); // If we have a session buffer, append data to that; otherwise // use the buffer read from the network directly. if (buf == null) { buf = input; usingSessionBuffer = false; } else { Boolean appended = false; // Make sure that the buffer is auto-expanded. if (buf.AutoExpand) { try { buf.Put(input); appended = true; } catch (InvalidOperationException) { // A user called derivation method (e.g. slice()), // which disables auto-expansion of the parent buffer. } catch (OverflowException) { // A user disabled auto-expansion. } } if (appended) { buf.Flip(); } else { // Reallocate the buffer if append operation failed due to // derivation or disabled auto-expansion. buf.Flip(); IoBuffer newBuf = IoBuffer.Allocate(buf.Remaining + input.Remaining); newBuf.AutoExpand = true; newBuf.Order = buf.Order; newBuf.Put(buf); newBuf.Put(input); newBuf.Flip(); buf = newBuf; // Update the session attribute. session.SetAttribute(BUFFER, buf); } } while (true) { Int32 oldPos = buf.Position; Boolean decoded = DoDecode(session, buf, output); if (decoded) { if (buf.Position == oldPos) { throw new InvalidOperationException("DoDecode() can't return true when buffer is not consumed."); } if (!buf.HasRemaining) { break; } } else { break; } } // if there is any data left that cannot be decoded, we store // it in a buffer in the session and next time this decoder is // invoked the session buffer gets appended to if (buf.HasRemaining) { if (usingSessionBuffer && buf.AutoExpand) { buf.Compact(); } else { StoreRemainingInSession(buf, session); } } else { if (usingSessionBuffer) { RemoveSessionBuffer(session); } } }
internal void DoFinishSessionInitialization(IoSession session, IoFuture future) { InitSession(session, future, null); }
/// <summary> /// Executes a commit of data. This will flush the data to the disk use the provided header data to properly /// execute this function. /// </summary> /// <param name="header"></param> public void CommitChanges(FileHeaderBlock header) { using (var pageLock = new IoSession(this, m_pageReplacementAlgorithm)) { //Determine how much committed data to write long lengthOfAllData = (header.LastAllocatedBlock + 1) * (long)m_fileStructureBlockSize; long copyLength = lengthOfAllData - m_lengthOfCommittedData; //Write the uncommitted data. m_queue.Write(m_lengthOfCommittedData, m_writeBuffer, copyLength, waitForWriteToDisk: true); byte[] bytes = header.GetBytes(); if (header.HeaderBlockCount == 10) { //Update the new header to position 0, position 1, and one of position 2-9 m_queue.WriteRaw(0, bytes, m_fileStructureBlockSize); m_queue.WriteRaw(m_fileStructureBlockSize, bytes, m_fileStructureBlockSize); m_queue.WriteRaw(m_fileStructureBlockSize * ((header.SnapshotSequenceNumber & 7) + 2), bytes, m_fileStructureBlockSize); } else { for (int x = 0; x < header.HeaderBlockCount; x++) { m_queue.WriteRaw(x * m_fileStructureBlockSize, bytes, m_fileStructureBlockSize); } } m_queue.FlushFileBuffers(); long startPos; //Copy recently committed data to the buffer pool if ((m_lengthOfCommittedData & (m_diskBlockSize - 1)) != 0) //Only if there is a split page. { startPos = m_lengthOfCommittedData & (~(long)(m_diskBlockSize - 1)); //Finish filling up the split page in the buffer. IntPtr ptrDest; if (pageLock.TryGetSubPage(startPos, out ptrDest)) { int length; IntPtr ptrSrc; m_writeBuffer.ReadBlock(m_lengthOfCommittedData, out ptrSrc, out length); Footer.WriteChecksumResultsToFooter(ptrSrc, m_fileStructureBlockSize, length); ptrDest += (m_diskBlockSize - length); Memory.Copy(ptrSrc, ptrDest, length); } startPos += m_diskBlockSize; } else { startPos = m_lengthOfCommittedData; } while (startPos < lengthOfAllData) { //If the address doesn't exist in the current list. Read it from the disk. int poolPageIndex; IntPtr poolAddress; m_pool.AllocatePage(out poolPageIndex, out poolAddress); m_writeBuffer.CopyTo(startPos, poolAddress, m_diskBlockSize); Footer.WriteChecksumResultsToFooter(poolAddress, m_fileStructureBlockSize, m_diskBlockSize); if (!m_pageReplacementAlgorithm.TryAddPage(startPos, poolAddress, poolPageIndex)) { m_pool.ReleasePage(poolPageIndex); } startPos += m_diskBlockSize; } m_lengthOfCommittedData = lengthOfAllData; } ReleaseWriteBufferSpace(); }
public void SessionOpened(IoSession session) { ConnectionCount++; TotalConnectionCount++; }
public void SessionClosed(IoSession session) { ConnectionCount--; var ariesSession = session.GetAttribute<IAriesSession>("s"); if (ariesSession == null) { LOG.Info("[SESSION-REPLACED (" + Config.Call_Sign + ")]"); return; } if (session.GetAttribute("dc") == null && session.GetAttribute("sessionKey") != null) { //unexpected disconnect. if (UnexpectedDisconnectWaitSeconds > 0) { //close this session after the timeout, if it isn't migrated. LOG.Info("[SESSION-INTERRUPTED (" + Config.Call_Sign + ")]"); Task.Run(async () => { await Task.WhenAny( ((AriesSession)ariesSession).DisconnectSource.Task, Task.Delay(UnexpectedDisconnectWaitSeconds * 1000) ); if (session.GetAttribute("migrated") != null) { //this session has been migrated to another connection - it no longer needs to be closed LOG.Info("[SESSION-REPLACED (" + Config.Call_Sign + ")]"); return; } _Sessions.Remove(ariesSession); LOG.Info("[SESSION-TIMEOUT (" + Config.Call_Sign + ")]"); foreach (var interceptor in _SessionInterceptors) { try { interceptor.SessionClosed(ariesSession); } catch (Exception ex) { LOG.Error(ex); } } }); return; } } _Sessions.Remove(ariesSession); LOG.Info("[SESSION-CLOSED (" + Config.Call_Sign + ")]"); foreach (var interceptor in _SessionInterceptors) { try{ interceptor.SessionClosed(ariesSession); } catch (Exception ex) { LOG.Error(ex); } } }
public Heartbeat( IoSession session, TimeoutNotifyProducerConsumer <AbstractAsyncCommand> producer) : base(session, CommandCode.Heartbeat, producer) { }
/// <summary> /// </summary> public DefaultReadFuture(IoSession session) : base(session) { }
/// <inheritdoc/> public void Dispose(IoSession session) { // Do nothing }
public void SessionClosed(IoSession session) { }
protected override bool DoDecode(IoSession session, IoBuffer buffer, IProtocolDecoderOutput output) { if (buffer.Remaining < 12) { return(false); } /** * We expect aries, voltron or electron packets */ var startPosition = buffer.Position; buffer.Order = ByteOrder.LittleEndian; uint packetType = buffer.GetUInt32(); uint timestamp = buffer.GetUInt32(); uint payloadSize = buffer.GetUInt32(); if (buffer.Remaining < payloadSize) { /** Not all here yet **/ buffer.Position = startPosition; return(false); } //LOG.Info("[ARIES] " + packetType + " (" + payloadSize + ")"); if (packetType == AriesPacketType.Voltron.GetPacketCode()) { DecodeVoltronStylePackets(buffer, ref payloadSize, output, VoltronPackets.GetByPacketCode); } else if (packetType == AriesPacketType.Electron.GetPacketCode()) { DecodeVoltronStylePackets(buffer, ref payloadSize, output, ElectronPackets.GetByPacketCode); } else if (packetType == AriesPacketType.Gluon.GetPacketCode()) { DecodeVoltronStylePackets(buffer, ref payloadSize, output, GluonPackets.GetByPacketCode); } else { //Aries var packetClass = AriesPackets.GetByPacketCode(packetType); if (packetClass != null) { byte[] data = new byte[(int)payloadSize]; buffer.Get(data, 0, (int)payloadSize); IAriesPacket packet = (IAriesPacket)Activator.CreateInstance(packetClass); packet.Deserialize(IoBuffer.Wrap(data), Context); output.Write(packet); payloadSize = 0; } else { buffer.Skip((int)payloadSize); payloadSize = 0; } } return(true); }
public void ExceptionCaught(IoSession session, Exception cause) { }
private void Connector_SessionOpened(object sender, Mina.Core.Session.IoSessionEventArgs e) { session = e.Session; State = ConnectingState.Connected; }
public void ExceptionCaught(IoSession session, Exception cause) { throw new NotImplementedException(); }
public void SessionOpened(IoSession session) { }
public void SessionOpened(IoSession session) { // Do nothing }
public AriesSession(IoSession ioSession) { this.IoSession = ioSession; IsAuthenticated = false; }
public void SessionCreated(IoSession session) { }
/// <summary> /// POST-STAR 메시지를 처리한다. /// </summary> /// <param name="session"></param> /// <param name="starMessage"></param> protected override void ReceivePoststarMessage(IoSession session, PostStarMessage starMessage) { FrmReceiveMessage frmReceiveMessage = new FrmReceiveMessage(starMessage); frmReceiveMessage.ShowDialog(); }
/// <summary> /// Implement this method to consume the specified cumulative buffer and decode its content into message(s). /// </summary> /// <param name="session"></param> /// <param name="input"></param> /// <param name="output"></param> /// <returns> /// true if and only if there's more to decode in the buffer /// and you want to have DoDecode method invoked again. /// Return false if remaining data is not enough to decode, /// then this method will be invoked again when more data is cumulated. /// </returns> protected abstract Boolean DoDecode(IoSession session, IoBuffer input, IProtocolDecoderOutput output);
public void SessionIdle(IoSession session, IdleStatus status) { }
public void Encode(IoSession session, object message, IProtocolEncoderOutput output) { Encode(session, (TMessage)message, output); }
private void RemoveSessionBuffer(IoSession session) { session.RemoveAttribute(BUFFER); }