Пример #1
0
        internal AmqpClientConnection(Uri uri, AmqpSettings amqpSettings)
        {
            _uri          = uri;
            _amqpSettings = amqpSettings;

            AmqpConnectionSettings = new AmqpConnectionSettings
            {
                ContainerId = Guid.NewGuid().ToString(),
                HostName    = _uri.Host
            };
        }
        private static AmqpConnectionSettings CreateAmqpConnectionSettings(uint maxFrameSize, string containerId, string hostName)
        {
            var connectionSettings = new AmqpConnectionSettings
            {
                MaxFrameSize = maxFrameSize,
                ContainerId  = containerId,
                HostName     = hostName
            };

            ClientInfo.Add(connectionSettings);
            return(connectionSettings);
        }
Пример #3
0
        async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            var timeoutHelper = new TimeoutHelper(timeout);

            this.refreshTokenTimer.Cancel();

            AmqpSettings         amqpSettings         = this.CreateAmqpSettings();
            TlsTransportSettings tlsTransportSettings = this.CreateTlsTransportSettings();

            var           amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
            TransportBase transport;

            switch (this.amqpTransportSettings.GetTransportType())
            {
            case TransportType.Amqp_WebSocket_Only:
                transport = await this.CreateClientWebSocketTransport(timeoutHelper.RemainingTime());

                break;

            case TransportType.Amqp_Tcp_Only:
                transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime());

                break;

            default:
                throw new InvalidOperationException("AmqpTransportSettings must specify WebSocketOnly or TcpOnly");
            }

            var amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString("N"),
                HostName     = this.connectionString.AmqpEndpoint.Host
            };

            var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await amqpConnection.OpenAsync(timeoutHelper.RemainingTime());

            var sessionSettings = new AmqpSessionSettings()
            {
                Properties = new Fields()
            };

            var amqpSession = amqpConnection.CreateSession(sessionSettings);
            await amqpSession.OpenAsync(timeoutHelper.RemainingTime());

            // This adds itself to amqpConnection.Extensions
            var cbsLink = new AmqpCbsLink(amqpConnection);

            await this.SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime());

            return(amqpSession);
        }
Пример #4
0
        public async Task <AmqpIotConnection> OpenConnectionAsync(TimeSpan timeout)
        {
            Logging.Enter(this, timeout, nameof(OpenConnectionAsync));

            var amqpTransportProvider = new AmqpTransportProvider();

            amqpTransportProvider.Versions.Add(s_amqpVersion_1_0_0);

            var amqpSettings = new AmqpSettings();

            amqpSettings.TransportProviders.Add(amqpTransportProvider);

            var amqpConnectionSettings = new AmqpConnectionSettings
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = CommonResources.GetNewStringGuid(),
                HostName     = _hostName,
            };

            TimeSpan idleTimeout = _amqpTransportSettings.IdleTimeout;

            if (idleTimeout != null)
            {
                amqpConnectionSettings.IdleTimeOut = Convert.ToUInt32(idleTimeout.TotalMilliseconds);
            }

            _amqpIotTransport = new AmqpIotTransport(amqpSettings, _amqpTransportSettings, _hostName, s_disableServerCertificateValidation);

            TransportBase transportBase = await _amqpIotTransport.InitializeAsync(timeout).ConfigureAwait(false);

            try
            {
                var amqpConnection    = new AmqpConnection(transportBase, amqpSettings, amqpConnectionSettings);
                var amqpIotConnection = new AmqpIotConnection(amqpConnection);
                amqpConnection.Closed += amqpIotConnection.AmqpConnectionClosed;
                await amqpConnection.OpenAsync(timeout).ConfigureAwait(false);

                Logging.Exit(this, timeout, $"{nameof(OpenConnectionAsync)}");

                return(amqpIotConnection);
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                transportBase?.Close();
                _amqpIotTransport?.Dispose();
                throw;
            }
            finally
            {
                Logging.Exit(this, nameof(OpenConnectionAsync));
            }
        }
        /// <summary>
        ///   Creates an AMQP connection for a given scope.
        /// </summary>
        ///
        /// <param name="amqpVersion">The version of AMQP to use for the connection.</param>
        /// <param name="serviceEndpoint">The endpoint for the Service Bus service to which the scope is associated.</param>
        /// <param name="transportType">The type of transport to use for communication.</param>
        /// <param name="proxy">The proxy, if any, to use for communication.</param>
        /// <param name="scopeIdentifier">The unique identifier for the associated scope.</param>
        /// <param name="timeout">The timeout to consider when creating the connection.</param>
        ///
        /// <returns>An AMQP connection that may be used for communicating with the Service Bus service.</returns>
        ///
        protected virtual async Task <AmqpConnection> CreateAndOpenConnectionAsync(
            Version amqpVersion,
            Uri serviceEndpoint,
            ServiceBusTransportType transportType,
            IWebProxy proxy,
            string scopeIdentifier,
            TimeSpan timeout)
        {
            var                    hostName          = serviceEndpoint.Host;
            AmqpSettings           amqpSettings      = CreateAmpqSettings(AmqpVersion);
            AmqpConnectionSettings connectionSetings = CreateAmqpConnectionSettings(hostName, scopeIdentifier);

            TransportSettings transportSettings = transportType.IsWebSocketTransport()
                ? CreateTransportSettingsForWebSockets(hostName, proxy)
                : CreateTransportSettingsforTcp(hostName, serviceEndpoint.Port);

            // Create and open the connection, respecting the timeout constraint
            // that was received.

            var stopWatch = Stopwatch.StartNew();

            var           initiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
            TransportBase transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false);

            var connection = new AmqpConnection(transport, amqpSettings, connectionSetings);

            await OpenAmqpObjectAsync(connection, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false);

            stopWatch.Stop();

            // Create the CBS link that will be used for authorization.  The act of creating the link will associate
            // it with the connection.

            new AmqpCbsLink(connection);

            // When the connection is closed, close each of the links associated with it.

            EventHandler closeHandler = null;

            closeHandler = (snd, args) =>
            {
                foreach (var link in ActiveLinks.Keys)
                {
                    link.SafeClose();
                }

                connection.Closed -= closeHandler;
            };

            connection.Closed += closeHandler;
            return(connection);
        }
        static AmqpConnectionSettings CreateAmqpConnectionSettings(uint maxFrameSize, string containerId, string hostName)
        {
            var connectionSettings = new AmqpConnectionSettings
            {
                MaxFrameSize = maxFrameSize,
                ContainerId  = containerId,
                HostName     = hostName,
                IdleTimeOut  = (uint)AmqpClientConstants.ConnectionIdleTimeout.TotalMilliseconds
            };

            ClientInfo.Add(connectionSettings);
            return(connectionSettings);
        }
Пример #7
0
        protected virtual async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            this.OnCreateSession();

            var timeoutHelper = new TimeoutHelper(timeout);

            AmqpSettings  amqpSettings = CreateAmqpSettings();
            TransportBase transport;

            switch (this.AmqpTransportSettings.GetTransportType())
            {
#if !WINDOWS_UWP
            case TransportType.Amqp_WebSocket_Only:
                transport = await this.CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime());

                break;
#endif
            case TransportType.Amqp_Tcp_Only:
                TlsTransportSettings tlsTransportSettings = this.CreateTlsTransportSettings();
                var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
                transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime());

                break;

            default:
                throw new InvalidOperationException("AmqpTransportSettings must specify WebSocketOnly or TcpOnly");
            }

            var amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString("N"),
                HostName     = this.hostName
            };

            var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await amqpConnection.OpenAsync(timeoutHelper.RemainingTime());

            var sessionSettings = new AmqpSessionSettings()
            {
                Properties = new Fields()
            };

            var amqpSession = amqpConnection.CreateSession(sessionSettings);
            await amqpSession.OpenAsync(timeoutHelper.RemainingTime());

            // This adds itself to amqpConnection.Extensions
            var cbsLink = new AmqpCbsLink(amqpConnection);
            return(amqpSession);
        }
Пример #8
0
        public static AmqpConnection CreateConnection(string host, int port, string sslHost, bool doSslUpgrade, SaslHandler saslHandler, int maxFrameSize,
                                                      uint?idleTimeoutMs = null)
        {
            AmqpSettings           settings     = GetAmqpSettings(true, sslHost, doSslUpgrade, saslHandler);
            TransportBase          transport    = CreateTransport(host, port, sslHost, doSslUpgrade, saslHandler);
            AmqpConnectionSettings connSettings = GetConnectionSettings(maxFrameSize);

            if (idleTimeoutMs != null)
            {
                connSettings.IdleTimeOut = idleTimeoutMs;
            }
            connSettings.HostName = host;
            return(new AmqpConnection(transport, settings, connSettings));
        }
Пример #9
0
        public async Task <AmqpIoTConnection> OpenConnectionAsync(TimeSpan timeout)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, timeout, $"{nameof(OpenConnectionAsync)}");
            }

            var amqpSettings          = new AmqpSettings();
            var amqpTransportProvider = new AmqpTransportProvider();

            amqpTransportProvider.Versions.Add(s_amqpVersion_1_0_0);
            amqpSettings.TransportProviders.Add(amqpTransportProvider);

            var amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = CommonResources.GetNewStringGuid(),
                HostName     = _hostName
            };

            var amqpIoTTransport = new AmqpIoTTransport(amqpSettings, _amqpTransportSettings, _hostName, s_disableServerCertificateValidation);

            TransportBase transportBase = await amqpIoTTransport.InitializeAsync(timeout).ConfigureAwait(false);

            try
            {
                var amqpConnection = new AmqpConnection(transportBase, amqpSettings, amqpConnectionSettings);
                AmqpIoTConnection amqpIoTConnection = new AmqpIoTConnection(amqpConnection);
                amqpConnection.Closed += amqpIoTConnection.AmqpConnectionClosed;
                await amqpConnection.OpenAsync(timeout).ConfigureAwait(false);

                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, timeout, $"{nameof(OpenConnectionAsync)}");
                }
                return(amqpIoTConnection);
            }
            catch (Exception e) when(!e.IsFatal())
            {
                transportBase?.Close();
                throw;
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, $"{nameof(OpenConnectionAsync)}");
                }
            }
        }
        public static AmqpConnectionSettings CreateAmqpConnectionSettings(uint maxFrameSize, string containerId, string hostName)
        {
            var connectionSettings = new AmqpConnectionSettings
            {
                MaxFrameSize = maxFrameSize,
                ContainerId  = containerId,
                HostName     = hostName
            };

            connectionSettings.AddProperty("product", ClientInfo.Product);
            connectionSettings.AddProperty("version", ClientInfo.Version);
            connectionSettings.AddProperty("framework", ClientInfo.Framework);
            connectionSettings.AddProperty("platform", ClientInfo.Platform);
            return(connectionSettings);
        }
        public static AmqpConnectionSettings CreateAmqpConnectionSettings(uint maxFrameSize, string containerId, string hostName)
        {
            var connectionSettings = new AmqpConnectionSettings
            {
                MaxFrameSize = maxFrameSize,
                ContainerId  = containerId,
                HostName     = hostName,
                IdleTimeOut  = (uint)Constants.DefaultOperationTimeout.TotalMilliseconds
            };

            connectionSettings.AddProperty("product", ClientInfo.Product);
            connectionSettings.AddProperty("version", ClientInfo.Version);
            connectionSettings.AddProperty("framework", ClientInfo.Framework);
            connectionSettings.AddProperty("platform", ClientInfo.Platform);
            return(connectionSettings);
        }
        /// <summary>
        ///   Creates an AMQP connection for a given scope.
        /// </summary>
        ///
        /// <param name="amqpVersion">The version of AMQP to use for the connection.</param>
        /// <param name="serviceEndpoint">The endpoint for the Event Hubs service to which the scope is associated.</param>
        /// <param name="transportType">The type of transport to use for communication.</param>
        /// <param name="proxy">The proxy, if any, to use for communication.</param>
        /// <param name="scopeIdentifier">The unique identifier for the associated scope.</param>
        /// <param name="timeout">The timeout to consider when creating the connection.</param>
        ///
        /// <returns>An AMQP connection that may be used for communicating with the Event Hubs service.</returns>
        ///
        protected virtual async Task <AmqpConnection> CreateConnectionAsync(Version amqpVersion,
                                                                            Uri serviceEndpoint,
                                                                            TransportType transportType,
                                                                            IWebProxy proxy,
                                                                            string scopeIdentifier,
                                                                            TimeSpan timeout)
        {
            var                    hostName          = serviceEndpoint.Host;
            AmqpSettings           amqpSettings      = CreateAmpqSettings(s_amqpVersion);
            AmqpConnectionSettings connectionSetings = CreateAmqpConnectionSettings(hostName, scopeIdentifier);

            TransportSettings transportSettings = transportType.IsWebSocketTransport()
                ? CreateTransportSettingsForWebSockets(hostName, proxy)
                : CreateTransportSettingsforTcp(hostName, serviceEndpoint.Port);

            // Create and open the connection, respecting the timeout constraint
            // that was received.

            var stopWatch = Stopwatch.StartNew();

            var           initiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
            TransportBase transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false);

            var connection = new AmqpConnection(transport, amqpSettings, connectionSetings);
            await connection.OpenAsync(timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false);

            stopWatch.Stop();

            // Create the CBS link that will be used for authorization and ensure that it is associated
            // with the connection.

            var cbsLink = new AmqpCbsLink(connection);

            // TODO (pri2 // squire):
            //   The act of creating the link should ensure that it is added to the connection.  Unsure
            //   of why this additional check was in the track one code.   Investigate and either
            //   document or remove.

            if (!connection.Extensions.Contains(typeof(AmqpCbsLink)))
            {
                connection.Extensions.Add(cbsLink);
            }

            return(connection);
        }
Пример #13
0
        internal AmqpIoTConnection(AmqpTransportSettings amqpTransportSettings, string hostName, bool disableServerCertificateValidation)
        {
            _amqpTransportSettings = amqpTransportSettings;

            _amqpSettings = new AmqpSettings();
            var amqpTransportProvider = new AmqpTransportProvider();

            amqpTransportProvider.Versions.Add(amqpVersion_1_0_0);
            _amqpSettings.TransportProviders.Add(amqpTransportProvider);

            _amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = CommonResources.GetNewStringGuid(),
                HostName     = hostName
            };

            _amqpIoTTransport = new AmqpIoTTransport(_amqpSettings, _amqpTransportSettings, hostName, disableServerCertificateValidation);
        }
Пример #14
0
        AmqpConnection IConnectionFactory.CreateConnection(
            TransportBase transport,
            ProtocolHeader protocolHeader,
            bool isInitiator,
            AmqpSettings settings,
            AmqpConnectionSettings connectionSettings)
        {
            if (this.requireSecureTransport && !transport.IsSecure)
            {
                throw new AmqpException(AmqpErrorCode.NotAllowed, "AMQP transport is not secure");
            }

            var connection = new AmqpConnection(transport, protocolHeader, false, settings, connectionSettings)
            {
                SessionFactory = this
            };
            connection.Opening += this.OnConnectionOpening;

            return connection;
        }
        public async Task ListenerSaslTlsTest()
        {
            string address = "amqps://*****:*****@localhost:5676";

            AmqpSettings           settings           = AmqpUtils.GetAmqpSettings(false, "localhost", false, new SaslPlainHandler(new TestSaslPlainAuthenticator()));
            AmqpConnectionSettings connectionSettings = AmqpUtils.GetConnectionSettings(32 * 1024);

            settings.RuntimeProvider = new TestRuntimeProvider();
            AmqpConnectionListener listener = new AmqpConnectionListener(new[] { address }, settings, connectionSettings);

            listener.Open();

            try
            {
                await RunClientAsync(address);
            }
            finally
            {
                listener.Close();
            }
        }
        async Task <AmqpConnection> CreateConnectionAsync(TimeSpan timeout)
        {
            string hostName    = this.Endpoint.Host;
            string networkHost = this.Endpoint.Host;
            int    port        = this.Endpoint.Port;

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            AmqpSettings  amqpSettings  = AmqpConnectionHelper.CreateAmqpSettings(
                amqpVersion: AmqpVersion,
                useSslStreamSecurity: true,
                hasTokenProvider: true);

            TransportSettings tpSettings = AmqpConnectionHelper.CreateTcpTransportSettings(
                networkHost: networkHost,
                hostName: hostName,
                port: port,
                useSslStreamSecurity: true);

            AmqpTransportInitiator initiator = new AmqpTransportInitiator(amqpSettings, tpSettings);
            TransportBase          transport = await initiator.ConnectTaskAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            string containerId = Guid.NewGuid().ToString();
            AmqpConnectionSettings amqpConnectionSettings = AmqpConnectionHelper.CreateAmqpConnectionSettings(AmqpConstants.DefaultMaxFrameSize, containerId, hostName);
            AmqpConnection         connection             = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await connection.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            // Always create the CBS Link + Session
            AmqpCbsLink cbsLink = new AmqpCbsLink(connection);

            if (connection.Extensions.Find <AmqpCbsLink>() == null)
            {
                connection.Extensions.Add(cbsLink);
            }

            MessagingEventSource.Log.AmqpConnectionCreated(hostName, connection);

            return(connection);
        }
Пример #17
0
        async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            this.refreshTokenTimer.Cancel();

            var amqpSettings         = this.CreateAmqpSettings();
            var tlsTransportSettings = this.CreateTlsTransportSettings();

            var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
            var transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime());

            AmqpConnectionSettings amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString("N"),
                HostName     = this.connectionString.AmqpEndpoint.Host
            };

            var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await amqpConnection.OpenAsync(timeoutHelper.RemainingTime());

            var sessionSettings = new AmqpSessionSettings()
            {
                Properties = new Fields()
            };

            var amqpSession = amqpConnection.CreateSession(sessionSettings);
            await amqpSession.OpenAsync(timeoutHelper.RemainingTime());

            // This adds itself to amqpConnection.Extensions
            var cbsLink = new AmqpCbsLink(amqpConnection);

            await this.SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime());

            return(amqpSession);
        }
Пример #18
0
        public AmqpProtocolHead(
            ITransportSettings transportSettings,
            AmqpSettings amqpSettings,
            ITransportListenerProvider transportListenerProvider)
        {
            this.syncLock                  = new AsyncLock();
            this.transportSettings         = Preconditions.CheckNotNull(transportSettings, nameof(transportSettings));
            this.amqpSettings              = Preconditions.CheckNotNull(amqpSettings, nameof(amqpSettings));
            this.transportListenerProvider = Preconditions.CheckNotNull(transportListenerProvider);

            this.connectionSettings = new AmqpConnectionSettings
            {
                ContainerId = "DeviceGateway_" + Guid.NewGuid().ToString("N"),
                HostName    = transportSettings.HostName,
                // 'IdleTimeOut' on connection settings will be used to close connection if server hasn't
                // received any packet for 'IdleTimeout'
                // Open frame send to client will have the IdleTimeout set and the client will do heart beat
                // every 'IdleTimeout * 7 / 8'
                // If server doesn't receive any packet till 'ServiceMaxConnectionIdleTimeout' the connection will be closed
                IdleTimeOut = Constants.DefaultAmqpConnectionIdleTimeoutInMilliSeconds
            };

            this.incomingConnectionMap = new ConcurrentDictionary <uint, AmqpConnection>();
        }
        private async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            Logging.Enter(this, timeout, nameof(CreateSessionAsync));

            TransportBase transport = null;

            try
            {
                var timeoutHelper = new TimeoutHelper(timeout);
                _refreshTokenTimer.Cancel();

                AmqpSettings amqpSettings = CreateAmqpSettings();
                if (_useWebSocketOnly)
                {
                    // Try only AMQP transport over WebSocket
                    transport = _clientWebSocketTransport = (ClientWebSocketTransport) await CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime())
                                                            .ConfigureAwait(false);
                }
                else
                {
                    TlsTransportSettings tlsTransportSettings = CreateTlsTransportSettings();
                    var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
                    try
                    {
                        transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
                    }
                    catch (Exception e) when(!(e is AuthenticationException))
                    {
                        Logging.Error(this, e, nameof(CreateSessionAsync));

                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }

                        // AMQP transport over TCP failed. Retry AMQP transport over WebSocket
                        if (timeoutHelper.RemainingTime() != TimeSpan.Zero)
                        {
                            transport = _clientWebSocketTransport = (ClientWebSocketTransport) await CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                Logging.Info(this, $"Initialized {nameof(TransportBase)}, ws={_useWebSocketOnly}");

                var amqpConnectionSettings = new AmqpConnectionSettings
                {
                    MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                    ContainerId  = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture), // Use a human readable link name to help with debugging
                    HostName     = ConnectionString.AmqpEndpoint.Host,
                };

                var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
                await amqpConnection.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                Logging.Info(this, $"{nameof(AmqpConnection)} opened.");

                var sessionSettings = new AmqpSessionSettings
                {
                    Properties = new Fields(),
                };

                try
                {
                    AmqpSession amqpSession = amqpConnection.CreateSession(sessionSettings);
                    await amqpSession.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                    Logging.Info(this, $"{nameof(AmqpSession)} opened.");

                    // This adds itself to amqpConnection.Extensions
                    var cbsLink = new AmqpCbsLink(amqpConnection);
                    await SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime()).ConfigureAwait(false);

                    return(amqpSession);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    Logging.Error(this, ex, nameof(CreateSessionAsync));

                    _clientWebSocketTransport?.Dispose();
                    _clientWebSocketTransport = null;

                    if (amqpConnection.TerminalException != null)
                    {
                        throw AmqpClientHelper.ToIotHubClientContract(amqpConnection.TerminalException);
                    }

                    amqpConnection.SafeClose(ex);
                    throw;
                }
            }
            finally
            {
                Logging.Exit(this, timeout, nameof(CreateSessionAsync));
            }
        }
Пример #20
0
 public TestHelperAmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, bool
                                 isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
     : base(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings)
 {
 }
 public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
 {
     connectionSettings.ContainerId = this.GetType().Name;
     return(new AmqpConnection(transport, protocolHeader, false, amqpSettings, connectionSettings));
 }
Пример #22
0
        async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            this.refreshTokenTimer.Cancel();

            var           amqpSettings = this.CreateAmqpSettings();
            TransportBase transport;

            if (this.useWebSocketOnly)
            {
                // Try only Amqp transport over WebSocket
                transport = await this.CreateClientWebSocketTransport(timeoutHelper.RemainingTime());
            }
            else
            {
                var tlsTransportSettings   = this.CreateTlsTransportSettings();
                var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
                try
                {
                    transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime());
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    // Amqp transport over TCP failed. Retry Amqp transport over WebSocket
                    if (timeoutHelper.RemainingTime() != TimeSpan.Zero)
                    {
                        transport = await this.CreateClientWebSocketTransport(timeoutHelper.RemainingTime());
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            AmqpConnectionSettings amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString("N"),
                HostName     = this.connectionString.AmqpEndpoint.Host
            };

            var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await amqpConnection.OpenAsync(timeoutHelper.RemainingTime());

            var sessionSettings = new AmqpSessionSettings()
            {
                Properties = new Fields()
            };

            var amqpSession = amqpConnection.CreateSession(sessionSettings);
            await amqpSession.OpenAsync(timeoutHelper.RemainingTime());

            // This adds itself to amqpConnection.Extensions
            var cbsLink = new AmqpCbsLink(amqpConnection);

            await this.SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime());

            return(amqpSession);
        }
Пример #23
0
 public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader,
                                        bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
 {
     return(new AmqpConnection(transport, protocolHeader, false, amqpSettings, connectionSettings));
 }
Пример #24
0
            protected override IEnumerator <IteratorTask <object> .TaskStep> GetTasks()
            {
                ConnectivityMode connectivityMode;
                object           obj  = null;
                bool             flag = false;

                try
                {
                    object thisLock = this.relay.ThisLock;
                    object obj1     = thisLock;
                    obj = thisLock;
                    Monitor.Enter(obj1, ref flag);
                    if (this.relay.State != AmqpObjectState.OpenReceived && this.relay.State != AmqpObjectState.Opened)
                    {
                        goto Label0;
                    }
                }
                finally
                {
                    if (flag)
                    {
                        Monitor.Exit(obj);
                    }
                }
                Microsoft.ServiceBus.Common.TimeoutHelper timeoutHelper = new Microsoft.ServiceBus.Common.TimeoutHelper(this.timeout);
                string       host        = this.relay.serviceBusUri.Host;
                AmqpSettings amqpSetting = AmqpRelay.ConnectTask.CreateAmqpSettings();

                connectivityMode = (this.relay.connectivitySettings != null ? this.relay.connectivitySettings.Mode : ServiceBusEnvironment.SystemConnectivity.Mode);
                ConnectivityMode connectivityMode1 = connectivityMode;

                if (connectivityMode1 == ConnectivityMode.Tcp)
                {
                    TcpTransportSettings tcpTransportSetting = new TcpTransportSettings()
                    {
                        Host = host,
                        Port = 5671
                    };
                    TlsTransportSettings tlsTransportSetting = new TlsTransportSettings(tcpTransportSetting)
                    {
                        TargetHost = host
                    };
                    AmqpTransportInitiator amqpTransportInitiator = new AmqpTransportInitiator(amqpSetting, tlsTransportSetting);
                    yield return(base.CallTask(amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));
                }
                else if (connectivityMode1 == ConnectivityMode.Http || this.relay.httpConnectivitySettings != null)
                {
                    WebSocketTransportSettings webSocketTransportSetting = new WebSocketTransportSettings(this.relay.serviceBusUri);
                    AmqpTransportInitiator     amqpTransportInitiator1   = new AmqpTransportInitiator(amqpSetting, webSocketTransportSetting);
                    yield return(base.CallTask(amqpTransportInitiator1.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));
                }
                else
                {
                    TcpTransportSettings tcpTransportSetting1 = new TcpTransportSettings()
                    {
                        Host = host,
                        Port = 5671
                    };
                    TlsTransportSettings tlsTransportSetting1 = new TlsTransportSettings(tcpTransportSetting1)
                    {
                        TargetHost = host
                    };
                    AmqpTransportInitiator amqpTransportInitiator2 = new AmqpTransportInitiator(amqpSetting, tlsTransportSetting1);
                    yield return(base.CallTask(amqpTransportInitiator2.ConnectTaskAsync(Microsoft.ServiceBus.Common.TimeoutHelper.Divide(timeoutHelper.RemainingTime(), 2)), IteratorTask <TResult> .ExceptionPolicy.Continue));

                    if (base.LastTask.Exception != null)
                    {
                        if (timeoutHelper.RemainingTime() == TimeSpan.Zero)
                        {
                            throw base.LastTask.Exception;
                        }
                        WebSocketTransportSettings webSocketTransportSetting1 = new WebSocketTransportSettings(this.relay.serviceBusUri);
                        AmqpTransportInitiator     amqpTransportInitiator3    = new AmqpTransportInitiator(amqpSetting, webSocketTransportSetting1);
                        yield return(base.CallTask(amqpTransportInitiator3.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));
                    }
                }
                TransportBase transportBase = base.LastTaskResult <TransportBase>();

                string[] strArrays = host.Split(new char[] { '.' });
                strArrays[0] = string.Concat(strArrays[0], "-relay");
                AmqpConnectionSettings amqpConnectionSetting = new AmqpConnectionSettings()
                {
                    ContainerId = Guid.NewGuid().ToString(),
                    HostName    = string.Join(".", strArrays)
                };

                this.relay.connection = new AmqpConnection(transportBase, amqpSetting, amqpConnectionSetting);
                yield return(base.CallTask(this.relay.connection.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));

                AmqpSessionSettings amqpSessionSetting = new AmqpSessionSettings();
                AmqpSession         amqpSession        = this.relay.connection.CreateSession(amqpSessionSetting);

                yield return(base.CallTask(amqpSession.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));

                AmqpLinkSettings amqpLinkSetting = new AmqpLinkSettings()
                {
                    Role = new bool?(false),
                    InitialDeliveryCount = new uint?(0),
                    LinkName             = string.Concat("HttpRelayServer_Link_", Guid.NewGuid()),
                    Target          = new Target(this.relay.serviceBusUri),
                    Source          = new Source(this.relay.serviceBusUri),
                    TotalLinkCredit = 1000,
                    AutoSendFlow    = true
                };
                AmqpLinkSettings amqpLinkSetting1 = amqpLinkSetting;

                if (this.relay.tokenRenewer != null)
                {
                    amqpLinkSetting1.AddProperty(AmqpConstants.SimpleWebTokenPropertyName, this.relay.tokenRenewer.CurrentToken.Token);
                }
                if (!this.relay.TransportSecurityRequired)
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.TransportSecurityRequiredName, false);
                }
                if (!this.relay.RelayClientAuthorizationRequired)
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.ClientAuthenticationRequiredName, false);
                }
                if (this.relay.PublishToRegistry)
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.RequiresPublicRegistry, true);
                }
                if (!string.IsNullOrEmpty(this.relay.ClientAgent))
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.ClientAgent, this.relay.ClientAgent);
                }
                if (!string.IsNullOrEmpty(this.relay.DisplayName))
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.DisplayName, this.relay.DisplayName);
                }
                amqpLinkSetting1.AddProperty(ClientConstants.DynamicRelay, this.relay.IsDynamic);
                amqpLinkSetting1.AddProperty(ClientConstants.ListenerTypeName, this.relay.ListenerType.ToString());
                this.relay.link = new DuplexAmqpLink(amqpSession, amqpLinkSetting1);
                yield return(base.CallTask(this.relay.link.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));

                this.relay.link.SafeAddClosed(this.relay.onAmqpObjectClosed);
                this.relay.link.RegisterMessageListener((AmqpMessage msg) => this.relay.messageListener(this.relay.link, msg));
                this.relay.OnOnline();
Label0:
                yield break;
            }
        /// <summary>
        /// Performs the tasks needed to build and open a connection to the IoT Hub
        /// service.
        /// </summary>
        /// <param name="serviceEndpoint">The endpoint of the IoT Hub service to connect to.</param>
        /// <param name="iotHubName">The name of the IoT Hub to connect to.</param>
        /// <param name="sharedAccessKeyName">The name of the shared access key being used for authentication.</param>
        /// <param name="sharedAccessKey">The shared access key being used for authentication.</param>
        /// <param name="timeout">The maximum amount of time that establishing the connection should be allowed to take.</param>
        /// <returns>An <see cref="AmqpConnection" /> to the requested IoT Hub.</returns>
        /// <seealso href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-amqp-support"/>
        private static async Task <AmqpConnection> CreateAndOpenConnectionAsync(
            Uri serviceEndpoint,
            string iotHubName,
            string sharedAccessKeyName,
            string sharedAccessKey,
            TimeSpan timeout)
        {
            var hostName  = serviceEndpoint.Host;
            var userName  = $"{ sharedAccessKeyName }@sas.root.{ iotHubName }";
            var signature = BuildSignature($"{ hostName }{ serviceEndpoint.AbsolutePath }", sharedAccessKeyName, sharedAccessKey, TimeSpan.FromMinutes(5));
            var port      = 5671;

            // Create the layers of settings needed to establish the connection.

            var amqpVersion = new Version(1, 0, 0, 0);

            var tcpSettings = new TcpTransportSettings
            {
                Host = hostName,
                Port = port,
                ReceiveBufferSize = AmqpConstants.TransportBufferSize,
                SendBufferSize    = AmqpConstants.TransportBufferSize
            };

            var transportSettings = new TlsTransportSettings(tcpSettings)
            {
                TargetHost = hostName,
            };

            var connectionSettings = new AmqpConnectionSettings
            {
                IdleTimeOut  = (uint)TimeSpan.FromMinutes(1).TotalMilliseconds,
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString(),
                HostName     = hostName
            };

            var saslProvider = new SaslTransportProvider();

            saslProvider.Versions.Add(new AmqpVersion(amqpVersion));
            saslProvider.AddHandler(new SaslPlainHandler {
                AuthenticationIdentity = userName, Password = signature
            });

            var amqpProvider = new AmqpTransportProvider();

            amqpProvider.Versions.Add(new AmqpVersion(amqpVersion));

            var amqpSettings = new AmqpSettings();

            amqpSettings.TransportProviders.Add(saslProvider);
            amqpSettings.TransportProviders.Add(amqpProvider);

            // Create and open the connection, respecting the timeout constraint
            // that was received.

            var stopWatch = Stopwatch.StartNew();
            var initiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
            var transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false);

            try
            {
                var connection = new AmqpConnection(transport, amqpSettings, connectionSettings);
                await connection.OpenAsync(timeout.Subtract(stopWatch.Elapsed)).ConfigureAwait(false);

                return(connection);
            }
            catch
            {
                transport.Abort();
                throw;
            }
            finally
            {
                stopWatch.Stop();
            }
        }
Пример #26
0
        protected virtual async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout, CancellationToken token)
        {
            this.OnCreateSession();

            var timeoutHelper = new TimeoutHelper(timeout);

            AmqpSettings  amqpSettings = CreateAmqpSettings();
            TransportBase transport;

            token.ThrowIfCancellationRequested();

            switch (this.AmqpTransportSettings.GetTransportType())
            {
#if !WINDOWS_UWP && !PCL
            case TransportType.Amqp_WebSocket_Only:
                transport = await this.CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime());

                break;
#endif
            case TransportType.Amqp_Tcp_Only:
                TlsTransportSettings tlsTransportSettings = this.CreateTlsTransportSettings();
                var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
                transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime());

                break;

            default:
                throw new InvalidOperationException("AmqpTransportSettings must specify WebSocketOnly or TcpOnly");
            }

            var amqpConnectionSettings = new AmqpConnectionSettings()
            {
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString("N"),
                HostName     = this.hostName
            };

            var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            try
            {
                token.ThrowIfCancellationRequested();
                await amqpConnection.OpenAsync(timeoutHelper.RemainingTime());

                var sessionSettings = new AmqpSessionSettings()
                {
                    Properties = new Fields()
                };

                AmqpSession amqpSession = amqpConnection.CreateSession(sessionSettings);
                token.ThrowIfCancellationRequested();
                await amqpSession.OpenAsync(timeoutHelper.RemainingTime());

                // This adds itself to amqpConnection.Extensions
                var cbsLink = new AmqpCbsLink(amqpConnection);
                return(amqpSession);
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                if (amqpConnection.TerminalException != null)
                {
                    throw AmqpClientHelper.ToIotHubClientContract(amqpConnection.TerminalException);
                }

                amqpConnection.SafeClose(ex);
                throw;
            }
        }