Exemplo n.º 1
0
        public ConnectionConfiguration Parse(string connectionString)
        {
            ConnectionString = connectionString;

            connectionConfiguration = new ConnectionConfiguration();

            foreach (var pair in
                     (from property in typeof(ConnectionConfiguration).GetProperties()
                      let match = Regex.Match(connectionString, string.Format("[^\\w]*{0}=(?<{0}>[^;]+)", property.Name), RegexOptions.IgnoreCase)
                                  where match.Success
                                  select new
            {
                Property = property,
                match.Groups[property.Name].Value
            }))
            {
                pair.Property.SetValue(connectionConfiguration, TypeDescriptor.GetConverter(pair.Property.PropertyType).ConvertFromString(pair.Value), null);
            }

            if (ContainsKey("host"))
            {
                connectionConfiguration.ParseHosts(this["host"] as string);
            }

            if (settings.HasSetting("Endpoint.DurableMessages"))
            {
                connectionConfiguration.UsePublisherConfirms = settings.GetOrDefault <bool>("Endpoint.DurableMessages");
            }


            connectionConfiguration.ClientProperties["endpoint_name"] = settings.GetOrDefault <string>("EndpointName");

            connectionConfiguration.Validate();
            return(connectionConfiguration);
        }
Exemplo n.º 2
0
        public void Initialize(ReadOnlySettings settings, TransportInfrastructure transportInfrastructure, PipelineSettings pipelineSettings)
        {
            var unicastBusConfig        = settings.GetConfigSection <UnicastBusConfig>();
            var conventions             = settings.Get <Conventions>();
            var configuredUnicastRoutes = settings.GetOrDefault <ConfiguredUnicastRoutes>();
            var distributorAddress      = settings.GetOrDefault <string>("LegacyDistributor.Address");

            List <DistributionStrategy> distributionStrategies;

            if (settings.TryGet(out distributionStrategies))
            {
                foreach (var distributionStrategy in distributionStrategies)
                {
                    DistributionPolicy.SetDistributionStrategy(distributionStrategy);
                }
            }

            unicastBusConfig?.MessageEndpointMappings.Apply(Publishers, UnicastRoutingTable, transportInfrastructure.MakeCanonicalForm, conventions);
            configuredUnicastRoutes?.Apply(UnicastRoutingTable, conventions);

            pipelineSettings.Register(b =>
            {
                var router = new UnicastSendRouter(settings.GetOrDefault <string>("BaseInputQueueName"), settings.EndpointName(), settings.InstanceSpecificQueue(), distributorAddress, DistributionPolicy, UnicastRoutingTable, EndpointInstances, i => transportInfrastructure.ToTransportAddress(LogicalAddress.CreateRemoteAddress(i)));
                return(new UnicastSendRouterConnector(router));
            }, "Determines how the message being sent should be routed");

            pipelineSettings.Register(new UnicastReplyRouterConnector(), "Determines how replies should be routed");

            EnforceBestPractices = ShouldEnforceBestPractices(settings);
            if (EnforceBestPractices)
            {
                EnableBestPracticeEnforcement(conventions, pipelineSettings);
            }
        }
Exemplo n.º 3
0
 public ClientOutboxCleaner(ITimerService timerService, IClientOutboxStorage clientOutboxStorage, IClientOutboxStorageV2 clientOutboxStorageV2, ReadOnlySettings settings, CriticalError criticalError)
 {
     _timerService          = timerService;
     _clientOutboxStorage   = clientOutboxStorage;
     _clientOutboxStorageV2 = clientOutboxStorageV2;
     _criticalError         = criticalError;
     _frequency             = settings.GetOrDefault <TimeSpan?>("Persistence.Sql.Outbox.FrequencyToRunDeduplicationDataCleanup") ?? TimeSpan.FromMinutes(1);
     _maxAge = settings.GetOrDefault <TimeSpan?>("Persistence.Sql.Outbox.TimeToKeepDeduplicationData") ?? TimeSpan.FromDays(7);
 }
Exemplo n.º 4
0
        public FakeReceiver(ReadOnlySettings settings)
        {
            this.settings = settings;

            throwCritical = settings.GetOrDefault <bool>("FakeTransport.ThrowCritical");
            throwOnStop   = settings.GetOrDefault <bool>("FakeTransport.ThrowOnPumpStop");

            exceptionToThrow = settings.GetOrDefault <Exception>();
        }
Exemplo n.º 5
0
        private static DocumentStoreInitializer CreateDefaultDocumentStore(ReadOnlySettings settings)
        {
            var p = settings.GetOrDefault <ConnectionParameters>(RavenDbSettingsExtensions.DefaultConnectionParameters);

            if (p != null)
            {
                var storeByParams = new DocumentStore
                {
                    Url             = p.Url,
                    DefaultDatabase = p.DatabaseName ?? settings.EndpointName(),
                    ApiKey          = p.ApiKey,
                    Credentials     = p.Credentials
                };

                return(new DocumentStoreInitializer(storeByParams));
            }

            var initContext = CreateStoreByConnectionStringName(settings, "NServiceBus/Persistence/RavenDB", "NServiceBus/Persistence");

            if (initContext != null)
            {
                return(initContext);
            }

            return(CreateStoreByUrl(settings, "http://localhost:8080"));
        }
        public AzureServiceBusQueueCreator(ReadOnlySettings settings)
        {
            this.settings        = settings;
            systemQueueAddresses = settings.GetOrDefault <QueueBindings>()?.SendingAddresses ?? new List <string>();

            if (!this.settings.TryGet(WellKnownConfigurationKeys.Topology.Resources.Queues.DescriptionFactory, out descriptionFactory))
            {
                descriptionFactory = (queuePath, setting) => new QueueDescription(queuePath)
                {
                    LockDuration                           = setting.GetOrDefault <TimeSpan>(WellKnownConfigurationKeys.Topology.Resources.Queues.LockDuration),
                    MaxSizeInMegabytes                     = setting.GetOrDefault <long>(WellKnownConfigurationKeys.Topology.Resources.Queues.MaxSizeInMegabytes),
                    RequiresDuplicateDetection             = setting.GetOrDefault <bool>(WellKnownConfigurationKeys.Topology.Resources.Queues.RequiresDuplicateDetection),
                    DefaultMessageTimeToLive               = setting.GetOrDefault <TimeSpan>(WellKnownConfigurationKeys.Topology.Resources.Queues.DefaultMessageTimeToLive),
                    EnableDeadLetteringOnMessageExpiration = setting.GetOrDefault <bool>(WellKnownConfigurationKeys.Topology.Resources.Queues.EnableDeadLetteringOnMessageExpiration),
                    DuplicateDetectionHistoryTimeWindow    = setting.GetOrDefault <TimeSpan>(WellKnownConfigurationKeys.Topology.Resources.Queues.DuplicateDetectionHistoryTimeWindow),
                    MaxDeliveryCount                       = IsSystemQueue(queuePath) ? 10 : setting.GetOrDefault <int>(WellKnownConfigurationKeys.Topology.Resources.Queues.MaxDeliveryCount),
                    EnableBatchedOperations                = setting.GetOrDefault <bool>(WellKnownConfigurationKeys.Topology.Resources.Queues.EnableBatchedOperations),
                    EnablePartitioning                     = setting.GetOrDefault <bool>(WellKnownConfigurationKeys.Topology.Resources.Queues.EnablePartitioning),
                    SupportOrdering                        = setting.GetOrDefault <bool>(WellKnownConfigurationKeys.Topology.Resources.Queues.SupportOrdering),
                    AutoDeleteOnIdle                       = setting.GetOrDefault <TimeSpan>(WellKnownConfigurationKeys.Topology.Resources.Queues.AutoDeleteOnIdle),

                    EnableExpress = setting.GetConditional <bool>(queuePath, WellKnownConfigurationKeys.Topology.Resources.Queues.EnableExpress),
                    ForwardDeadLetteredMessagesTo = setting.GetConditional <string>(queuePath, WellKnownConfigurationKeys.Topology.Resources.Queues.ForwardDeadLetteredMessagesTo),
                };
            }
        }
Exemplo n.º 7
0
        public void Initialize(ReadOnlySettings settings, Func <LogicalAddress, string> toTransportAddress, PipelineSettings pipelineSettings, ReceiveConfiguration receiveConfiguration)
        {
            var conventions             = settings.Get <Conventions>();
            var configuredUnicastRoutes = settings.GetOrDefault <ConfiguredUnicastRoutes>();

            if (settings.TryGet(out List <DistributionStrategy> distributionStrategies))
            {
                foreach (var distributionStrategy in distributionStrategies)
                {
                    DistributionPolicy.SetDistributionStrategy(distributionStrategy);
                }
            }

            configuredUnicastRoutes?.Apply(UnicastRoutingTable, conventions);

            pipelineSettings.Register(b =>
            {
                var router = new UnicastSendRouter(receiveConfiguration == null, receiveConfiguration?.QueueNameBase, receiveConfiguration?.InstanceSpecificQueue, DistributionPolicy, UnicastRoutingTable, EndpointInstances, i => toTransportAddress(LogicalAddress.CreateRemoteAddress(i)));
                return(new UnicastSendRouterConnector(router));
            }, "Determines how the message being sent should be routed");

            pipelineSettings.Register(new UnicastReplyRouterConnector(), "Determines how replies should be routed");

            EnforceBestPractices = ShouldEnforceBestPractices(settings);
            if (EnforceBestPractices)
            {
                EnableBestPracticeEnforcement(conventions, pipelineSettings);
            }
        }
        public TransportInfrastructure(ReadOnlySettings settings)
        {
            configuration = new TransportConfiguration(settings);

            try
            {
                sqsClient = configuration.SqsClientFactory();
            }
            catch (AmazonClientException e)
            {
                var message = "Unable to configure the SQS client. Make sure the environment variables for AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set or the client factory configures the created client accordingly";
                Logger.Error(message, e);
                throw new Exception(message, e);
            }

            try
            {
                if (!string.IsNullOrEmpty(settings.GetOrDefault <string>(SettingsKeys.S3BucketForLargeMessages)))
                {
                    s3Client = configuration.S3ClientFactory();
                }
            }
            catch (AmazonClientException e)
            {
                var message = "Unable to configure the S3 client. Make sure the environment variables for AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set or the client factory configures the created client accordingly";
                Logger.Error(message, e);
                throw new Exception(message, e);
            }

            queueUrlCache = new QueueUrlCache(sqsClient);
        }
        void ApplyConventions(ReadOnlySettings settings)
        {
            if (DocumentIdConventionsExtensions.NeedToApplyDocumentIdConventionsToDocumentStore(settings))
            {
                var sagasEnabled    = settings.IsFeatureActive(typeof(Sagas));
                var timeoutsEnabled = settings.IsFeatureActive(typeof(TimeoutManager));
                var idConventions   = new DocumentIdConventions(docStore, settings.GetAvailableTypes(), settings.EndpointName(), sagasEnabled, timeoutsEnabled);
                docStore.Conventions.FindTypeTagName = idConventions.FindTypeTagName;
            }

            var store = docStore as DocumentStore;

            if (store == null)
            {
                return;
            }

            var isSendOnly = settings.GetOrDefault <bool>("Endpoint.SendOnly");

            if (!isSendOnly)
            {
                var usingDtc = settings.GetRequiredTransactionModeForReceives() == TransportTransactionMode.TransactionScope;
                if (usingDtc)
                {
                    throw new Exception("RavenDB Persistence does not support Distributed Transaction Coordinator (DTC) transactions. You must change the TransportTransactionMode in order to continue. See the RavenDB Persistence documentation for more details.");
                }
            }
#if NET452
            store.EnlistInDistributedTransactions = false;
#endif
        }
Exemplo n.º 10
0
        internal void ApplyMappings(ReadOnlySettings settings, Configuration configuration)
        {
            var tableNamingConvention = settings.GetOrDefault <Func <Type, string> >("NHibernate.Sagas.TableNamingConvention");

            var scannedAssemblies = settings.GetAvailableTypes().Select(t => t.Assembly).Distinct();

            foreach (var assembly in scannedAssemblies)
            {
                configuration.AddAssembly(assembly);
            }

            var             types = settings.GetAvailableTypes().Except(configuration.ClassMappings.Select(x => x.MappedClass));
            SagaModelMapper modelMapper;

            if (tableNamingConvention == null)
            {
                modelMapper = new SagaModelMapper(types);
            }
            else
            {
                modelMapper = new SagaModelMapper(types, tableNamingConvention);
            }

            configuration.AddMapping(modelMapper.Compile());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Provides a factory method for building a message serializer.
        /// </summary>
        public override Func <IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
        {
            Guard.AgainstNull(nameof(settings), settings);
            var encoding = settings.GetOrDefault <Encoding>("Serialization.Json.Encoding") ?? Encoding.UTF8;

            return(mapper => new JsonMessageSerializer(mapper, encoding));
        }
        public static IDocumentStore Get(ReadOnlySettings settings)
        {
            // The holder is known to be non-null since we set it in the ctor
            var holder = settings.Get <DocumentStoreHolder>();

            if (holder.DocumentStore == null)
            {
                var p = settings.GetOrDefault <ConnectionParameters>(RavenDbSettingsExtensions.DefaultConnectionParameters);
                if (p != null)
                {
                    holder.DocumentStore = new DocumentStore
                    {
                        Url             = p.Url,
                        DefaultDatabase = p.DatabaseName ?? settings.EndpointName(),
                        ApiKey          = p.ApiKey
                    };
                    Helpers.ApplyRavenDBConventions(settings, holder.DocumentStore);
                    holder.DocumentStore.Initialize();
                }
                else
                {
                    holder.DocumentStore = Helpers.CreateDocumentStoreByConnectionStringName(settings, "NServiceBus/Persistence/RavenDB", "NServiceBus/Persistence");

                    if (holder.DocumentStore == null)
                    {
                        holder.DocumentStore = Helpers.CreateDocumentStoreByUrl(settings, "http://localhost:8080");
                    }
                }
            }
            return(holder.DocumentStore);
        }
Exemplo n.º 13
0
        static IDictionary <string, string> InitFromConfiguration(ReadOnlySettings settings)
        {
            connectionStringSettingsCollection = NHibernateSettingRetriever.ConnectionStrings() ??
                                                 new ConnectionStringSettingsCollection();

            var configuration = CreateNHibernateConfiguration();

            var defaultConnectionString = settings.GetOrDefault <string>("NHibernate.Common.ConnectionString") ?? GetConnectionStringOrNull("NServiceBus/Persistence");
            var configurationProperties = configuration.Properties;

            var appSettingsSection = NHibernateSettingRetriever.AppSettings() ?? new NameValueCollection();

            foreach (string appSetting in appSettingsSection)
            {
                var match = PropertyRetrievalRegex.Match(appSetting);
                if (match.Success)
                {
                    configurationProperties[match.Groups[1].Value] = appSettingsSection[appSetting];
                }
            }
            if (!string.IsNullOrEmpty(defaultConnectionString))
            {
                configurationProperties[Environment.ConnectionString] = defaultConnectionString;
            }

            if (!configurationProperties.ContainsKey(Environment.Dialect))
            {
                configurationProperties[Environment.Dialect] = DefaultDialect;
            }
            return(configurationProperties);
        }
        public override Func <IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
        {
            var builder         = new TOriginalSerializationDefintion().Configure(settings);
            var scenarioContext = settings.GetOrDefault <ScenarioContext>();

            return(mapper => Builder(builder, mapper, scenarioContext));
        }
 public override Func <IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
 {
     return(mapper =>
     {
         var value = settings.GetOrDefault <string>(Key);
         return new MyCustomSerializer(value);
     });
 }
Exemplo n.º 16
0
        public static ReceiveConfiguration Build(ReadOnlySettings settings, TransportComponent.Configuration transportConfiguration)
        {
            var isSendOnlyEndpoint = settings.Get <bool>("Endpoint.SendOnly");

            if (isSendOnlyEndpoint)
            {
                if (settings.HasExplicitValue(ReceiveSettingsExtensions.CustomLocalAddressKey))
                {
                    throw new Exception($"Specifying a base name for the input queue using `{nameof(ReceiveSettingsExtensions.OverrideLocalAddress)}(baseInputQueueName)` is not supported for send-only endpoints.");
                }
                return(null);
            }

            var endpointName   = settings.EndpointName();
            var discriminator  = settings.GetOrDefault <string>("EndpointInstanceDiscriminator");
            var queueNameBase  = settings.GetOrDefault <string>(ReceiveSettingsExtensions.CustomLocalAddressKey) ?? endpointName;
            var purgeOnStartup = settings.GetOrDefault <bool>("Transport.PurgeOnStartup");

            //note: This is an old hack, we are passing the endpoint name to bind but we only care about the properties
            var mainInstanceProperties = transportConfiguration.BindToLocalEndpoint(new EndpointInstance(endpointName)).Properties;

            var logicalAddress = LogicalAddress.CreateLocalAddress(queueNameBase, mainInstanceProperties);

            var localAddress = transportConfiguration.ToTransportAddress(logicalAddress);

            string instanceSpecificQueue = null;

            if (discriminator != null)
            {
                instanceSpecificQueue = transportConfiguration.ToTransportAddress(logicalAddress.CreateIndividualizedAddress(discriminator));
            }

            var transactionMode = GetRequiredTransactionMode(settings);

            var pushRuntimeSettings = GetDequeueLimitations(settings);

            return(new ReceiveConfiguration(
                       logicalAddress,
                       queueNameBase,
                       localAddress,
                       instanceSpecificQueue,
                       transactionMode,
                       pushRuntimeSettings,
                       purgeOnStartup,
                       settings.GetOrDefault <Notification <ReceivePipelineCompleted> >() ?? new Notification <ReceivePipelineCompleted>()));
        }
        static T GetConditional <T>(this ReadOnlySettings settings, Func <bool> condition, string key)
        {
            if (condition())
            {
                return(settings.GetOrDefault <T>(key));
            }

            return(settings.GetDefault <T>(key));
        }
Exemplo n.º 18
0
        internal static DocumentStoreInitializer GetUninitializedDocumentStore <TStorageType>(ReadOnlySettings settings)
            where TStorageType : StorageType
        {
            // First try to get a document store specific to a storage type (Subscriptions, Gateway, etc.)
            var docStoreInitializer = settings.GetOrDefault <DocumentStoreInitializer>(featureSettingsKeys[typeof(TStorageType)]);

            // Next try finding a shared DocumentStore
            if (docStoreInitializer == null)
            {
                docStoreInitializer = settings.GetOrDefault <DocumentStoreInitializer>(defaultDocStoreSettingsKey);
            }

            if (docStoreInitializer == null)
            {
                throw new Exception($"In order to use RavenDB as persistence for {typeof(TStorageType).Name}, a DocumentStore instance or builder must be set using persistence.{nameof(RavenDbSettingsExtensions.SetDefaultDocumentStore)}(...).");
            }

            return(docStoreInitializer);
        }
Exemplo n.º 19
0
        public static StartupCheckResult CheckForInvalidSettings(ReadOnlySettings settings)
        {
            var externalTimeoutManagerAddress = settings.GetOrDefault <string>("NServiceBus.ExternalTimeoutManagerAddress") != null;
            var timeoutManagerFeatureActive   = settings.GetOrDefault <FeatureState>(typeof(TimeoutManager).FullName) == FeatureState.Active;
            var timeoutManagerDisabled        = settings.GetOrDefault <bool>(WellKnownConfigurationKeys.DelayedDelivery.DisableTimeoutManager);

            if (externalTimeoutManagerAddress)
            {
                return(StartupCheckResult.Failed("An external timeout manager address cannot be configured because the timeout manager is not being used for delayed delivery."));
            }

            if (!timeoutManagerDisabled && !timeoutManagerFeatureActive)
            {
                return(StartupCheckResult.Failed(
                           "The timeout manager is not active, but the transport has not been properly configured for this. "
                           + "Use 'EndpointConfiguration.UseTransport<AzureStorageQueueTransport>().DelayedDelivery().DisableTimeoutManager()' to ensure delayed messages can be sent properly."));
            }

            return(StartupCheckResult.Success);
        }
Exemplo n.º 20
0
        public SqsTransportInfrastructure(ReadOnlySettings settings)
        {
            this.settings           = settings;
            messageMetadataRegistry = this.settings.Get <MessageMetadataRegistry>();
            configuration           = new TransportConfiguration(settings);

            if (settings.HasSetting(SettingsKeys.DisableNativePubSub))
            {
                OutboundRoutingPolicy = new OutboundRoutingPolicy(OutboundRoutingType.Unicast, OutboundRoutingType.Unicast, OutboundRoutingType.Unicast);
            }
            else
            {
                OutboundRoutingPolicy = new OutboundRoutingPolicy(OutboundRoutingType.Unicast, OutboundRoutingType.Multicast, OutboundRoutingType.Unicast);
            }

            try
            {
                sqsClient = configuration.SqsClientFactory();
            }
            catch (AmazonClientException e)
            {
                var message = "Unable to configure the SQS client. Make sure the environment variables for AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set or the client factory configures the created client accordingly";
                Logger.Error(message, e);
                throw new Exception(message, e);
            }

            try
            {
                snsClient = configuration.SnsClientFactory();
            }
            catch (AmazonClientException e)
            {
                var message = "Unable to configure the SNS client. Make sure the environment variables for AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set or the client factory configures the created client accordingly";
                Logger.Error(message, e);
                throw new Exception(message, e);
            }

            try
            {
                if (!string.IsNullOrEmpty(settings.GetOrDefault <string>(SettingsKeys.S3BucketForLargeMessages)))
                {
                    s3Client = configuration.S3ClientFactory();
                }
            }
            catch (AmazonClientException e)
            {
                var message = "Unable to configure the S3 client. Make sure the environment variables for AWS_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set or the client factory configures the created client accordingly";
                Logger.Error(message, e);
                throw new Exception(message, e);
            }

            queueCache = new QueueCache(sqsClient, configuration);
            topicCache = new TopicCache(snsClient, messageMetadataRegistry, configuration);
        }
Exemplo n.º 21
0
        public DistributorReadyMessageProcessor(IBuilder builder, ReadOnlySettings settings)
        {
            disable = !settings.GetOrDefault <bool>("Distributor.Enabled");

            if (disable)
            {
                return;
            }

            workerAvailabilityManager = builder.Build <IWorkerAvailabilityManager>();
            address = MasterNodeConfiguration.GetMasterNodeAddress(settings).SubScope("distributor.control");
        }
        public DistributorReadyMessageProcessor(IBuilder builder, ReadOnlySettings settings)
        {
            disable = !settings.GetOrDefault<bool>("Distributor.Enabled");

            if (disable)
            {
                return;
            }

            workerAvailabilityManager = builder.Build<IWorkerAvailabilityManager>();
            address = MasterNodeConfiguration.GetMasterNodeAddress(settings).SubScope("distributor.control");
        }
        static bool ShouldIndividualize(AzureServiceBusQueueConfig configSection, ReadOnlySettings settings)
        {
            // if this setting is set, then the core is responsible for individualization
            if (settings != null && settings.HasExplicitValue("IndividualizeEndpointAddress"))
            {
                return false;
            }

            // if explicitly set in code
            if (settings != null && settings.HasExplicitValue("ScaleOut.UseSingleBrokerQueue"))
                return !settings.Get<bool>("ScaleOut.UseSingleBrokerQueue");

            // if explicitly set in config
            if (configSection != null)
                return configSection.QueuePerInstance;

            // if default is set
            if (settings != null && !settings.GetOrDefault<bool>("ScaleOut.UseSingleBrokerQueue"))
                return !settings.GetOrDefault<bool>("ScaleOut.UseSingleBrokerQueue");

            return false;
        }
        public DistributorSatellite(IBuilder builder, ReadOnlySettings settings)
        {
            disable = !settings.GetOrDefault<bool>("Distributor.Enabled");

            if (disable)
            {
                return;
            }

            messageSender = builder.Build<ISendMessages>();
            workerManager = builder.Build<IWorkerAvailabilityManager>();
            address = MasterNodeConfiguration.GetMasterNodeAddress(settings);
        }
        public DistributorSatellite(IBuilder builder, ReadOnlySettings settings)
        {
            disable = !settings.GetOrDefault <bool>("Distributor.Enabled");

            if (disable)
            {
                return;
            }

            messageSender = builder.Build <ISendMessages>();
            workerManager = builder.Build <IWorkerAvailabilityManager>();
            address       = MasterNodeConfiguration.GetMasterNodeAddress(settings);
        }
Exemplo n.º 26
0
        internal static DocumentStoreInitializer GetUninitializedDocumentStore <TStorageType>(ReadOnlySettings settings)
            where TStorageType : StorageType
        {
            // First try to get a document store specific to a storage type (Subscriptions, Gateway, etc.)
            var docStoreInitializer = settings.GetOrDefault <DocumentStoreInitializer>(featureSettingsKeys[typeof(TStorageType)]);

            // Next, if a connection string name exists for the storage type, create based on that
            if (docStoreInitializer == null)
            {
                docStoreInitializer = CreateStoreByConnectionStringName(settings, connStrKeys[typeof(TStorageType)]);
            }

            // Next try finding a shared DocumentStore
            if (docStoreInitializer == null)
            {
                docStoreInitializer = settings.GetOrDefault <DocumentStoreInitializer>(defaultDocStoreSettingsKey);
            }

            // Otherwise, we need to create it ourselves, but do so only once.
            if (docStoreInitializer == null)
            {
                // The holder is known to be non-null since we set it in SharedDocumentStore feature ctor
                var holder = settings.Get <SingleSharedDocumentStore>();
                if (holder.Initializer == null)
                {
                    holder.Initializer = CreateDefaultDocumentStore(settings);
                }

                docStoreInitializer = holder.Initializer;
            }

            if (docStoreInitializer == null)
            {
                throw new Exception($"RavenDB is configured as persistence for {typeof(TStorageType).Name} and no DocumentStore instance could be found.");
            }

            return(docStoreInitializer);
        }
Exemplo n.º 27
0
        static string GetDefaultEndpointAddress(ReadOnlySettings settings)
        {
            if (!settings.GetOrDefault <bool>("IndividualizeEndpointAddress"))
            {
                return(settings.EndpointName());
            }

            if (!settings.HasSetting("EndpointInstanceDiscriminator"))
            {
                throw new Exception("No endpoint instance discriminator found. This value is usually provided by your transport so please make sure you're on the lastest version of your specific transport or set the discriminator using 'configuration.ScaleOut().UniqueQueuePerEndpointInstance(myDiscriminator)'");
            }

            return(settings.EndpointName() + settings.Get <string>("EndpointInstanceDiscriminator"));
        }
Exemplo n.º 28
0
        static string GetDefaultEndpointAddress(ReadOnlySettings settings)
        {
            if (!settings.GetOrDefault<bool>("IndividualizeEndpointAddress"))
            {
                return settings.EndpointName();
            }

            if (!settings.HasSetting("EndpointInstanceDiscriminator"))
            {
                throw new Exception("No endpoint instance discriminator found. This value is usually provided by your transport so please make sure you're on the lastest version of your specific transport or set the discriminator using 'configuration.ScaleOut().UniqueQueuePerEndpointInstance(myDiscriminator)'");
            }

            return settings.EndpointName() + settings.Get<string>("EndpointInstanceDiscriminator");
        }
Exemplo n.º 29
0
        public static StartupCheckResult CheckForInvalidSettings(ReadOnlySettings settings)
        {
            var timeoutManagerFeatureActive   = settings.IsFeatureActive(typeof(TimeoutManager));
            var timeoutManagerShouldBeEnabled = settings.GetOrDefault <bool>(WellKnownConfigurationKeys.DelayedDelivery.EnableTimeoutManager);

            if (timeoutManagerShouldBeEnabled && !timeoutManagerFeatureActive)
            {
                return(StartupCheckResult.Failed(
                           "The timeout manager is not active, but the transport has not been properly configured for this. "
                           + "Use 'EndpointConfiguration.UseTransport<AzureStorageQueueTransport>().DelayedDelivery().DisableTimeoutManager()' to ensure delayed messages can be sent properly."));
            }

            return(StartupCheckResult.Success);
        }
Exemplo n.º 30
0
        internal void ApplyMappings(ReadOnlySettings settings, Configuration configuration)
        {
            var tableNamingConvention = settings.GetOrDefault <Func <Type, string> >("NHibernate.Sagas.TableNamingConvention");

            var scannedAssemblies = settings.GetAvailableTypes().Select(t => t.Assembly).Distinct();

            foreach (var assembly in scannedAssemblies)
            {
                configuration.AddAssembly(assembly);
            }

            var allSagaMetadata = settings.Get <SagaMetadataCollection>();
            var types           = settings.GetAvailableTypes().Except(configuration.ClassMappings.Select(x => x.MappedClass));

            SagaModelMapper.AddMappings(configuration, allSagaMetadata, types, tableNamingConvention);
        }
Exemplo n.º 31
0
        AzureStorageAddressingSettings GetAddressing(ReadOnlySettings settings, string connectionString)
        {
            var addressing = settings.GetOrDefault <AzureStorageAddressingSettings>() ?? new AzureStorageAddressingSettings();

            if (settings.TryGet <AccountConfigurations>(out var accounts) == false)
            {
                accounts = new AccountConfigurations();
            }

            var shouldUseAccountNames = settings.TryGet(WellKnownConfigurationKeys.UseAccountNamesInsteadOfConnectionStrings, out object _);

            addressing.SetAddressGenerator(addressGenerator);
            addressing.RegisterMapping(accounts.defaultAlias, accounts.mappings, shouldUseAccountNames);
            addressing.Add(new AccountInfo(QueueAddress.DefaultStorageAccountAlias, connectionString), false);

            return(addressing);
        }
        /// <summary>
        /// Initializes the <see cref="ConfigureNHibernate"/> NHibernate properties.
        /// </summary>
        /// <remarks>
        /// Configure NHibernate using the <c>&lt;hibernate-configuration&gt;</c> section
        /// from the application config file, if found, or the file <c>hibernate.cfg.xml</c> if the
        /// <c>&lt;hibernate-configuration&gt;</c> section not include the session-factory configuration.
        /// However those settings can be overwritten by our own configuration settings if specified.
        /// </remarks>
        void Init()
        {
            connectionStringSettingsCollection = NHibernateSettingRetriever.ConnectionStrings() ??
                                                 new ConnectionStringSettingsCollection();

            var configuration = CreateNHibernateConfiguration();

            var defaultConnectionString = settings.GetOrDefault <string>("NHibernate.Common.ConnectionString") ?? GetConnectionStringOrNull("NServiceBus/Persistence");
            var configurationProperties = configuration.Properties;

            var appSettingsSection = NHibernateSettingRetriever.AppSettings() ?? new NameValueCollection();

            foreach (string appSetting in appSettingsSection)
            {
                var match = PropertyRetrievalRegex.Match(appSetting);
                if (match.Success)
                {
                    configurationProperties[match.Groups[1].Value] = appSettingsSection[appSetting];
                }
            }
            if (!String.IsNullOrEmpty(defaultConnectionString))
            {
                configurationProperties[Environment.ConnectionString] = defaultConnectionString;
            }

            if (!configurationProperties.ContainsKey(Environment.Dialect))
            {
                configurationProperties[Environment.Dialect] = DefaultDialect;
            }

            TimeoutPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                  "NServiceBus/Persistence/NHibernate/Timeout");
            SubscriptionStorageProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                     "NServiceBus/Persistence/NHibernate/Subscription");
            SagaPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                               "NServiceBus/Persistence/NHibernate/Saga");
            GatewayDeduplicationProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                      "NServiceBus/Persistence/NHibernate/Deduplication");
            DistributorPersisterProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                                      "NServiceBus/Persistence/NHibernate/Distributor");
            OutboxProperties = OverrideConnectionStringSettingIfNotNull(configurationProperties,
                                                                        "NServiceBus/Persistence/NHibernate/Outbox");
        }
        internal static void VerifyStorageEngineSupportsDtcIfRequired(IDocumentStore store, ReadOnlySettings settings)
        {
            var suppressDistributedTransactions = settings.GetRequiredTransactionModeForReceives() != TransportTransactionMode.TransactionScope;
            if (suppressDistributedTransactions)
            {
                return;
            }

            if (settings.GetOrDefault<bool>("RavenDB.IConfirmToUseAStorageEngineWhichDoesntSupportDtcWhilstLeavingDistributedTransactionSupportEnabled"))
            {
                return;
            }

            var stats = store.DatabaseCommands.GetStatistics();
            if (!stats.SupportsDtc)
            {
                throw new InvalidOperationException(StorageEngineDoesntSupportDtcMessage);
            }
        }
Exemplo n.º 34
0
        void ApplyConventions(ReadOnlySettings settings)
        {
            var store = docStore as DocumentStore;
            if (store == null)
            {
                return;
            }

            UnwrappedSagaListener.Register(store);

            var isSendOnly = settings.GetOrDefault<bool>("Endpoint.SendOnly");
            if (!isSendOnly)
            {
                var usingDtc = settings.GetRequiredTransactionModeForReceives() == TransportTransactionMode.TransactionScope;
                if (usingDtc)
                {
                    throw new Exception("RavenDB does not support Distributed Transaction Coordinator (DTC) transactions. You must change the TransportTransactionMode in order to continue. See the RavenDB Persistence documentation for more details.");
                }
            }
        }
        private static DocumentStoreInitializer CreateDefaultDocumentStore(ReadOnlySettings settings)
        {
            var p = settings.GetOrDefault <ConnectionParameters>(MartenSettingsExtensions.DefaultConnectionParameters);

            if (p != null)
            {
                var storeByParams = DocumentStore.For(p.ConnectionString);

                return(new DocumentStoreInitializer(storeByParams));
            }

            var initContext = CreateStoreByConnectionStringName("NServiceBus/Persistence/Marten", "NServiceBus/Persistence");

            if (initContext != null)
            {
                return(initContext);
            }

            return(null);
        }
        internal void ApplyMappings(ReadOnlySettings settings, Configuration configuration)
        {
            var tableNamingConvention = settings.GetOrDefault<Func<Type, string>>("NHibernate.Sagas.TableNamingConvention");

            var scannedAssemblies = settings.GetAvailableTypes().Select(t => t.Assembly).Distinct();

            foreach (var assembly in scannedAssemblies)
            {
                configuration.AddAssembly(assembly);
            }

            var types = settings.GetAvailableTypes().Except(configuration.ClassMappings.Select(x => x.MappedClass));
            SagaModelMapper modelMapper;
            if (tableNamingConvention == null)
            {
                modelMapper = new SagaModelMapper(types);
            }
            else
            {
                modelMapper = new SagaModelMapper(types, tableNamingConvention);
            }

            configuration.AddMapping(modelMapper.Compile());
        }
 internal static JsonSerializerSettings GetJsonSerializerSettings(ReadOnlySettings settings)
 {
     return settings.GetOrDefault<JsonSerializerSettings>("SqlPersistence.Saga.JsonSerializerSettings");
 }
 internal static RetrieveVersionSpecificJsonSettings GetVersionSettings(ReadOnlySettings settings)
 {
     return settings.GetOrDefault<RetrieveVersionSpecificJsonSettings>();
 }
Exemplo n.º 39
0
 /// <summary>
 /// Provides a factory method for building a message serializer.
 /// </summary>
 public override Func<IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
 {
     var encoding = settings.GetOrDefault<Encoding>("Serialization.Json.Encoding") ?? Encoding.UTF8;
     return mapper => new JsonMessageSerializer(mapper, encoding);
 }
 internal static Func<TextReader, JsonReader> GetReaderCreator(ReadOnlySettings settings)
 {
     return settings.GetOrDefault<Func<TextReader, JsonReader>>("SqlPersistence.Saga.ReaderCreator");
 }
 internal static bool NeedToApplyDocumentIdConventionsToDocumentStore(ReadOnlySettings settings)
 {
     return settings.GetOrDefault<bool>(DoNotUseLegacyConventionsSettingsKey) == false;
 }