Esempio n. 1
0
        public void TestBackgroundUpdateSucceeds()
        {
            var k = new BlockingCell <int>();

            SetAfter(TimingInterval, k, 123);

            ResetTimer();
            int v = k.WaitForValue(TimingInterval_2X);

            Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
            Assert.AreEqual(123, v);
        }
Esempio n. 2
0
        public void TestGetValueWithTimeoutInfinite()
        {
            var k = new BlockingCell <int>();

            SetAfter(TimingInterval, k, 123);

            ResetTimer();
            int v = k.WaitForValue(Timeout.InfiniteTimeSpan);

            Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
            Assert.AreEqual(123, v);
        }
        ///<summary>Try to close connection in a graceful way</summary>
        ///<remarks>
        ///<para>
        ///Shutdown reason contains code and text assigned when closing the connection,
        ///as well as the information about what initiated the close
        ///</para>
        ///<para>
        ///Abort flag, if true, signals to close the ongoing connection immediately
        ///and do not report any errors if it was already closed.
        ///</para>
        ///<para>
        ///Timeout determines how much time internal close operations should be given
        ///to complete. Negative or Timeout.Infinite value mean infinity.
        ///</para>
        ///</remarks>
        public void Close(ShutdownEventArgs reason, bool abort, int timeout)
        {
            if (!SetCloseReason(reason))
            {
                if (abort)
                {
                    if (!m_appContinuation.WaitOne(BlockingCell.validatedTimeout(timeout), true))
                    {
                        m_frameHandler.Close();
                    }
                    return;
                }
                else
                {
                    throw new AlreadyClosedException(m_closeReason);
                }
            }

            OnShutdown();
            m_session0.SetSessionClosing(false);

            try
            {
                // Try to send connection close
                // Wait for CloseOk in the MainLoop
                m_session0.Transmit(ConnectionCloseWrapper(reason.ReplyCode,
                                                           reason.ReplyText));
            }
            catch (IOException ioe)
            {
                if (m_model0.CloseReason == null)
                {
                    if (!abort)
                    {
                        throw ioe;
                    }
                    else
                    {
                        LogCloseError("Couldn't close connection cleanly. "
                                      + "Socket closed unexpectedly", ioe);
                    }
                }
            }
            finally
            {
                TerminateMainloop();
            }
            if (!m_appContinuation.WaitOne(BlockingCell.validatedTimeout(timeout), true))
            {
                m_frameHandler.Close();
            }
        }
Esempio n. 4
0
        public void TestBackgroundUpdateSucceedsWithInfiniteTimeoutTimeSpan()
        {
            var k = new BlockingCell <int>();

            SetAfter(TimingInterval, k, 123);

            ResetTimer();
            var infiniteTimeSpan = new TimeSpan(0, 0, 0, 0, Timeout.Infinite);
            var v = k.WaitForValue(infiniteTimeSpan);

            Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
            Assert.AreEqual(123, v);
        }
Esempio n. 5
0
        public void TestGetValueWhichDoesNotTimeOut()
        {
            BlockingCell k = new BlockingCell
            {
                Value = 123
            };

            ResetTimer();
            var v = k.GetValue(TimingInterval);

            Assert.Greater(SafetyMargin, ElapsedMs());
            Assert.AreEqual(123, v);
        }
        public void TestBackgroundUpdateSucceedsWithInfiniteTimeoutTimeSpan()
        {
            var k = new BlockingCell <int>();

            SetAfter(TimingInterval, k, 123);

            ResetTimer();
            TimeSpan infiniteTimeSpan = Timeout.InfiniteTimeSpan;
            int      v = k.WaitForValue(infiniteTimeSpan);

            Assert.True(TimingInterval - SafetyMargin < ElapsedMs());
            Assert.Equal(123, v);
        }
        public void TestTimeoutShort()
        {
            BlockingCell k = new BlockingCell();

            k.Value = 123;

            ResetTimer();
            object v;
            bool   r = k.GetValue(TimingInterval, out v);

            Assert.Greater(SafetyMargin, ElapsedMs());
            Assert.IsTrue(r);
            Assert.AreEqual(123, v);
        }
        public void TestBgLong()
        {
            BlockingCell k = new BlockingCell();

            SetAfter(TimingInterval * 2, k, 123);

            ResetTimer();
            object v;
            bool   r = k.GetValue(TimingInterval, out v);

            Assert.Greater(TimingInterval + SafetyMargin, ElapsedMs());
            Assert.IsTrue(!r);
            Assert.AreEqual(null, v);
        }
        public void TestBgShort()
        {
            BlockingCell k = new BlockingCell();

            SetAfter(TimingInterval, k, 123);

            ResetTimer();
            object v;
            bool   r = k.GetValue(TimingInterval * 2, out v);

            Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
            Assert.IsTrue(r);
            Assert.AreEqual(123, v);
        }
Esempio n. 10
0
        public void HandleConnectionStart(byte versionMajor,
                                          byte versionMinor,
                                          IDictionary serverProperties,
                                          byte[] mechanisms,
                                          byte[] locales)
        {
            if (m_connectionStartCell == null)
            {
                ShutdownEventArgs reason =
                    new ShutdownEventArgs(ShutdownInitiator.Library,
                                          CommonFraming.Constants.CommandInvalid,
                                          "Unexpected Connection.Start");
                ((ConnectionBase)m_session.Connection).Close(reason);
            }
            ConnectionStartDetails details = new ConnectionStartDetails();

            details.m_versionMajor      = versionMajor;
            details.m_versionMinor      = versionMinor;
            details.m_serverProperties  = serverProperties;
            details.m_mechanisms        = mechanisms;
            details.m_locales           = locales;
            m_connectionStartCell.Value = details;
            m_connectionStartCell       = null;
        }
Esempio n. 11
0
        ///<summary>Try to close connection in a graceful way</summary>
        ///<remarks>
        ///<para>
        ///Shutdown reason contains code and text assigned when closing the connection,
        ///as well as the information about what initiated the close
        ///</para>
        ///<para>
        ///Abort flag, if true, signals to close the ongoing connection immediately
        ///and do not report any errors if it was already closed.
        ///</para>
        ///<para>
        ///Timeout determines how much time internal close operations should be given
        ///to complete. Negative or Timeout.Infinite value mean infinity.
        ///</para>
        ///</remarks>
        public void Close(ShutdownEventArgs reason, bool abort, int timeout)
        {
            if (!SetCloseReason(reason))
            {
                if (!abort)
                {
                    throw new AlreadyClosedException(m_closeReason);
                }
            }
            else
            {
                OnShutdown();
                m_session0.SetSessionClosing(false);

                try
                {
                    // Try to send connection.close
                    // Wait for CloseOk in the MainLoop
                    m_session0.Transmit(ConnectionCloseWrapper(reason.ReplyCode,
                                                               reason.ReplyText));
                }
                catch (AlreadyClosedException ace)
                {
                    if (!abort)
                    {
                        throw ace;
                    }
                }
#pragma warning disable 0168
                catch (NotSupportedException nse)
                {
                    // buffered stream had unread data in it and Flush()
                    // was called, ignore to not confuse the user
                }
#pragma warning restore 0168
                catch (IOException ioe)
                {
                    if (m_model0.CloseReason == null)
                    {
                        if (!abort)
                        {
                            throw ioe;
                        }
                        else
                        {
                            LogCloseError("Couldn't close connection cleanly. "
                                          + "Socket closed unexpectedly", ioe);
                        }
                    }
                }
                finally
                {
                    TerminateMainloop();
                }
            }

#if NETFX_CORE
            var receivedSignal = m_appContinuation.WaitOne(BlockingCell <object> .validatedTimeout(timeout));
#else
            var receivedSignal = m_appContinuation.WaitOne(BlockingCell <object> .validatedTimeout(timeout));
#endif

            if (!receivedSignal)
            {
                m_frameHandler.Close();
            }
        }
Esempio n. 12
0
        void StartAndTune()
        {
            var connectionStartCell = new BlockingCell <ConnectionStartDetails>();

            m_model0.m_connectionStartCell        = connectionStartCell;
            m_model0.HandshakeContinuationTimeout = m_factory.HandshakeContinuationTimeout;
            m_frameHandler.ReadTimeout            = (int)m_factory.HandshakeContinuationTimeout.TotalMilliseconds;
            m_frameHandler.SendHeader();

            var connectionStart = connectionStartCell.WaitForValue();

            if (connectionStart == null)
            {
                throw new IOException("connection.start was never received, likely due to a network timeout");
            }

            ServerProperties = connectionStart.m_serverProperties;

            var serverVersion = new AmqpVersion(connectionStart.m_versionMajor,
                                                connectionStart.m_versionMinor);

            if (!serverVersion.Equals(Protocol.Version))
            {
                TerminateMainloop();
                FinishClose();
                throw new ProtocolVersionMismatchException(Protocol.MajorVersion,
                                                           Protocol.MinorVersion,
                                                           serverVersion.Major,
                                                           serverVersion.Minor);
            }

            m_clientProperties = new Dictionary <string, object>(m_factory.ClientProperties);
            m_clientProperties["capabilities"]    = Protocol.Capabilities;
            m_clientProperties["connection_name"] = this.ClientProvidedName;

            // FIXME: parse out locales properly!
            ConnectionTuneDetails connectionTune = default(ConnectionTuneDetails);
            bool tuned = false;

            try
            {
                string               mechanismsString = Encoding.UTF8.GetString(connectionStart.m_mechanisms, 0, connectionStart.m_mechanisms.Length);
                string[]             mechanisms       = mechanismsString.Split(' ');
                AuthMechanismFactory mechanismFactory = m_factory.AuthMechanismFactory(mechanisms);
                if (mechanismFactory == null)
                {
                    throw new IOException("No compatible authentication mechanism found - " +
                                          "server offered [" + mechanismsString + "]");
                }
                AuthMechanism mechanism = mechanismFactory.GetInstance();
                byte[]        challenge = null;
                do
                {
                    byte[] response = mechanism.handleChallenge(challenge, m_factory);
                    ConnectionSecureOrTune res;
                    if (challenge == null)
                    {
                        res = m_model0.ConnectionStartOk(m_clientProperties,
                                                         mechanismFactory.Name,
                                                         response,
                                                         "en_US");
                    }
                    else
                    {
                        res = m_model0.ConnectionSecureOk(response);
                    }

                    if (res.m_challenge == null)
                    {
                        connectionTune = res.m_tuneDetails;
                        tuned          = true;
                    }
                    else
                    {
                        challenge = res.m_challenge;
                    }
                }while (!tuned);
            }
            catch (OperationInterruptedException e)
            {
                if (e.ShutdownReason != null && e.ShutdownReason.ReplyCode == Constants.AccessRefused)
                {
                    throw new AuthenticationFailureException(e.ShutdownReason.ReplyText);
                }
                throw new PossibleAuthenticationFailureException(
                          "Possibly caused by authentication failure", e);
            }

            var channelMax = (ushort)NegotiatedMaxValue(m_factory.RequestedChannelMax,
                                                        connectionTune.m_channelMax);

            m_sessionManager = new SessionManager(this, channelMax);

            uint frameMax = NegotiatedMaxValue(m_factory.RequestedFrameMax,
                                               connectionTune.m_frameMax);

            FrameMax = frameMax;

            var heartbeat = (ushort)NegotiatedMaxValue(m_factory.RequestedHeartbeat,
                                                       connectionTune.m_heartbeat);

            Heartbeat = heartbeat;

            m_model0.ConnectionTuneOk(channelMax,
                                      frameMax,
                                      heartbeat);

            // now we can start heartbeat timers
            MaybeStartHeartbeatTimers();
        }
Esempio n. 13
0
        private void StartAndTune()
        {
            var connectionStartCell = new BlockingCell <ConnectionStartDetails>();

            _model0.m_connectionStartCell        = connectionStartCell;
            _model0.HandshakeContinuationTimeout = _config.HandshakeContinuationTimeout;
            _frameHandler.ReadTimeout            = _config.HandshakeContinuationTimeout;
            _frameHandler.SendHeader();

            ConnectionStartDetails connectionStart = connectionStartCell.WaitForValue();

            if (connectionStart is null)
            {
                throw new IOException("connection.start was never received, likely due to a network timeout");
            }

            ServerProperties = connectionStart.m_serverProperties;

            var serverVersion = new AmqpVersion(connectionStart.m_versionMajor, connectionStart.m_versionMinor);

            if (!serverVersion.Equals(Protocol.Version))
            {
                TerminateMainloop();
                FinishClose();
                throw new ProtocolVersionMismatchException(Protocol.MajorVersion, Protocol.MinorVersion, serverVersion.Major, serverVersion.Minor);
            }

            // FIXME: parse out locales properly!
            ConnectionTuneDetails connectionTune = default;
            bool tuned = false;

            try
            {
                string mechanismsString = Encoding.UTF8.GetString(connectionStart.m_mechanisms);
                IAuthMechanismFactory mechanismFactory = GetAuthMechanismFactory(mechanismsString);
                IAuthMechanism        mechanism        = mechanismFactory.GetInstance();
                byte[]? challenge = null;
                do
                {
                    byte[] response = mechanism.handleChallenge(challenge, _config);
                    ConnectionSecureOrTune res;
                    if (challenge is null)
                    {
                        res = _model0.ConnectionStartOk(ClientProperties,
                                                        mechanismFactory.Name,
                                                        response,
                                                        "en_US");
                    }
                    else
                    {
                        res = _model0.ConnectionSecureOk(response);
                    }

                    if (res.m_challenge is null)
                    {
                        connectionTune = res.m_tuneDetails;
                        tuned          = true;
                    }
                    else
                    {
                        challenge = res.m_challenge;
                    }
                }while (!tuned);
            }
            catch (OperationInterruptedException e)
            {
                if (e.ShutdownReason != null && e.ShutdownReason.ReplyCode == Constants.AccessRefused)
                {
                    throw new AuthenticationFailureException(e.ShutdownReason.ReplyText);
                }
                throw new PossibleAuthenticationFailureException(
                          "Possibly caused by authentication failure", e);
            }

            ushort channelMax = (ushort)NegotiatedMaxValue(_config.MaxChannelCount, connectionTune.m_channelMax);

            _sessionManager = new SessionManager(this, channelMax);

            uint frameMax = NegotiatedMaxValue(_config.MaxFrameSize, connectionTune.m_frameMax);

            FrameMax       = frameMax;
            MaxPayloadSize = frameMax == 0 ? int.MaxValue : (int)frameMax - Client.Impl.Framing.BaseFrameSize;

            uint heartbeatInSeconds = NegotiatedMaxValue((uint)_config.HeartbeatInterval.TotalSeconds, (uint)connectionTune.m_heartbeatInSeconds);

            Heartbeat = TimeSpan.FromSeconds(heartbeatInSeconds);

            _model0.ConnectionTuneOk(channelMax, frameMax, (ushort)Heartbeat.TotalSeconds);

            // now we can start heartbeat timers
            MaybeStartHeartbeatTimers();
        }
Esempio n. 14
0
        public void Open(bool insist)
        {
            BlockingCell connectionStartCell = new BlockingCell();

            m_model0.m_connectionStartCell = connectionStartCell;
            m_frameHandler.Timeout         = HandshakeTimeout;
            m_frameHandler.SendHeader();

            ConnectionStartDetails connectionStart = (ConnectionStartDetails)
                                                     connectionStartCell.Value;

            ServerProperties = connectionStart.m_serverProperties;

            AmqpVersion serverVersion = new AmqpVersion(connectionStart.m_versionMajor,
                                                        connectionStart.m_versionMinor);

            if (!serverVersion.Equals(Protocol.Version))
            {
                TerminateMainloop();
                FinishClose();
                throw new ProtocolVersionMismatchException(Protocol.MajorVersion,
                                                           Protocol.MinorVersion,
                                                           serverVersion.Major,
                                                           serverVersion.Minor);
            }

            m_clientProperties = new Hashtable(m_factory.ClientProperties);

            // FIXME: check that PLAIN is supported.
            // FIXME: parse out locales properly!
            ConnectionTuneDetails connectionTune = default(ConnectionTuneDetails);

            try
            {
                connectionTune =
                    m_model0.ConnectionStartOk(m_clientProperties,
                                               "PLAIN",
                                               Encoding.UTF8.GetBytes(
                                                   "\0" + m_factory.UserName +
                                                   "\0" + m_factory.Password),
                                               "en_US");
            }
            catch (OperationInterruptedException e)
            {
                throw new PossibleAuthenticationFailureException(
                          "Possibly caused by authentication failure", e);
            }

            ushort channelMax = (ushort)NegotiatedMaxValue(m_factory.RequestedChannelMax,
                                                           connectionTune.m_channelMax);

            m_sessionManager = new SessionManager(this, channelMax);

            uint frameMax = NegotiatedMaxValue(m_factory.RequestedFrameMax,
                                               connectionTune.m_frameMax);

            FrameMax = frameMax;

            ushort heartbeat = (ushort)NegotiatedMaxValue(m_factory.RequestedHeartbeat,
                                                          connectionTune.m_heartbeat);

            Heartbeat = heartbeat;

            m_model0.ConnectionTuneOk(channelMax,
                                      frameMax,
                                      heartbeat);

            string knownHosts = m_model0.ConnectionOpen(m_factory.VirtualHost,
                                                        "", // FIXME: make configurable?
                                                        insist);

            KnownHosts = AmqpTcpEndpoint.ParseMultiple(Protocol, knownHosts);
        }