private void OnInitialize() { var selfInstance = InstanceEnumerator.EnumerateInstances().First(i => i.IsSelf); cloudStorageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(ConfigurationSettingsKeys.StorageConnectionString)); log.Info("Storage account selected: {0}",cloudStorageAccount.BlobEndpoint); cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); log.Info("Storage client created"); var containerName = ConfigurationProvider.GetSetting(ConfigurationSettingsKeys.StorageContainerName,"ravendb"); // In order to force a connection we just enumerate all available containers: var availableContainers = cloudBlobClient.ListContainers().ToArray(); foreach (var container in availableContainers) { log.Info("Available container: {0}",container.Name); } if (!availableContainers.Any(c => c.Name.Equals(containerName))) { log.Info("Container {0} does not exist, creating",containerName); // Container does not exist: cloudBlobClient.GetContainerReference(containerName).Create(); } cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName); log.Info("Container {0} selected",cloudBlobContainer.Name); localCache = RoleEnvironment.GetLocalResource(ConfigurationSettingsKeys.StorageCacheResource); log.Info("Cache resource retrieved: {0}, path: {1}",localCache.Name,localCache.RootPath); CloudDrive.InitializeCache(localCache.RootPath, localCache.MaximumSizeInMegabytes); log.Info("Cache initialized: {0} mb",localCache.MaximumSizeInMegabytes); var driveName = string.Format("{0}{1}.vhd", selfInstance.InstanceType, selfInstance.InstanceIndex).ToLowerInvariant(); log.Info("Virtual drive name: {0}",driveName); var pageBlob = cloudBlobContainer.GetPageBlobReference(driveName); log.Info("Virtual drive blob: {0}",pageBlob.Uri); cloudDrive = cloudStorageAccount.CreateCloudDrive(pageBlob.Uri.ToString()); log.Info("Virtual drive created: {0}",cloudDrive.Uri); var storageSize = ConfigurationProvider.GetSetting(ConfigurationSettingsKeys.StorageSize, 50000); log.Info("Storage size: {0} mb",storageSize); cloudDrive.CreateIfNotExist(storageSize); log.Info("Virtual drive initialized: {0}",cloudDrive.Uri); var mountedDirectoryPath = cloudDrive.Mount(storageSize, DriveMountOptions.None); log.Info("Virtual drive mounted at: {0}",mountedDirectoryPath); mountedDirectory = new DirectoryInfo(mountedDirectoryPath); log.Info("Ensuring drive is available: {0}",mountedDirectoryPath); UpdateTestFile(); log.Info("Storage initialization succeeded"); }
/// <summary> /// ON START /// </summary> /// <returns></returns> public override bool OnStart() { Trace.TraceInformation("RoutingConfigRole entry point called - OnStart Method"); // Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 10 * 12 * Environment.ProcessorCount; //Disable small packet assembling, reducing network lattency ServicePointManager.UseNagleAlgorithm = false; //Enable TCP KeepAlive 2h, 1s ServicePointManager.SetTcpKeepAlive(true, 2 * 3600 * 1000, 1000); Trace.TraceInformation("Instance start - Configuring RoleEnvironment handlers"); #region Setup CloudStorageAccount Configuration Setting Publisher // This code sets up a handler to update CloudStorageAccount instances when their corresponding // configuration settings change in the service configuration file. CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => { // Provide the configSetter with the initial value configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)); RoleEnvironment.Changed += (sender, arg) => { if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>().Any((change) => (change.ConfigurationSettingName == configName))) { // If the autorestart config changed, do nothing if (configName != "AutoRestart") { // The corresponding configuration setting has changed, propagate the value if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName))) { Trace.TraceInformation("RoleEnvironmentConfigurationSettingChange : Requesting a recycle"); // In this case, the change to the storage account credentials in the // service configuration is significant enough that the role needs to be // recycled in order to use the latest settings. (for example, the // endpoint has changed) RoleEnvironment.RequestRecycle(); } } } }; }); #endregion // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. RoleEnvironment.Changing += new EventHandler<RoleEnvironmentChangingEventArgs>(RoleEnvironment_Changing); RoleEnvironment.Stopping += new EventHandler<RoleEnvironmentStoppingEventArgs>(RoleEnvironment_Stopping); RoleEnvironment.StatusCheck += new EventHandler<RoleInstanceStatusCheckEventArgs>(RoleEnvironment_StatusCheck); Trace.TraceInformation("Instance start - Configuring Diagnostic Monitor"); #region Diagnostic Monitor configuration var cfg = DiagnosticMonitor.GetDefaultInitialConfiguration(); cfg.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information; cfg.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1); cfg.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration { CounterSpecifier = @"\Processor(_Total)\% Processor Time", SampleRate = TimeSpan.FromSeconds(10d) }); cfg.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration { CounterSpecifier = @"\Memory\Available Bytes", SampleRate = TimeSpan.FromSeconds(10d) }); cfg.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration { CounterSpecifier = @"\PhysicalDisk(_Total)\% Idle Time", SampleRate = TimeSpan.FromSeconds(10d) }); cfg.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration { CounterSpecifier = @"\PhysicalDisk(_Total)\Avg. Disk Queue Length", SampleRate = TimeSpan.FromSeconds(10d) }); cfg.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1d); DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", cfg); #endregion #if !DEBUG // Configuration of the firewall // FirewallManagement.ConfigureFirewall(); #else Trace.TraceInformation("DEBUG Mode : Firewall not configured !!"); #endif SetCurrentState(RoutingConfigRoleState.Starting); #region Path for the storage //Drive only for S+C role if (MongoDBAzurePlatform.Instance.MyFunctionnalRoutingRole == MongoDBAzurePlatform.FunctionnalRoutingRole.RoutingAndConfigRole) { Trace.TraceInformation("Instance start - Mounting cloud drive for MongoC data"); // Get the local cache for the cloud drive LocalResource localCache = RoleEnvironment.GetLocalResource("MongocCache"); // we'll use all the cache space we can (note: InitializeCache doesn't work with trailing slash) CloudDrive.InitializeCache(localCache.RootPath.TrimEnd('\\'), localCache.MaximumSizeInMegabytes); // connect to the storage account storageAccount = CloudStorageAccount.FromConfigurationSetting("MongoDbData"); // client for talking to our blob files CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // the container that our dive is going to live in CloudBlobContainer drives = blobClient.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName")); // create blob container (it has to exist before creating the cloud drive) try { drives.CreateIfNotExist(); } catch { } // get the url to the vhd page blob we'll be using var vhdUrl = drives.GetPageBlobReference(string.Format("mongoc-{0}.vhd", RoleEnvironment.CurrentRoleInstance.Id)).Uri.ToString(); mongoDrive = storageAccount.CreateCloudDrive(vhdUrl); try { mongoDrive.Create(localCache.MaximumSizeInMegabytes); } catch (CloudDriveException) { // exception is thrown if all is well but the drive already exists } dbConfigPath = mongoDrive.Mount(localCache.MaximumSizeInMegabytes, DriveMountOptions.Force) + @"\"; Trace.TraceInformation("Instance start - Cloud drive mounted"); } #endregion switch (MongoDBAzurePlatform.Instance.MyFunctionnalRoutingRole) { case MongoDBAzurePlatform.FunctionnalRoutingRole.RoutingAndConfigRole: Trace.TraceInformation(string.Format("Instance Start (S+C) - Registering mongoc and mongos instance as 'stopped', MongoConfig IP is {0}, MongoS IP is {1}", MongoDBAzurePlatform.Instance.MyMongoCAddress.ToString(),MongoDBAzurePlatform.Instance.MyMongoSAddress.ToString())); break; case MongoDBAzurePlatform.FunctionnalRoutingRole.RoutingOnlyRole: Trace.TraceInformation(string.Format("Instance Start (S only) - Registering mongoc and mongos instance as 'stopped', MongoS IP is {0}", MongoDBAzurePlatform.Instance.MyMongoSAddress.ToString())); break; default: Trace.TraceError("On Start : Wrong Functionnal Role : " + (MongoDBAzurePlatform.Instance.MyFunctionnalRoutingRole.ToString())); break; } MongoHelper.RegisterInstanceOrUpdate(MongoHelper.RoutingConfigRoleMongoProcessState.Stopped, "mongoc"); MongoHelper.RegisterInstanceOrUpdate(MongoHelper.RoutingConfigRoleMongoProcessState.Stopped, "mongos"); //Start MongoDB performance counters collection for MongoC process Trace.TraceInformation("Instance start - Starting custom performance counters"); if (MongoDBAzurePlatform.Instance.MyFunctionnalRoutingRole == MongoDBAzurePlatform.FunctionnalRoutingRole.RoutingAndConfigRole) MongoDB.PerformanceCounters.PerformanceMonitor.Start(MongoDBAzurePlatform.Instance.MyMongoCAddress.Host, MongoDBAzurePlatform.Instance.MyMongoCAddress.Port, int.Parse(RoleEnvironment.GetConfigurationSettingValue("PerfCountersSamplingIntervalInMs"))); Trace.TraceInformation("Instance start - end of instance start"); switch (MongoDBAzurePlatform.Instance.MyFunctionnalRoutingRole) { case MongoDBAzurePlatform.FunctionnalRoutingRole.RoutingAndConfigRole: SetCurrentState(RoutingConfigRoleState.MongoConfig_NotRunning); break; case MongoDBAzurePlatform.FunctionnalRoutingRole.RoutingOnlyRole: SetCurrentState(RoutingConfigRoleState.MongoShard_NotRunning); break; default: Trace.TraceError("On Start : Wrong Functionnal Role : "+(MongoDBAzurePlatform.Instance.MyFunctionnalRoutingRole.ToString())); break; } return base.OnStart(); }