private void AreEqual(CrashDumps exp, CrashDumps act)
 {
     if (exp != null)
     {
         Assert.Equal(exp.ContainerName, act.ContainerName);
         Assert.Equal(exp.DirectoryQuotaPercentage, act.DirectoryQuotaPercentage);
         Assert.Equal(exp.DumpType, act.DumpType);
         AreEqual(exp.Processes, act.Processes);
     }
 }
        public static void ConfigureDiagnosticMonitor(LogLevel logLevel)
        {
            var       transferPeriod  = TimeSpan.FromMinutes(5);
            const int bufferQuotaInMb = 100;

            // Add Windows Azure Trace Listener
            Trace.Listeners.Add(new DiagnosticMonitorTraceListener());

            // Enable Collection of Crash Dumps
            CrashDumps.EnableCollection(true);

            // Get the Default Initial Config
            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            // Windows Azure Logs
            config.Logs.ScheduledTransferPeriod         = transferPeriod;
            config.Logs.BufferQuotaInMB                 = bufferQuotaInMb;
            config.Logs.ScheduledTransferLogLevelFilter = logLevel;

            // File-based logs
            config.Directories.ScheduledTransferPeriod = transferPeriod;
            config.Directories.BufferQuotaInMB         = bufferQuotaInMb;

            config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = transferPeriod;
            config.DiagnosticInfrastructureLogs.BufferQuotaInMB                 = bufferQuotaInMb;
            config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Warning;

            // Windows Event logs
            config.WindowsEventLog.DataSources.Add("Application!*");
            config.WindowsEventLog.DataSources.Add("System!*");
            config.WindowsEventLog.ScheduledTransferPeriod         = transferPeriod;
            config.WindowsEventLog.ScheduledTransferLogLevelFilter = logLevel;
            config.WindowsEventLog.BufferQuotaInMB = bufferQuotaInMb;

            // Performance Counters
            var counters = new List <string> {
                @"\Processor(_Total)\% Processor Time",
                @"\Memory\Available MBytes",
                @"\ASP.NET Applications(__Total__)\Requests Total",
                @"\ASP.NET Applications(__Total__)\Requests/Sec",
                @"\ASP.NET\Requests Queued",
            };

            counters.ForEach(counter => config.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration {
                CounterSpecifier = counter, SampleRate = TimeSpan.FromSeconds(60)
            }));
            config.PerformanceCounters.ScheduledTransferPeriod = transferPeriod;
            config.PerformanceCounters.BufferQuotaInMB         = bufferQuotaInMb;

            DiagnosticMonitor.Start(Constants.DiagnosticsConnectionStringKey, config);
            Trace.TraceInformation("Diagnostics configured.");
        }
Beispiel #3
0
        static void SetupDiagnostics()
        {
            var cfg = DiagnosticMonitor.GetDefaultInitialConfiguration();

            if (CollectPerfCounters)
            {
                AddPerformanceCounter(cfg, @"\Processor(_Total)\% Processor Time", TimeSpan.FromSeconds(5));
                AddPerformanceCounter(cfg, @"\Memory\Available Mbytes", TimeSpan.FromSeconds(5));
            }

            if (CollectWindowsEventLogs)
            {
                AddEventSource(cfg, "System!*");
                AddEventSource(cfg, "Application!*");
            }

            cfg.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Information;
            cfg.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(5);

            CrashDumps.EnableCollection(FullCrashDumps);
            DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", cfg);
        }
Beispiel #4
0
        public override bool OnStart()
        {
            Trace.WriteLine("OrleansAzureWeb-OnStart");

            // For information on handling configuration changes see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            #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(
                (string configName, Func <string, bool> 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)))
                    {
                        // The corresponding configuration setting has changed, propagate the value
                        if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                        {
                            // 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

            //        DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString");
            //        System.Diagnostics.Trace.Listeners.Add(new Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());

            //        System.Diagnostics.Trace.Listeners.Add(new Microsoft.
            //WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener());
            //        System.Diagnostics.Trace.AutoFlush = true;
            //        System.Diagnostics.Trace.TraceInformation("Information");

            DiagnosticMonitorConfiguration diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

            var perfCounters = new List <string>
            {
                @"\Processor(_Total)\% Processor Time",
                @"\Memory\Available Mbytes",
                @"\TCPv4\Connections Established",
                @"\ASP.NET Applications(__Total__)\Requests/Sec",
                @"\Network Interface(*)\Bytes Received/sec",
                @"\Network Interface(*)\Bytes Sent/sec"
            };

            // Add perf counters to configuration
            foreach (var counter in perfCounters)
            {
                var counterConfig = new PerformanceCounterConfiguration
                {
                    CounterSpecifier = counter,
                    SampleRate       = TimeSpan.FromSeconds(5)
                };

                diagConfig.PerformanceCounters.DataSources.Add(counterConfig);
            }

            diagConfig.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

            //Windows Event Logs
            diagConfig.WindowsEventLog.DataSources.Add("System!*");
            diagConfig.WindowsEventLog.DataSources.Add("Application!*");
            diagConfig.WindowsEventLog.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1.0);
            diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning;

            //Azure Trace Logs
            diagConfig.Logs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1.0);
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Warning;

            //Crash Dumps
            CrashDumps.EnableCollection(true);

            //IIS Logs
            diagConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

            DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagConfig);


            bool ok = base.OnStart();

            Trace.WriteLine("OrleansAzureWeb-OnStart completed with OK=" + ok);

            return(ok);
        }
Beispiel #5
0
        /// <summary>Windows Azure診断(Windows Azure Diagnostics)関連の設定</summary>
        private void ConfigureDiagnostics()
        {
            // Windows Azure診断(Windows Azure Diagnostics)情報出力用のストレージ アカウント取得
            string wadConnectionString = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";

            //// ストレージ アカウントの初期化
            //CloudStorageAccount cloudStorageAccount =
            //  CloudStorageAccount.Parse(
            //    RoleEnvironment.GetConfigurationSettingValue(wadConnectionString));

            //// RoleInstance診断管理の初期化(ロールに対する診断の有効化)
            //RoleInstanceDiagnosticManager roleInstanceDiagnosticManager =
            //  cloudStorageAccount.CreateRoleInstanceDiagnosticManager(
            //    RoleEnvironment.DeploymentId,
            //    RoleEnvironment.CurrentRoleInstance.Role.Name,
            //    RoleEnvironment.CurrentRoleInstance.Id);
            var storageConnectionString = RoleEnvironment.GetConfigurationSettingValue(
                wadConnectionString);
            var deploymentDiagnosticManager = new DeploymentDiagnosticManager(
                storageConnectionString,
                RoleEnvironment.DeploymentId);
            RoleInstanceDiagnosticManager roleInstanceDiagnosticManager = deploymentDiagnosticManager.GetRoleInstanceDiagnosticManager(
                RoleEnvironment.CurrentRoleInstance.Role.Name,
                RoleEnvironment.CurrentRoleInstance.Id);

            // RoleInstance診断管理からコンフィグを取得する。
            // ・基本的にはデフォルト設定を利用する。
            // ・RoleEnvironment.Changedイベント ハンドラを仕掛ける場合はカレント設定を利用する。
            DiagnosticMonitorConfiguration config =
                DiagnosticMonitor.GetDefaultInitialConfiguration();

            // roleInstanceDiagnosticManager.GetCurrentConfiguration();

            #region Windows Azure診断(Windows Azure Diagnostics)APIを使用した設定開始

            #region インフラストラクチャ ログ(診断モニタ自体のログ)
            // 転送レベルおよび転送間隔を設定
            config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;       // 要検討
            config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = TimeSpan.FromSeconds(15); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADDiagnosticInfrastructureLogsTable

            #region イベント ログの設定
            // 取得するイベント ソースを設定
            config.WindowsEventLog.DataSources.Add("Application!*");
            config.WindowsEventLog.DataSources.Add("System!*");
            // 転送レベルおよび転送間隔を設定
            config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Undefined;       // 要検討
            config.WindowsEventLog.ScheduledTransferPeriod         = TimeSpan.FromMinutes(15); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADWindowsEventLogsTable

            #region パフォーマンス カウンタの転送設定
            // カウンタ、サンプリング レートの指定
            config.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                SampleRate       = TimeSpan.FromSeconds(10)
            });
            config.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
            {
                CounterSpecifier = @"\Memory\Available Bytes",
                SampleRate       = TimeSpan.FromSeconds(10)
            });
            // 転送間隔を設定
            config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(15); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADPerformanceCountersTable

            #region クラッシュ ダンプ転送の有効化
            CrashDumps.EnableCollection(true);
            #endregion
            // 出力先のBlobストレージ コンテナ名:wad-crash-dumps

            #region IISログ、FREBログの転送設定(※ web.config への設定も必要)
            // IISログはデフォルトで取得が有効となっているため、Blobへの転送を指定するのみで収集が可能となる。
            // FREB(Failed Request Trace log)ログについてはweb.config への設定も必要
            #endregion
            // 出力先のBlobストレージ コンテナ名:wad-iis-logfiles、wad-iis-failedreqlogfiles

            #region トレース ログの設定(※ *.config への設定も必要)
            // 転送レベルおよび転送間隔を設定
            config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;      // 要検討
            config.Logs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1); // 要検討
            #endregion
            // 出力先のTableストレージ名:WADLogsTable

            #region カスタム ログ(ローカル ストレージへの出力の場合)

            // 出力先ディレクトリ設定
            DirectoryConfiguration dirConfig1 = new DirectoryConfiguration()
            {
                // 出力先Blobコンテナの指定
                Container = "my-custom-logfiles1",
                // クォーターの設定(実際に使う量)
                DirectoryQuotaInMB = 100,
            };

            // ローカル ストレージのパスを指定
            //(ローカル ストレージの設定自体は、Visual Studioを使用し*.csdefに設定可能)
            LocalResource ls = RoleEnvironment.GetLocalResource("LogStorage");
            dirConfig1.Path = ls.RootPath;

            // log4netに環境変数経由でパス情報(RootPath)を
            // 渡そうとしたがエミュレータ上でうまく動作せず断念。

            // ローカル ストレージを転送元コレクションに追加
            config.Directories.DataSources.Add(dirConfig1);
            // なお、ローカル ストレージのパスは、LocalResource.RootPathにて取得が可能である。

            #endregion
            // 出力先のBlobストレージ コンテナ名:my-custom-logfiles1

            #region カスタムログ(任意の出力先の場合)

            // 出力先ディレクトリ設定
            DirectoryConfiguration dirConfig2 = new DirectoryConfiguration()
            {
                // 出力先Blobコンテナの指定
                Container = "my-custom-logfiles2",
                // クォーターの設定(実際に使う量)
                DirectoryQuotaInMB = 100,
            };

            // 任意のディレクトリを指定
            string path = "c:\\logs";
            dirConfig2.Path = path;
            // ディレクトリを転送元コレクションに追加
            config.Directories.DataSources.Add(dirConfig2);

            // ディレクトリ セキュリティを取得
            DirectorySecurity ds = Directory.GetAccessControl(path);

            // Everyone FullControlのアクセス ルールの生成
            FileSystemAccessRule AccessRule = new FileSystemAccessRule(
                "Everyone",
                FileSystemRights.FullControl,
                InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            // ディレクトリ キュリティにアクセス ルールを追加
            ds.AddAccessRule(AccessRule);

            // ディレクトリにディレクトリ セキュリティを反映
            // ★ <Runtime executionContext="elevated"/>を「*.csdef」に記述。
            Directory.SetAccessControl(path, ds);

            #endregion
            // 出力先のBlobストレージ コンテナ名:my-custom-logfiles2

            // IISログ、カスタム ログ、クラッシュ ダンプなどで
            // 使用するディレクトリ バッファからBlobストレージへの転送間隔の指定
            config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(15);

            #endregion

            // RoleInstance診断管理にコンフィグを設定
            roleInstanceDiagnosticManager.SetCurrentConfiguration(config);

            // 診断の開始(エミュレータでは不要だが、実機では必要
            DiagnosticMonitor.Start(wadConnectionString, config);

            // ローカル ストレージへのログ出力テスト
            path = Path.Combine(ls.RootPath,
                                string.Format("test_{0}.txt", DateTime.Now.ToString("yyyyMMdd")));

            // StreamWriterを開き、ログを出力
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine("{0} : {1}", DateTime.UtcNow, "ローカル ストレージへのログ出力テスト");
                sw.Close();
            }
        }
Beispiel #6
0
        public override bool OnStart()
        {
            DiagnosticMonitorConfiguration diagConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

            var perfCounters = new List <string>
            {
                @"\Processor(_Total)\% Processor Time",
                @"\Memory\Available Mbytes",
                @"\TCPv4\Connections Established",
                @"\ASP.NET Applications(__Total__)\Requests/Sec",
                @"\Network Interface(*)\Bytes Received/sec",
                @"\Network Interface(*)\Bytes Sent/sec"
            };

            // Add perf counters to configuration
            foreach (var counter in perfCounters)
            {
                var counterConfig = new PerformanceCounterConfiguration
                {
                    CounterSpecifier = counter,
                    SampleRate       = TimeSpan.FromSeconds(1.0)
                };

                diagConfig.PerformanceCounters.DataSources.Add(counterConfig);
            }

            diagConfig.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromSeconds(20.0);

            //Windows Event Logs
            diagConfig.WindowsEventLog.DataSources.Add("System!*");
            diagConfig.WindowsEventLog.DataSources.Add("Application!*");
            diagConfig.WindowsEventLog.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1.0);
            diagConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning;

            //Azure Trace Logs
            diagConfig.Logs.ScheduledTransferPeriod         = TimeSpan.FromSeconds(20.0);
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Warning;
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Information;
            //  diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
            diagConfig.Logs.ScheduledTransferLogLevelFilter = LogLevel.Error;
            //Crash Dumps
            CrashDumps.EnableCollection(true);

            //IIS Logs
            diagConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

            DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagConfig);

            Trace.TraceInformation(RoleEnvironment.Roles.Count.ToString());
            Trace.TraceInformation("Instance {0} started.", RoleEnvironment.CurrentRoleInstance.Id);

            RoleEnvironment.Changing += new EventHandler <RoleEnvironmentChangingEventArgs>(RoleEnvironment_Changing);

            // CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
            // account.
            //    RoleEnvironment.GetConfigurationSettingValue("CacheServiceRole");

            RoleEnvironment.Changed += new EventHandler <RoleEnvironmentChangedEventArgs>(RoleEnvironment_Changed);


            //if (RoleEnvironment.IsEmulated)
            //{
            //    var traceSource = CreateTraceSource();
            //    traceSource.TraceInformation("Instance {0} started.", RoleEnvironment.CurrentRoleInstance.Id);
            //}
            return(base.OnStart());
            //// To enable the AzureLocalStorageTraceListner, uncomment relevent section in the web.config
            //DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
            //diagnosticConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
            //diagnosticConfig.Directories.DataSources.Add(AzureLocalStorageTraceListener.GetLogDirectory());

            //// For information on handling configuration changes
            //// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            //return base.OnStart();
        }
 /// <summary>
 /// Will add a full crashdump.
 /// Note: Full crashdumps are not available in asp.net roles
 /// </summary>
 void AddFullCrashDumps()
 {
     CrashDumps.EnableCollection(true);
 }
Beispiel #8
0
        /// <summary>
        /// Notifies this extension component that it has been registered in the owner's collection of extensions.
        /// </summary>
        /// <param name="owner">The extensible owner object that aggregates this extension.</param>
        public void Attach(IExtensibleCloudServiceComponent owner)
        {
            IRoleConfigurationSettingsExtension roleConfigExtension = owner.Extensions.Find <IRoleConfigurationSettingsExtension>();

            if (roleConfigExtension != null && CloudEnvironment.IsAvailable)
            {
                ApplicationDiagnosticSettings       diagnosticSettings = roleConfigExtension.GetSection <ApplicationDiagnosticSettings>(ApplicationDiagnosticSettings.SectionName);
                StorageAccountConfigurationSettings storageSettings    = roleConfigExtension.GetSection <StorageAccountConfigurationSettings>(StorageAccountConfigurationSettings.SectionName);

                if (diagnosticSettings != null)
                {
                    if (diagnosticSettings.DiagnosticEnabled)
                    {
                        DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();

                        // Configure the scheduled transfer period for all logs.
                        diagnosticConfig.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = diagnosticSettings.DiagnosticLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.Directories.ScheduledTransferPeriod         = diagnosticSettings.FileLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.Logs.ScheduledTransferPeriod                = diagnosticSettings.TraceLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.PerformanceCounters.ScheduledTransferPeriod = diagnosticSettings.PerformanceCountersTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);
                        diagnosticConfig.WindowsEventLog.ScheduledTransferPeriod     = diagnosticSettings.EventLogsTransferPeriod.Coalesce(diagnosticSettings.DefaultTransferPeriod);

                        // Configure the logs levels for scheduled transfers.
                        diagnosticConfig.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = FromTraceSourceLevel(diagnosticSettings.DiagnosticLogsTransferFilter);
                        diagnosticConfig.Logs.ScheduledTransferLogLevelFilter            = FromTraceSourceLevel(diagnosticSettings.TraceLogsTransferFilter);
                        diagnosticConfig.WindowsEventLog.ScheduledTransferLogLevelFilter = FromTraceSourceLevel(diagnosticSettings.EventLogsTransferFilter);

                        // Configure the Windows Event Log data sources.
                        foreach (string logName in diagnosticSettings.EventLogDataSources.AllKeys)
                        {
                            diagnosticConfig.WindowsEventLog.DataSources.Add(logName);
                        }

                        // Configure the data sources for file-based logs.
                        foreach (string containerName in diagnosticSettings.FileLogDirectories.AllKeys)
                        {
                            diagnosticConfig.Directories.DataSources.Add(new DirectoryConfiguration()
                            {
                                Container = containerName, Path = diagnosticSettings.FileLogDirectories[containerName].Value
                            });
                        }

                        // Configure the data sources for performance counter data
                        foreach (string counterName in diagnosticSettings.PerformanceCountersDataSources.AllKeys)
                        {
                            diagnosticConfig.PerformanceCounters.DataSources.Add(new PerformanceCounterConfiguration()
                            {
                                CounterSpecifier = counterName, SampleRate = TimeSpan.Parse(diagnosticSettings.PerformanceCountersDataSources[counterName].Value)
                            });
                        }

                        // Configure crash dumps collection.
                        if (diagnosticSettings.CrashDumpCollectionEnabled)
                        {
                            CrashDumps.EnableCollection(true);
                        }

                        // Look up for the storage account definition.
                        StorageAccountInfo storageAccountInfo = storageSettings.Accounts.Get(diagnosticSettings.DiagnosticStorageAccount);

                        if (storageAccountInfo != null)
                        {
                            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentialsAccountAndKey(storageAccountInfo.AccountName, storageAccountInfo.AccountKey), true);
                            RetryPolicy         retryPolicy    = roleConfigExtension.StorageRetryPolicy;

                            // Start the Azure Diagnostic Monitor using a retryable scope.
                            this.diagnosticMonitor = retryPolicy.ExecuteAction <DiagnosticMonitor>(() => { return(DiagnosticMonitor.Start(storageAccount, diagnosticConfig)); });
                        }
                    }
                    else
                    {
                        // Do not proceed any further since diagnostic is not enabled in the application configuration.
                        return;
                    }
                }
            }

            if (null == this.diagnosticMonitor)
            {
                // Configuration extension is not available by some reasons, let try and see if DiagnosticsConnectionString property is set in the configuration.
                string diagConnectionString = CloudEnvironment.GetConfigurationSettingValue(Resources.DiagnosticsConnectionStringSettingName);

                // If DiagnosticsConnectionString is defined, start a Diagnostic Monitor using the storage account configuration specified in the setting.
                if (!String.IsNullOrEmpty(diagConnectionString))
                {
                    this.diagnosticMonitor = DiagnosticMonitor.Start(diagConnectionString, GetDiagnosticMonitorDefaultConfiguration());
                }
            }
        }
Beispiel #9
0
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            //var settingAsString = RoleEnvironment.GetConfigurationSettingValue("Full.Setting.Path");

            if (!RoleEnvironment.IsEmulated)
            {
                #region Machine Key Reconfiguration
                // http://msdn.microsoft.com/en-us/library/gg494983.aspx

                _logger = new WebRoleLogger();
                _logger.Log("RoleEntryPoint.OnStart() has been invoked.");
                try
                {
                    // locate the encrypted web.config file
                    var webConfigPath       = GetEncryptedWebConfigFilePath();
                    var webConfigFileExists = File.Exists(webConfigPath);
                    if (!webConfigFileExists)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate web.config file at '{0}'.", webConfigPath));
                    }

                    // get web.config file contents
                    var webConfigContent = File.ReadAllText(webConfigPath);

                    // construct an XML configuration document
                    var webConfigXmlDocument = new ConfigXmlDocument {
                        InnerXml = webConfigContent,
                    };
                    if (webConfigXmlDocument.DocumentElement == null)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file."));
                    }

                    // find the configProtectedData node
                    var configProtectedDataNode = webConfigXmlDocument.DocumentElement.ChildNodes.Cast <XmlNode>()
                                                  .SingleOrDefault(x => x.Name == "configProtectedData");
                    if (configProtectedDataNode == null)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData node in web.config file."));
                    }

                    // find the configProtectedData/provider child node
                    var configProtectionProviderNode = configProtectedDataNode;
                    while (configProtectionProviderNode != null && configProtectionProviderNode.Attributes != null &&
                           (configProtectionProviderNode.Attributes["name"] == null || configProtectionProviderNode.Attributes["thumbprint"] == null))
                    {
                        configProtectionProviderNode = configProtectionProviderNode.ChildNodes.Cast <XmlNode>().FirstOrDefault();
                    }
                    if (configProtectionProviderNode == null || configProtectionProviderNode.Attributes == null)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate configProtectedData/provider child node in web.config file."));
                    }

                    // get the configProtectedData/provider node attributes (name & thumbprint)
                    var configProtectionProviderName       = configProtectionProviderNode.Attributes["name"].Value;
                    var configProtectionProviderThumbprint = configProtectionProviderNode.Attributes["thumbprint"].Value;

                    // construct & initialize a ProtectedConfigurationProvider
                    var configProtectionProviderAssembly = Assembly.Load("Pkcs12ProtectedConfigurationProvider");
                    var configProtectionProviderType     = configProtectionProviderAssembly.GetTypes()
                                                           .First(t => typeof(ProtectedConfigurationProvider).IsAssignableFrom(t));
                    var protectedConfigurationProvider = Activator.CreateInstance(configProtectionProviderType) as ProtectedConfigurationProvider;
                    if (protectedConfigurationProvider == null)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to construct a ProtectedConfigurationProvider."));
                    }

                    protectedConfigurationProvider.Initialize(configProtectionProviderName, new NameValueCollection
                    {
                        { "thumbprint", configProtectionProviderThumbprint },
                    });

                    // get encrypted appSettings XML node
                    var encryptedAppSettingsNode = webConfigXmlDocument.DocumentElement.ChildNodes
                                                   .Cast <XmlNode>().SingleOrDefault(x => x.Name == "appSettings");
                    if (encryptedAppSettingsNode == null)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate encrypted appSettings node."));
                    }

                    // decrypt appSettings XML
                    var decryptedAppSettingsNode = protectedConfigurationProvider.Decrypt(encryptedAppSettingsNode).ChildNodes
                                                   .Cast <XmlNode>().SingleOrDefault(x => x.Name == "appSettings");
                    if (decryptedAppSettingsNode == null)
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate decrypted appSettings node."));
                    }

                    // extract machineConfig values from decrypted appSettings XML
                    var validationKey       = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationKey");
                    var validationAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineValidationAlgorithm");
                    var decryptionKey       = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionKey");
                    var decryptionAlgorithm = GetDecryptedAppSetting(decryptedAppSettingsNode, "MachineDecryptionAlgorithm");
                    if (string.IsNullOrWhiteSpace(validationKey) || string.IsNullOrWhiteSpace(validationAlgorithm) ||
                        string.IsNullOrWhiteSpace(decryptionKey) || string.IsNullOrWhiteSpace(decryptionAlgorithm))
                    {
                        return(FailBecauseMachineConfigCannotBeReconfigured("A machineKey attribute value could not be found in decrypted appSettings."));
                    }

                    using (var server = new ServerManager())
                    {
                        // load IIS site's web configuration
                        var siteName = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id);
                        var site     = RoleEnvironment.IsEmulated ? server.Sites.First() : server.Sites[siteName];
                        if (site == null)
                        {
                            return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate site '{0}'.", siteName));
                        }

                        var siteWebConfiguration = site.GetWebConfiguration();
                        if (siteWebConfiguration == null)
                        {
                            return(FailBecauseMachineConfigCannotBeReconfigured("Unable to load web configuration for site '{0}'.", siteName));
                        }

                        var machineKeySection = siteWebConfiguration.GetSection("system.web/machineKey");
                        if (machineKeySection == null)
                        {
                            return(FailBecauseMachineConfigCannotBeReconfigured("Unable to locate machineConfig section in site '{0}' web configuration.", siteName));
                        }

                        // overwrite machineKey values
                        machineKeySection.SetAttributeValue("validationKey", validationKey);
                        machineKeySection.SetAttributeValue("validation", validationAlgorithm);
                        machineKeySection.SetAttributeValue("decryptionKey", decryptionKey);
                        machineKeySection.SetAttributeValue("decryption", decryptionAlgorithm);
                        server.CommitChanges();
                    }
                }
                catch (Exception ex)
                {
                    if (ex.Message == FailBecauseMachineConfigCannotBeReconfiguredMessage)
                    {
                        throw;
                    }

                    _logger.Log("A(n) {0} exception was encountered while trying to set the machineConfig.", ex.GetType().Name);
                    _logger.Log(ex.Message);
                    _logger.Log(ex.StackTrace);
                    _logger.Log(ex.Source);
                }
                _logger.Dispose();

                #endregion
                #region Diagnostics Trace Logging

                var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

                // Change the polling interval for all logs.
                config.ConfigurationChangePollInterval = TimeSpan.FromSeconds(30.0);

                // Set the transfer interval for all logs.
                config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);

                // Add performance counter monitoring for configured counters
                var counters = new List <string>
                {
                    @"\Processor(_Total)\% Processor Time",
                    @"\Memory\Available Mbytes",
                    @"\TCPv4\Connections Established",
                    @"\ASP.NET Applications(__Total__)\Requests/Sec",
                    @"\Network Interface(*)\Bytes Received/sec",
                    @"\Network Interface(*)\Bytes Sent/sec"
                };
                foreach (var counterConfig in counters.Select(counter =>
                                                              new PerformanceCounterConfiguration
                {
                    CounterSpecifier = counter,
                    SampleRate = TimeSpan.FromMinutes(1)
                })
                         )
                {
                    config.PerformanceCounters.DataSources.Add(counterConfig);
                }
                config.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);

                //Diagnostics Infrastructure logs
                config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1);
                config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;//.error

                //Windows Event Logs
                config.WindowsEventLog.DataSources.Add("System!*");
                config.WindowsEventLog.DataSources.Add("Application!*");
                config.WindowsEventLog.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1);
                config.WindowsEventLog.ScheduledTransferLogLevelFilter = LogLevel.Warning;

                //Azure Trace Logs
                config.Logs.ScheduledTransferPeriod         = TimeSpan.FromMinutes(1);
                config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

                //Crash Dumps
                CrashDumps.EnableCollection(true);

                //IIS Logs
                config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);

                // start the diagnostics monitor
                DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", config);

                #endregion
                #region IIS Domain Binding

                // By default, the website name is "[ Current Role Instance id]_Web"
                var siteName1 = string.Format("{0}_Web", RoleEnvironment.CurrentRoleInstance.Id);

                // In future, if you need add more endpoint(HTTP or HTTPS),
                // please create new bindingEntry and append to the cmd string,
                // separate with ','. For how to use AppCmd to config IIS site,
                // please refer to this article
                // http://learn.iis.net/page.aspx/114/getting-started-with-appcmdexe

                var command = string.Format("set site \"{0}\" /bindings:{1}", siteName1, GetAppCmdBindings());

                const string appCmdPath = @"d:\Windows\System32\inetsrv\appcmd.exe";

                try
                {
                    Process.Start(new ProcessStartInfo(appCmdPath, command));
                    Trace.TraceInformation("Initialize IIS binding succeed.");
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.Message);
                    throw;
                }

                #endregion
            }

            var baseOnStart = base.OnStart();
            return(baseOnStart);
        }