public async Task Init( string name, IProviderRuntime providerRuntime, IProviderConfiguration config )
    {
      Log = providerRuntime.GetLogger( this.GetType().Name );

      try
      {
        ConfigureJsonSerializerSettings( config );

        if( !config.Properties.ContainsKey( "DataConnectionString" ) )
        {
          throw new BadProviderConfigException(
            "The DataConnectionString setting has not been configured in the cloud role. Please add a DataConnectionString setting with a valid Azure Storage connection string." );
        }
        else
        {
          var account = CloudStorageAccount.Parse( config.Properties[ "DataConnectionString" ] );
          var blobClient = account.CreateCloudBlobClient();
          var containerName = config.Properties.ContainsKey( "ContainerName" ) ? config.Properties[ "ContainerName" ] : "grainstate";
          container = blobClient.GetContainerReference( containerName );
          await container.CreateIfNotExistsAsync();
        }
      }
      catch( Exception ex )
      {
        Log.Error( 0, ex.ToString(), ex );
        throw;
      }
    }
Example #2
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Log = providerRuntime.GetLogger("Storage.AzureBlobStorage");

            try
            {
                this.Name = name;
                ConfigureJsonSerializerSettings(config);

                if (!config.Properties.ContainsKey("DataConnectionString")) throw new BadProviderConfigException("The DataConnectionString setting has not been configured in the cloud role. Please add a DataConnectionString setting with a valid Azure Storage connection string.");

                var account = CloudStorageAccount.Parse(config.Properties["DataConnectionString"]);
                var blobClient = account.CreateCloudBlobClient();
                var containerName = config.Properties.ContainsKey("ContainerName") ? config.Properties["ContainerName"] : "grainstate";
                container = blobClient.GetContainerReference(containerName);
                await container.CreateIfNotExistsAsync().ConfigureAwait(false);

                Log.Info((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, "Init: Name={0} ServiceId={1} {2}", name, providerRuntime.ServiceId.ToString(), string.Join(" ", FormatPropertyMessage(config)));
                Log.Info((int)AzureProviderErrorCode.AzureBlobProvider_ParamConnectionString, "AzureBlobStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(config.Properties["DataConnectionString"]));
            }
            catch (Exception ex)
            {
                Log.Error((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, ex.ToString(), ex);
                throw;
            }
        }
        public override async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            await base.Init(name, providerRuntime, config);

            long grainId = GrainCallBootstrapTestConstants.GrainId;
            int a = GrainCallBootstrapTestConstants.A;
            int b = GrainCallBootstrapTestConstants.B;
            ISimpleGrain grain = providerRuntime.GrainFactory.GetGrain<ISimpleGrain>(grainId, SimpleGrain.SimpleGrainNamePrefix);
            
            logger.Info("Setting A={0} on {1}", a, grainId);
            await grain.SetA(a);
            logger.Info("Setting B={0} on {1}", b, grainId);
            await grain.SetB(b);
            
            logger.Info("Getting AxB from {0}", grainId);
            int axb = await grain.GetAxB();
            logger.Info("Got AxB={0} from {1}", axb, grainId);
            
            int expected = a * b;
            int actual = axb;
            if (expected != actual) {
                throw new Exception(string.Format(
                    "Value returned to {0} by {1} should be {2} not {3}", 
                     GetType().Name, grainId, expected, actual));
            }
        }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            string connectionStringName = config.Properties["ConnectionStringName"];

            if (string.IsNullOrEmpty(connectionStringName))
            {
                this.Log.Info("Starting RavenDB Storage Provider InMemory");
                return this.InMemoryMode();
            }

            var settings = ConfigurationManager.ConnectionStrings[connectionStringName];

            var connectionStringBuilder = new DbConnectionStringBuilder
            {
                ConnectionString = settings.ConnectionString
            };

            object url;
            if (connectionStringBuilder.TryGetValue("Url", out url))
            {
                this.Log.Info("Starting RavenDB Storage Provider attached to server {0}", url);
                return this.ServerMode(connectionStringName);
            }

            object dataDir;
            if (connectionStringBuilder.TryGetValue("DataDir", out dataDir))
            {
                this.Log.Info("Starting RavenDB Storage Provider embedded in directory {0}", dataDir);
                return this.LocalMode(connectionStringName);
            }

            return TaskDone.Done;
        }
Example #5
0
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            this.logger = providerRuntime.GetLogger("Dashboard");

            var router = new Router();
            new DashboardController(router, TaskScheduler.Current,  providerRuntime);

            var options = new StartOptions
            {
                ServerFactory = "Nowin",
                Port = config.Properties.ContainsKey("Port") ? int.Parse(config.Properties["Port"]) : 8080,
            };

            var username = config.Properties.ContainsKey("Username") ? config.Properties["Username"] : null;
            var password = config.Properties.ContainsKey("Password") ? config.Properties["Password"] : null;
            try
            {
                host = WebApp.Start(options, app => new WebServer(router, username, password).Configuration(app));
            }
            catch (Exception ex)
            {
                this.logger.Error(10001, ex.ToString());
            }

            this.logger.Verbose($"Dashboard listening on {options.Port}");

            this.profiler = new GrainProfiler(TaskScheduler.Current, providerRuntime);

            var dashboardGrain = providerRuntime.GrainFactory.GetGrain<IDashboardGrain>(0);
            return dashboardGrain.Init();
        }
Example #6
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            serviceId = providerRuntime.ServiceId.ToString();

            if (!config.Properties.ContainsKey(DATA_CONNECTION_STRING) || string.IsNullOrWhiteSpace(config.Properties[DATA_CONNECTION_STRING]))
                throw new ArgumentException("DataConnectionString property not set");

            dataConnectionString = config.Properties["DataConnectionString"];

            if (config.Properties.ContainsKey(TABLE_NAME_PROPERTY))
                tableName = config.Properties[TABLE_NAME_PROPERTY];

            isDeleteStateOnClear = config.Properties.ContainsKey(DELETE_ON_CLEAR_PROPERTY) &&
                "true".Equals(config.Properties[DELETE_ON_CLEAR_PROPERTY], StringComparison.OrdinalIgnoreCase);

            Log = providerRuntime.GetLogger("Storage.AzureTableStorage." + id);

            var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}",
                Name, serviceId, tableName, isDeleteStateOnClear);

            if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY))
                useJsonFormat = "true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase);
            
            if (useJsonFormat)
            {
                jsonSettings = jsonSettings = OrleansJsonSerializer.SerializerSettings;
            }
            initMsg = String.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat);

            Log.Info((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, initMsg);
            Log.Info((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(dataConnectionString));
            tableDataManager = new GrainStateTableDataManager(tableName, dataConnectionString, Log);
            return tableDataManager.InitTableAsync();
        }
Example #7
0
 /// <summary>
 /// Initializes the provider during silo startup.
 /// </summary>
 /// <param name="name">The name of this provider instance.</param>
 /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
 /// <param name="config">Configuration info for this provider instance.</param>
 /// <returns>Completion promise for this operation.</returns>
 public override Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     this.Name = name;
     this.RootDirectory = config.Properties["RootDirectory"];
     if (string.IsNullOrWhiteSpace(RootDirectory)) throw new ArgumentException("RootDirectory property not set");
     DataManager = new GrainStateFileDataManager(RootDirectory);
     return base.Init(name, providerRuntime, config);
 }
 public virtual Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Name = name;
     logger = providerRuntime.GetLogger(GetType().Name);
     logger.Info("Init Name={0}", Name);
     Interlocked.Increment(ref initCount);
     return TaskDone.Done;
 }
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     //process uncommit event message(store uncommit event message to event-store)
     //var eventDispatcher = GrainFactory.GetGrain<IEventStoreDispatcher>(0);
     GrainInternalEventHandlerProvider.RegisterInternalEventHandler(this.GetType().Assembly);
      
     return TaskDone.Done;
 }
        //---------------------------------------------------------------------
        public async Task Init(string name, IProviderRuntime provider_runtime, IProviderConfiguration config)
        {
            Console.Title = "GameCloud.IM v1.00.000 build20161014";
            Console.WriteLine("GameCloud.IM v1.00.000 build20161014");

            var startup = new IMStartup();
            await startup.Start();
        }
 /// <summary>
 /// Initializes the storage provider.
 /// </summary>
 /// <param name="name">The name of this provider instance.</param>
 /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
 /// <param name="config">Configuration info for this provider instance.</param>
 /// <returns>Completion promise for this operation.</returns>
 public override Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     this.Name = name;
     this.ConnectionString = config.Properties["ConnectionString"];
     this.Database = config.Properties["Database"];
     if (string.IsNullOrWhiteSpace(ConnectionString)) throw new ArgumentException("ConnectionString property not set");
     if (string.IsNullOrWhiteSpace(Database)) throw new ArgumentException("Database property not set");
     DataManager = new GrainStateMongoDataManager(Database, ConnectionString);
     return base.Init(name, providerRuntime, config);
 }
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            logger = providerRuntime.GetLogger("SqlStatisticsPublisher");

            //TODO: Orleans does not yet provide the type of database used (to, e.g., to load dlls), so SQL Server is assumed.            
            database = RelationalStorageUtilities.CreateGenericStorageInstance(WellKnownRelationalInvariants.SqlServer, config.Properties["ConnectionString"]);

            await InitOrleansQueriesAsync();           
        }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            providerRuntime.SetInvokeInterceptor((method, request, grain, invoker) =>
            {
                RequestContext.Set("GrainInfo", 38);
                return invoker.Invoke(grain, request);
            });

            return Task.FromResult(0);
        }
        public override async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            await base.Init(name, providerRuntime, config);

            string latencyParam = config.Properties[LATENCY_PARAM_STRING];
            latency = latencyParam == null ? DefaultLatency : TimeSpan.Parse(latencyParam);
            Log.Info("Init: Fixed Store Latency={0}", latency);

            mockCallsOnly = config.Properties.ContainsKey(MOCK_CALLS_PARAM_STRING) &&
                "true".Equals(config.Properties[MOCK_CALLS_PARAM_STRING], StringComparison.OrdinalIgnoreCase);
        }
        /// <summary>
        /// Initializes publisher
        /// </summary>
        /// <param name="name">Provider name</param>
        /// <param name="providerRuntime">Provider runtime API</param>
        /// <param name="config">Provider configuration</param>
        /// <returns></returns>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            logger = providerRuntime.GetLogger("SqlStatisticsPublisher");

            string adoInvariant = AdoNetInvariants.InvariantNameSqlServer;
            if (config.Properties.ContainsKey("AdoInvariant"))
                adoInvariant = config.Properties["AdoInvariant"];

            orleansQueries = await RelationalOrleansQueries.CreateInstance(adoInvariant, config.Properties["ConnectionString"]);
        }
Example #16
0
        internal Task LoadStorageProviders(IDictionary<string, ProviderCategoryConfiguration> configs)
        {
            storageProviderLoader = new ProviderLoader<IStorageProvider>();
            providerRuntime = SiloProviderRuntime.Instance;

            if (!configs.ContainsKey(ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME))
                return TaskDone.Done;

            storageProviderLoader.LoadProviders(configs[ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME].Providers, this);
            return storageProviderLoader.InitProviders(providerRuntime);
        }
        public GrainController(Router router, TaskScheduler taskScheduler, IProviderRuntime providerRuntime)
        {
            this.TaskScheduler = taskScheduler;
            this.ProviderRuntime = providerRuntime;

            Action<string, Func<IOwinContext, IDictionary<string, string>, Task>> add = router.Add;

            add("/grain/:type/:id/:method", CallGrain);
            add("/grain/:type/:id/:method/:classprefix", CallGrain);
            add("/pinggrain", PingGrain);
            add("/ping", Ping);
        }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            var system = ClusterActorSystem.Current;
            var providers = config.Properties["providers"].Split(';');

            StreamPubSubWrapper.Hook(providers, stream => 
                StreamSubscriptionMatcher
                    .Match(system, stream)
                    .Select(x => new StreamPubSubMatch(x.Receive))
                    .ToArray());

            return TaskDone.Done;
        }
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            logger = providerRuntime.GetLogger("SqlStatisticsPublisher");

            string adoInvariant = AdoNetInvariants.InvariantNameSqlServer;
            if (config.Properties.ContainsKey("AdoInvariant"))
                adoInvariant = config.Properties["AdoInvariant"];

            database = RelationalStorageUtilities.CreateGenericStorageInstance(adoInvariant, config.Properties["ConnectionString"]);

            queryConstants = await database.InitializeOrleansQueriesAsync(); 
        }
        //---------------------------------------------------------------------
        public async Task Init(string name, IProviderRuntime provider_runtime, IProviderConfiguration config)
        {
            Console.Title = "GameCloud.IM.Test.App v1.00.000";

            Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            Console.WriteLine("IMTestAppOrleansBootstrap.Init()");
            Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            IMTestAppContext.Instance.Setup();

            var grain_player = provider_runtime.GrainFactory.GetGrain<IGrainIMTestAppPlayer>(Guid.NewGuid());
            await grain_player.Setup();

        }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Log = providerRuntime.GetLogger(this.GetType().FullName);

            ConnectString = config.Properties["DataConnectionString"];

            if (config.Properties.ContainsKey("Table"))
            {
                Table = config.Properties["Table"];
                CustomTable = true;
            }

            return TaskDone.Done;
        }
Example #22
0
        public GrainProfiler(TaskScheduler taskScheduler, IProviderRuntime providerRuntime)
        {
            this.TaskScheduler = taskScheduler;
            this.ProviderRuntime = providerRuntime;

            // register interceptor, wrapping any previously set interceptor
            this.innerInterceptor = providerRuntime.GetInvokeInterceptor();
            providerRuntime.SetInvokeInterceptor(this.InvokeInterceptor);
            siloAddress = providerRuntime.SiloIdentity.ToSiloAddress();

            // register timer to report every second
            timer = new Timer(this.ProcessStats, providerRuntime, 1 * 1000, 1 * 1000);

        }
        public DashboardController(Router router, TaskScheduler taskScheduler, IProviderRuntime providerRuntime)
        {

            this.TaskScheduler = taskScheduler;
            this.ProviderRuntime = providerRuntime;

            Action<string, Func<IOwinContext, IDictionary<string, string>, Task>> add = router.Add;

            add("/", Index);
            add("/index.min.js", IndexJs);
            add("/DashboardCounters", GetDashboardCounters);
            add("/RuntimeStats/:address", GetRuntimeStats);
            add("/HistoricalStats/:address", GetHistoricalStats);
            add("/GrainStats/:grain", GetGrainStats);
        }
 public async override Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Log = providerRuntime.GetLogger(this.GetType().FullName);
     Log.Info(0, "Init ErrorInjection={0}", ErrorInjection);
     try
     {
         SetErrorInjection(ErrorInjectionPoint.None);
         await base.Init(name, providerRuntime, config);
     }
     catch (Exception exc)
     {
         Log.Error(0, "Unexpected error during Init", exc);
         throw;
     }
 }
 public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     try
     {
         var account = CloudStorageAccount.Parse(config.Properties["DataConnectionString"]);
         var blobClient = account.CreateCloudBlobClient();
         var containerName = config.Properties.ContainsKey("ContainerName") ? config.Properties["ContainerName"] : "grainstate";
         container = blobClient.GetContainerReference(containerName);
         await container.CreateIfNotExistsAsync();
     }
     catch (Exception ex)
     {
         Log.Error(0, ex.ToString());
     }
 }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name = name;
            Log = providerRuntime.GetLogger(GetType().Name);

            string Url = config.Properties["Url"];
            string DefaultDatabase = config.Properties["DefaultDatabase"];

            if (string.IsNullOrEmpty(Url))
            {
                this.Log.Info("Starting RavenDB Storage Provider InMemory");
                return this.InMemoryMode();
            }

            return this.ServerMode(Url, DefaultDatabase);
        }
        public DynamoDBStorageProviderTests()
        {
            if (!AWSTestConstants.IsDynamoDbAvailable)
                throw new SkipException("Unable to connect to DynamoDB simulator");

            DefaultProviderRuntime = new StorageProviderManager(new GrainFactory(), null);
            ((StorageProviderManager)DefaultProviderRuntime).LoadEmptyStorageProviders(new ClientProviderRuntime(new GrainFactory(), null)).WaitWithThrow(TestConstants.InitTimeout);
            SerializationManager.InitializeForTesting();

            var properties = new Dictionary<string, string>();
            properties["DataConnectionString"] = $"Service={AWSTestConstants.Service}";
            var config = new ProviderConfiguration(properties, null);
            var provider = new DynamoDBStorageProvider();
            provider.Init("DynamoDBStorageProviderTests", DefaultProviderRuntime, config).Wait();
            PersistenceStorageTests = new CommonStorageTests(provider);
        }
Example #28
0
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Dashboard.OrleansTS = TaskScheduler.Current;
            Dashboard.ProviderRuntime = providerRuntime;

            this.logger = providerRuntime.GetLogger("Dashboard");

            var port = config.Properties.ContainsKey("port") ? int.Parse(config.Properties["port"]) : 8080;
            var url = $"http://localhost:{port}";

            this.host = new NancyHost(new Uri(url));
            this.host.Start();

            this.logger.Verbose($"Dashboard listening on {url}");

            var dashboardGrain = providerRuntime.GrainFactory.GetGrain<IDashboardGrain>(0);
            return dashboardGrain.Init();
        }
        /// <summary>
        /// Initializes the storage provider.
        /// </summary>
        /// <param name="name">The name of this provider instance.</param>
        /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
        /// <param name="config">Configuration info for this provider instance.</param>
        /// <returns>Completion promise for this operation.</returns> 
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            this.Name = name;
            this.ConfigSectionName = config.Properties["ConfigSectionName"];
            string useGuidAsStorageKeyString;
            config.Properties.TryGetValue("UseGuidAsStorageKey", out useGuidAsStorageKeyString);
            var useGuidAsStorageKey = true;//default is true

            if (!string.IsNullOrWhiteSpace(useGuidAsStorageKeyString))
                Boolean.TryParse(useGuidAsStorageKeyString, out useGuidAsStorageKey);

            this.UseGuidAsStorageKey = useGuidAsStorageKey;

            if (string.IsNullOrWhiteSpace(ConfigSectionName)) throw new ArgumentException("ConfigSectionName property not set");
            var configSection = ReadConfig(ConfigSectionName);
            DataManager = await GrainStateCouchbaseDataManager.Initialize(configSection);
            Log = providerRuntime.GetLogger(this.GetType().FullName);
        }
        public DashboardController(Router router, TaskScheduler taskScheduler, IProviderRuntime providerRuntime)
        {

            this.TaskScheduler = taskScheduler;
            this.ProviderRuntime = providerRuntime;

            Action<string, Func<IOwinContext, IDictionary<string, string>, Task>> add = router.Add;

            add("/", Index);
            add("/index.min.js", IndexJs);
            add("/DashboardCounters", GetDashboardCounters);
            add("/RuntimeStats/:address", GetRuntimeStats);
            add("/HistoricalStats/:address", GetHistoricalStats);

            //this.Get["/SiloPerformanceMetrics"] = GetSiloPerformanceMetrics;
            //this.Get["/ClientPerformanceMetrics"] = GetClientPerformanceMetrics;
            //this.Get["/Counters"] = GetCounters;
            //add("/ForceActivationCollection/{timespan:int}/{address?}", PostForceActivationCollection);
        }
Example #31
0
 Task IProvider.Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Name = name;
     return(Run(config.Properties));
 }
Example #32
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("The parameter must contain characters", nameof(name));
            }

            if (providerRuntime == null)
            {
                throw new ArgumentNullException(nameof(providerRuntime));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (!config.Properties.ContainsKey(DataConnectionStringPropertyName))
            {
                throw new BadProviderConfigException($"The {DataConnectionStringPropertyName} setting has not been configured. Add a {DataConnectionStringPropertyName} setting with a valid connection string.");
            }

            this.serializationManager = providerRuntime.ServiceProvider.GetRequiredService <SerializationManager>();

            //NOTE: StorageSerializationPicker should be defined outside and given as a parameter in constructor or via Init in IProviderConfiguration perhaps.
            //Currently this limits one's options to much to the current situation of providing only one serializer for serialization and deserialization
            //with no regard to state update or serializer changes. Maybe have this serialized as a JSON in props and read via a key?
            StorageSerializationPicker = new DefaultRelationalStoragePicker(this.ConfigureDeserializers(config, providerRuntime), this.ConfigureSerializers(config, providerRuntime));

            //NOTE: Currently there should be only one pair of providers given. That is, only UseJsonFormatPropertyName, UseXmlFormatPropertyName or UseBinaryFormatPropertyName.
            if (StorageSerializationPicker.Deserializers.Count > 1 || StorageSerializationPicker.Serializers.Count > 1)
            {
                throw new ArgumentException("Configuration error, only one serializer and deserializer should be given.", nameof(config));
            }

            if (StorageSerializationPicker.Deserializers.Count == 0 || StorageSerializationPicker.Serializers.Count == 0)
            {
                StorageSerializationPicker.Deserializers.Add(new OrleansStorageDefaultBinaryDeserializer(this.serializationManager, UseBinaryFormatPropertyName));
                StorageSerializationPicker.Serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializationManager, UseBinaryFormatPropertyName));
            }

            var connectionInvariant = config.Properties.ContainsKey(DataConnectionInvariantPropertyName) ? config.Properties[DataConnectionInvariantPropertyName] : DefaultAdoInvariantInvariantPropertyName;

            Storage   = RelationalStorage.CreateInstance(connectionInvariant, config.Properties[DataConnectionStringPropertyName]);
            ServiceId = providerRuntime.ServiceId.ToString();
            var queries = await Storage.ReadAsync(DefaultInitializationQuery, command => { }, (selector, resultSetCount, token) =>
            {
                return(Task.FromResult(Tuple.Create(selector.GetValue <string>("QueryKey"), selector.GetValue <string>("QueryText"))));
            }).ConfigureAwait(false);

            CurrentOperationalQueries = new RelationalStorageProviderQueries(
                queries.Single(i => i.Item1 == "WriteToStorageKey").Item2,
                queries.Single(i => i.Item1 == "ReadFromStorageKey").Item2,
                queries.Single(i => i.Item1 == "ClearStorageKey").Item2);

            var loggerFactory = providerRuntime.ServiceProvider.GetService <ILoggerFactory>();

            this.logger = loggerFactory.CreateLogger <AdoNetStorageProvider>();
            Log         = new LoggerWrapper(this.logger, this.GetType().FullName, loggerFactory);
            Name        = name;

            logger.Info((int)RelationalStorageProviderCodes.RelationalProviderInitProvider, $"Initialized storage provider: ServiceId={ServiceId} ProviderName={Name} Invariant={Storage.InvariantName} ConnectionString={Storage.ConnectionString}.");
        }
Example #33
0
 public StatisticsProviderManager(string kind, IProviderRuntime runtime)
 {
     providerKind = kind;
     this.runtime = runtime;
 }
Example #34
0
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Name      = name;
     directory = config.Properties["directory"];
     return(TaskDone.Done);
 }
Example #35
0
 public StorageProviderManager(IGrainFactory grainFactory, IServiceProvider serviceProvider, IProviderRuntime providerRuntime, LoadedProviderTypeLoaders loadedProviderTypeLoaders, ILoggerFactory loggerFactory)
 {
     this.providerRuntime  = providerRuntime;
     GrainFactory          = grainFactory;
     ServiceProvider       = serviceProvider;
     storageProviderLoader = new ProviderLoader <IStorageProvider>(loadedProviderTypeLoaders, loggerFactory);
     this.loggerFactory    = loggerFactory;
 }
 public async Task Init(IProviderRuntime providerRuntime)
 {
     await providerRuntime.GrainFactory.GetGrain <IProducerGrain>(Guid.Empty).Simulate();
 }
Example #37
0
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Name = name;
     return(Task.CompletedTask);
 }
Example #38
0
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            this.Name = name;

            this.logger = providerRuntime.GetLogger("Dashboard");

            this.dashboardTraceListener = new DashboardTraceListener();

            var port     = config.Properties.ContainsKey("Port") ? int.Parse(config.Properties["Port"]) : 8080;
            var hostname = config.Properties.ContainsKey("Host") ? config.Properties["Host"] : "*";

            var username = config.Properties.ContainsKey("Username") ? config.Properties["Username"] : null;
            var password = config.Properties.ContainsKey("Password") ? config.Properties["Password"] : null;

            var credentials = new UserCredentials(username, password);


            try
            {
                var builder = new WebHostBuilder()
                              .ConfigureServices(s => s
                                                 .AddSingleton(TaskScheduler.Current)
                                                 .AddSingleton(providerRuntime)
                                                 .AddSingleton(dashboardTraceListener)
                                                 )
                              .ConfigureServices(services =>
                {
                    services
                    .AddMvcCore()
                    .AddApplicationPart(typeof(DashboardController).GetTypeInfo().Assembly)
                    .AddJsonFormatters();
                })
                              .Configure(app =>
                {
                    if (credentials.HasValue())
                    {
                        // only when usename and password are configured
                        // do we inject basicauth middleware in the pipeline
                        app.UseMiddleware <BasicAuthMiddleware>(credentials);
                    }

                    app.UseMvc();
                })
                              .UseKestrel()
                              .UseUrls($"http://{hostname}:{port}");
                host = builder.Build();
                host.Start();
            }
            catch (Exception ex)
            {
                this.logger.Error(10001, ex.ToString());
            }

            this.logger.Verbose($"Dashboard listening on {port}");

            this.profiler = new GrainProfiler(TaskScheduler.Current, providerRuntime);

            var dashboardGrain = providerRuntime.GrainFactory.GetGrain <IDashboardGrain>(0);
            await dashboardGrain.Init();

            var siloGrain = providerRuntime.GrainFactory.GetGrain <ISiloGrain>(providerRuntime.ToSiloAddress());
            await siloGrain.SetOrleansVersion(typeof(SiloAddress).GetTypeInfo().Assembly.GetName().Version.ToString());

            Trace.Listeners.Add(dashboardTraceListener);

            // horrible hack to grab the scheduler
            // to allow the stats publisher to push
            // counters to grains
            OrleansScheduler = TaskScheduler.Current;
        }
Example #39
0
        private ICollection <IStorageDeserializer> ConfigureDeserializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
        {
            var deserializers = new List <IStorageDeserializer>();

            if (options.UseJsonFormat)
            {
                var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(providerRuntime.ServiceProvider), options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
                options.ConfigureJsonSerializerSettings?.Invoke(jsonSettings);

                deserializers.Add(new OrleansStorageDefaultJsonDeserializer(jsonSettings, JsonFormatSerializerTag));
            }

            if (options.UseXmlFormat)
            {
                deserializers.Add(new OrleansStorageDefaultXmlDeserializer(XmlFormatSerializerTag));
            }
            //if none are set true, configure binary format serializer by default
            if (!options.UseXmlFormat && !options.UseJsonFormat)
            {
                deserializers.Add(new OrleansStorageDefaultBinaryDeserializer(this.serializer, BinaryFormatSerializerTag));
            }

            return(deserializers);
        }
Example #40
0
 public PersistentStreamProvider(string name, StreamPubSubOptions pubsubOptions, StreamLifecycleOptions lifeCycleOptions, IProviderRuntime runtime, SerializationManager serializationManager, ILogger <PersistentStreamProvider> logger)
 {
     if (String.IsNullOrEmpty(name))
     {
         throw new ArgumentNullException(nameof(name));
     }
     if (runtime == null)
     {
         throw new ArgumentNullException(nameof(runtime));
     }
     this.pubsubOptions        = pubsubOptions ?? throw new ArgumentNullException(nameof(pubsubOptions));
     this.Name                 = name;
     this.lifeCycleOptions     = lifeCycleOptions ?? throw new ArgumentNullException(nameof(lifeCycleOptions));
     this.runtime              = runtime.ServiceProvider.GetRequiredService <IStreamProviderRuntime>();
     this.runtimeClient        = runtime.ServiceProvider.GetRequiredService <IRuntimeClient>();
     this.serializationManager = serializationManager ?? throw new ArgumentNullException(nameof(serializationManager));
     this.logger               = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Example #41
0
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Name = name;
     return(TaskDone.Done);
 }
 public DashboardController(TaskScheduler taskScheduler, IProviderRuntime providerRuntime, DashboardTraceListener traceListener)
 {
     this.traceListener   = traceListener;
     this.taskScheduler   = taskScheduler;
     this.providerRuntime = providerRuntime;
 }
Example #43
0
 /// <summary>
 /// Initializes the storage provider.
 /// </summary>
 /// <param name="name">The name of this provider instance.</param>
 /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
 /// <param name="config">Configuration info for this provider instance.</param>
 /// <returns>Completion promise for this operation.</returns>
 public virtual Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     return(Task.CompletedTask);
 }
        private ICollection <IStorageSerializer> ConfigureSerializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
        {
            var serializers = new List <IStorageSerializer>();

            if (options.UseJsonFormat)
            {
                var typeResolver = providerRuntime.ServiceProvider.GetRequiredService <ITypeResolver>();
                var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory),
                                                                                  options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
                serializers.Add(new OrleansStorageDefaultJsonSerializer(jsonSettings, JsonFormatSerializerTag));
            }
            if (options.UseXmlFormat)
            {
                serializers.Add(new OrleansStorageDefaultXmlSerializer(XmlFormatSerializerTag));
            }

            //if none are set true, configure binary format serializer by default
            if (!options.UseXmlFormat && !options.UseJsonFormat)
            {
                serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializationManager, BinaryFormatSerializerTag));
            }

            return(serializers);
        }
Example #45
0
 /// <summary>
 /// Initializes the storage provider.
 /// </summary>
 /// <param name="name">The name of this provider instance.</param>
 /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
 /// <param name="config">Configuration info for this provider instance.</param>
 /// <returns>Completion promise for this operation.</returns>
 public virtual Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Log = providerRuntime.GetLogger(this.GetType().FullName);
     return(Task.CompletedTask);
 }
Example #46
0
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     throw new System.NotImplementedException();
 }
 public LogConsistencyProviderManager(IGrainFactory grainFactory, IServiceProvider serviceProvider, IProviderRuntime runtime, LoadedProviderTypeLoaders loadedProviderTypeLoaders, ILoggerFactory loggerFactory)
 {
     GrainFactory       = grainFactory;
     ServiceProvider    = serviceProvider;
     this.runtime       = runtime;
     this.loggerFactory = loggerFactory;
     providerLoader     = new ProviderLoader <ILogConsistencyProvider>(loadedProviderTypeLoaders, loggerFactory);
 }
Example #48
0
 protected virtual JsonSerializerSettings ReturnSerializerSettings(ITypeResolver typeResolver, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     return(OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory), config));
 }
 public RabbitMQTestBootstrap(IProviderRuntime providerRuntime)
 {
     _providerRuntime = providerRuntime;
 }
Example #50
0
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Trace.TraceInformation("{0} Init called", GetType().Name);
     Name = name;
     return(TaskDone.Done);
 }
Example #51
0
 public void Init(IProviderRuntime ProviderRuntime)
 {
     serializationManager = ProviderRuntime.ServiceProvider.GetRequiredService <SerializationManager>();
 }
Example #52
0
        private ICollection <IStorageSerializer> ConfigureSerializers(IProviderConfiguration config, IProviderRuntime providerRuntime)
        {
            const string @true       = "true";
            var          serializers = new List <IStorageSerializer>();

            if (config.Properties.ContainsKey(UseJsonFormatPropertyName) && @true.Equals(config.Properties[UseJsonFormatPropertyName], StringComparison.OrdinalIgnoreCase))
            {
                var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.serializationManager, providerRuntime.GrainFactory), config);
                serializers.Add(new OrleansStorageDefaultJsonSerializer(jsonSettings, UseJsonFormatPropertyName));
            }

            if (config.Properties.ContainsKey(UseXmlFormatPropertyName) && @true.Equals(config.Properties[UseXmlFormatPropertyName], StringComparison.OrdinalIgnoreCase))
            {
                serializers.Add(new OrleansStorageDefaultXmlSerializer(UseXmlFormatPropertyName));
            }

            if (config.Properties.ContainsKey(UseBinaryFormatPropertyName) && @true.Equals(config.Properties[UseBinaryFormatPropertyName], StringComparison.OrdinalIgnoreCase))
            {
                serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializationManager, UseBinaryFormatPropertyName));
            }

            return(serializers);
        }
 public LogConsistencyProviderManager(IGrainFactory grainFactory, IServiceProvider serviceProvider, IProviderRuntime runtime)
 {
     GrainFactory    = grainFactory;
     ServiceProvider = serviceProvider;
     this.runtime    = runtime;
 }
 public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     Name             = name;
     connectionString = config.Properties["ConnectionString"];
     return(TaskDone.Done);
 }