コード例 #1
0
        public static async Task <HttpResponseMessage> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "analyze")] HttpRequestMessage request,
            TraceWriter log,
            ExecutionContext context,
            CancellationToken cancellationToken)
        {
            using (IUnityContainer childContainer = Container.CreateChildContainer().WithTracer(log, true))
            {
                // Create a tracer for this run (that will also log to the specified TraceWriter)
                IExtendedTracer tracer = childContainer.Resolve <IExtendedTracer>();
                tracer.TraceInformation($"Analyze function request received with invocation Id {context.InvocationId}");
                tracer.AddCustomProperty("FunctionName", context.FunctionName);
                tracer.AddCustomProperty("InvocationId", context.InvocationId.ToString("N", CultureInfo.InvariantCulture));

                try
                {
                    // Trace app counters (before analysis)
                    tracer.TraceAppCounters();

                    // Read the request
                    SmartDetectorExecutionRequest smartDetectorExecutionRequest = await request.Content.ReadAsAsync <SmartDetectorExecutionRequest>(cancellationToken);

                    tracer.AddCustomProperty("SmartDetectorId", smartDetectorExecutionRequest.SmartDetectorId);
                    tracer.TraceInformation($"Analyze request received: {JsonConvert.SerializeObject(smartDetectorExecutionRequest)}");

                    // Process the request
                    ISmartDetectorRunner runner = childContainer.Resolve <ISmartDetectorRunner>();
                    bool shouldDetectorTrace    = bool.Parse(ConfigurationReader.ReadConfig("ShouldDetectorTrace", required: true));
                    List <ContractsAlert> alertPresentations = await runner.RunAsync(smartDetectorExecutionRequest, shouldDetectorTrace, cancellationToken);

                    tracer.TraceInformation($"Analyze completed, returning {alertPresentations.Count} Alerts");

                    // Create the response with StringContent to prevent Json from serializing to a string
                    var response = request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(JsonConvert.SerializeObject(alertPresentations), Encoding.UTF8, "application/json");
                    return(response);
                }
                catch (AnalysisFailedException afe)
                {
                    // Handle the exception
                    TopLevelExceptionHandler.TraceUnhandledException(afe, tracer, log);

                    // Return error status
                    return(request.CreateResponse(afe.StatusCode, afe.ReasonPhrase));
                }
                catch (Exception e)
                {
                    // Handle the exception
                    TopLevelExceptionHandler.TraceUnhandledException(e, tracer, log);

                    // Return error status
                    return(request.CreateResponse(HttpStatusCode.InternalServerError, e.Message));
                }
                finally
                {
                    // Trace app counters (after analysis)
                    tracer.TraceAppCounters();
                }
            }
        }
 /// <summary>
 /// Creates a <see cref="Policy"/> instance with default exponential retry policy.
 /// </summary>
 /// <param name="tracer">The tracer</param>
 /// <param name="dependencyName">The dependency name</param>
 /// <param name="retryCount">The retry count (3 by default)</param>
 /// <returns>The retry policy</returns>
 public static Policy CreateDefaultPolicy(IExtendedTracer tracer, string dependencyName, int retryCount = 3)
 {
     return(Policy.Handle <Exception>(ex => !(ex is TaskCanceledException)).WaitAndRetryAsync(
                retryCount,
                (i) => TimeSpan.FromSeconds(Math.Pow(2, i)),
                (exception, span, context) => tracer.TraceError($"Failed accessing {dependencyName} on {exception.Message}, retry {Math.Log(span.Seconds, 2)} out of {retryCount}")));
 }
コード例 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MsiCredentials"/> class.
 /// </summary>
 /// <param name="httpClientWrapper">The HTTP client wrapper</param>
 /// <param name="resource">The resource name - the URL for which these credentials will be used</param>
 /// <param name="tracer">The tracer</param>
 public MsiCredentials(IHttpClientWrapper httpClientWrapper, string resource, IExtendedTracer tracer)
 {
     this.resource          = resource;
     this.httpClientWrapper = httpClientWrapper;
     this.tracer            = tracer;
     this.retryPolicy       = PolicyExtensions.CreateTransientHttpErrorPolicy(this.tracer, DependencyName);
 }
 /// <summary>
 /// Creates a <see cref="Policy"/> instance that retries on transient HTTP errors with default exponential retry policy.
 /// </summary>
 /// <param name="tracer">The tracer</param>
 /// <param name="dependencyName">The dependency name</param>
 /// <param name="retryCount">The retry count (3 by default)</param>
 /// <returns>The retry policy</returns>
 public static Policy <HttpResponseMessage> CreateTransientHttpErrorPolicy(IExtendedTracer tracer, string dependencyName, int retryCount = 3)
 {
     return(Policy <HttpResponseMessage>
            .Handle <HttpRequestException>()
            .Or <TimeoutException>()
            .OrResult(response => response.StatusCode >= HttpStatusCode.InternalServerError || response.StatusCode == HttpStatusCode.RequestTimeout)
            .WaitAndRetryAsync(
                retryCount,
                i => TimeSpan.FromSeconds(Math.Pow(2, i)),
                (response, span, context) =>
     {
         if (response.Exception != null)
         {
             tracer.TraceError($"Failed accessing {dependencyName} on exception {response.Exception.Message}, retry {Math.Log(span.Seconds, 2)} out of {retryCount}");
         }
         else if (response.Result != null)
         {
             tracer.TraceError($"Failed accessing {dependencyName} on HTTP error {response.Result.StatusCode}, retry {Math.Log(span.Seconds, 2)} out of {retryCount}");
         }
         else
         {
             tracer.TraceError($"Failed accessing {dependencyName} for unknown reason, retry {Math.Log(span.Seconds, 2)} out of {retryCount}");
         }
     }));
 }
 public BlobStateRepository(string smartDetectorId, string alertRuleResourceId, ICloudStorageProviderFactory cloudStorageProviderFactory, IExtendedTracer tracer)
 {
     this.smartDetectorId           = Diagnostics.EnsureStringNotNullOrWhiteSpace(() => smartDetectorId);
     this.alertRuleResourceId       = Diagnostics.EnsureStringNotNullOrWhiteSpace(() => alertRuleResourceId).ToLowerInvariant();
     this.cloudBlobContainerWrapper = cloudStorageProviderFactory.GetSmartDetectorStateStorageContainerAsync().Result;
     this.tracer = tracer;
 }
        /// <summary>
        /// Runs an asynchronous dependency operation, using the specified policy, sends
        /// telemetry information about it using the specified tracer, and returns the
        /// operation result.
        /// Any exception in the dependency call would be propagated to the caller.
        /// </summary>
        /// <typeparam name="T">The operation result type</typeparam>
        /// <param name="policy">The policy</param>
        /// <param name="tracer">The tracer</param>
        /// <param name="dependencyName">The dependency name.</param>
        /// <param name="commandName">The command name</param>
        /// <param name="dependencyCall">The dependency call action</param>
        /// <param name="extractMetricsFromResultFunc">Function that extracts metrics from the result</param>
        /// <param name="properties">Named string values you can use to classify and filter dependencies</param>
        /// <returns>A task running the asynchronous operation and returning its result</returns>
        public static async Task <T> RunAndTrackDependencyAsync <T>(
            this Policy <T> policy,
            IExtendedTracer tracer,
            string dependencyName,
            string commandName,
            Func <Task <T> > dependencyCall,
            Func <T, IDictionary <string, double> > extractMetricsFromResultFunc = null,
            IDictionary <string, string> properties = null)
        {
            DateTime startTime = DateTime.UtcNow;
            bool     success   = false;
            IDictionary <string, double> metrics = null;

            try
            {
                T result = await policy.ExecuteAsync(dependencyCall);

                metrics = extractMetricsFromResultFunc?.Invoke(result);
                success = true;
                return(result);
            }
            finally
            {
                tracer.TrackDependency(dependencyName, commandName, startTime, DateTime.UtcNow - startTime, success, metrics, properties);
            }
        }
        /// <summary>
        /// Creates a smart detector loader object for the child process, based on the command line arguments received from the parent process.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        /// <param name="tracerForLoader">The tracer to use</param>
        /// <returns>The smart detector loader instance</returns>
        public ISmartDetectorLoader CreateLoaderForChildProcess(string[] args, IExtendedTracer tracerForLoader)
        {
            // Get the temp folder name from the arguments and create the loader
            ChildProcessArguments arguments = ChildProcessArguments.FromCommandLineArguments(args);

            return(new SmartDetectorLoader(arguments.TempFolder, tracerForLoader));
        }
        /// <summary>
        /// The main method
        /// </summary>
        /// <param name="args">Command line arguments. These arguments are expected to be created by <see cref="IChildProcessManager.RunChildProcessAsync{TOutput}"/>.</param>
        /// <returns>Exit code</returns>
        public static int Main(string[] args)
        {
            IExtendedTracer tracer = null;

            try
            {
                // Inject dependencies
                container = DependenciesInjector.GetContainer()
                            .InjectAnalysisDependencies(withChildProcessRunner: false)
                            .WithChildProcessRegistrations(args);

                // Trace
                tracer = container.Resolve <IExtendedTracer>();
                tracer.TraceInformation($"Starting Smart Detector runner process, process ID {Process.GetCurrentProcess().Id}");

                // Run the analysis
                IChildProcessManager childProcessManager = container.Resolve <IChildProcessManager>();
                return(childProcessManager.RunAndListenToParentAsync <SmartDetectorExecutionRequest, List <ContractsAlert> >(args, RunSmartDetectorAsync, ConvertExceptionToExitCode).GetAwaiter().GetResult());
            }
            catch (Exception e)
            {
                tracer?.ReportException(e);
                tracer?.TraceError("Unhandled exception in child process: " + e.Message);
                Console.Error.WriteLine(e.ToString());
                return(-1);
            }
        }
コード例 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MetricClient"/> class
        /// </summary>
        /// <param name="tracer">The tracer</param>
        /// <param name="subscriptionId">The subscription Id</param>
        /// <param name="monitorManagementClient">Monitor management client to use to fetch metric data</param>
        public MetricClient(IExtendedTracer tracer, string subscriptionId, IMonitorManagementClient monitorManagementClient)
        {
            this.tracer = Diagnostics.EnsureArgumentNotNull(() => tracer);

            this.monitorManagementClient = monitorManagementClient;
            this.monitorManagementClient.SubscriptionId = subscriptionId;
            this.tracer      = tracer;
            this.retryPolicy = PolicyExtensions.CreateDefaultPolicy(this.tracer, DependencyName);
        }
コード例 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ActivityLogClient"/> class.
        /// </summary>
        /// <param name="credentialsFactory">The credentials factory</param>
        /// <param name="httpClientWrapper">The HTTP client wrapper</param>
        /// <param name="tracer">The tracer</param>
        public ActivityLogClient(ICredentialsFactory credentialsFactory, IHttpClientWrapper httpClientWrapper, IExtendedTracer tracer)
        {
            this.httpClientWrapper = Diagnostics.EnsureArgumentNotNull(() => httpClientWrapper);
            this.tracer            = Diagnostics.EnsureArgumentNotNull(() => tracer);
            this.baseUri           = new Uri(ConfigurationManager.AppSettings["ResourceManagerBaseUri"] ?? "https://management.azure.com/");
            Diagnostics.EnsureArgumentNotNull(() => credentialsFactory);
            this.credentials = credentialsFactory.Create(ConfigurationManager.AppSettings["ResourceManagerCredentialsResource"] ?? "https://management.azure.com/");

            this.httpRetryPolicy = PolicyExtensions.CreateTransientHttpErrorPolicy(this.tracer, DependencyName);
        }
コード例 #11
0
        /// <summary>
        /// Trace information for an unhandled exception.
        /// Each request handler should perform its logic within a try block, and call this handler within the catch block.
        /// </summary>
        /// <param name="ex">the exception caught at top level</param>
        /// <param name="tracer">Tracer that will be used to send telemetry on the failure</param>
        /// <param name="fallbackTracer">Fallback tracer, in case the tracer fails</param>
        public static void TraceUnhandledException(Exception ex, IExtendedTracer tracer, TraceWriter fallbackTracer)
        {
            // Trace the full exception details
            string errorToTrace = $"Top level exception: {ex}";

            try
            {
                // Write to trace
                tracer?.TraceError(errorToTrace);

                // Report the exception
                if (ex != null && tracer != null)
                {
                    AggregateException aggregateException = ex as AggregateException;
                    if (aggregateException != null)
                    {
                        aggregateException.InnerExceptions.ToList().ForEach(tracer.ReportException);
                    }
                    else
                    {
                        tracer.ReportException(ex);
                    }
                }

                // Flush all traces
                tracer?.Flush();
            }
            catch (Exception traceException)
            {
                try
                {
                    // Try to write to the fallback tracer
                    fallbackTracer?.Error($"Tracer failed - using fallback tracer. Tracer error: {traceException}");
                    fallbackTracer?.Error(errorToTrace);
                    fallbackTracer?.Flush();
                }
                catch (Exception fallbackTraceException)
                {
                    try
                    {
                        // Try to write to console
                        Console.WriteLine($"Tracer failed - using fallback tracer. Tracer error: {traceException}");
                        Console.WriteLine($"Fallback tracer failed - using console. Fallback tracer error: {fallbackTraceException}");
                        Console.WriteLine(errorToTrace);
                    }
                    catch (Exception)
                    {
                        // Just swallow, nothing better to do here..
                    }
                }
            }
        }
コード例 #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExtendedAzureResourceManagerClient"/> class
 /// </summary>
 /// <param name="credentialsFactory">The credentials factory</param>
 /// <param name="tracer">The tracer</param>
 public ExtendedAzureResourceManagerClient(ICredentialsFactory credentialsFactory, IExtendedTracer tracer)
 {
     Diagnostics.EnsureArgumentNotNull(() => credentialsFactory);
     this.baseUri     = new Uri(ConfigurationManager.AppSettings["ResourceManagerBaseUri"] ?? "https://management.azure.com/");
     this.credentials = credentialsFactory.Create(ConfigurationManager.AppSettings["ResourceManagerCredentialsResource"] ?? "https://management.azure.com/");
     this.tracer      = Diagnostics.EnsureArgumentNotNull(() => tracer);
     this.tracer      = tracer;
     this.retryPolicy = Policy
                        .Handle <CloudException>(ex => ex.Request != null && (ex.Response.StatusCode >= HttpStatusCode.InternalServerError || ex.Response.StatusCode == HttpStatusCode.RequestTimeout))
                        .WaitAndRetryAsync(
         3,
         (i) => TimeSpan.FromSeconds(Math.Pow(2, i)),
         (exception, span, context) => tracer.TraceError($"Failed accessing DependencyName on {exception.Message}, retry {Math.Log(span.Seconds, 2)} out of 3"));
 }
 /// <summary>
 /// Try to delete the specified folder - does not throw exception in case of failure, only traces
 /// </summary>
 /// <param name="folder">The folder to delete</param>
 /// <param name="tracer">The tracer to use</param>
 /// <returns>True if the folder was successfully deleted, false otherwise</returns>
 public static bool TryDeleteFolder(string folder, IExtendedTracer tracer = null)
 {
     try
     {
         Directory.Delete(folder, true);
         tracer?.TraceInformation($"Successfully deleted folder {folder}");
         return(true);
     }
     catch (Exception e)
     {
         tracer?.TraceWarning($"Could not delete folder {folder}, error: {e.Message}");
         tracer?.ReportException(e);
         return(false);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="AnalysisServicesFactory"/> class.
        /// </summary>
        /// <param name="tracer">The tracer</param>
        /// <param name="httpClientWrapper">The HTTP client wrapper.</param>
        /// <param name="credentialsFactory">The credentials factory.</param>
        /// <param name="azureResourceManagerClient">The Azure Resource Manager client.</param>
        /// <param name="queryRunInfoProvider">The query run information provider.</param>
        public AnalysisServicesFactory(IExtendedTracer tracer, IHttpClientWrapper httpClientWrapper, ICredentialsFactory credentialsFactory, IExtendedAzureResourceManagerClient azureResourceManagerClient, IQueryRunInfoProvider queryRunInfoProvider)
        {
            this.tracer                     = tracer;
            this.httpClientWrapper          = httpClientWrapper;
            this.credentialsFactory         = credentialsFactory;
            this.azureResourceManagerClient = azureResourceManagerClient;
            this.queryRunInfoProvider       = queryRunInfoProvider;

            // string timeoutString = ConfigurationReader.ReadConfig("AnalyticsQueryTimeoutInMinutes", required: true);
            string timeoutString = "15";

            this.queryTimeout = TimeSpan.FromMinutes(int.Parse(timeoutString, CultureInfo.InvariantCulture));

            this.UsedLogAnalysisClient = false;
            this.UsedMetricClient      = false;
        }
コード例 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SmartDetectorRunner"/> class
 /// </summary>
 /// <param name="smartDetectorRepository">The Smart Detector repository</param>
 /// <param name="smartDetectorLoader">The Smart Detector loader</param>
 /// <param name="analysisServicesFactory">The analysis services factory</param>
 /// <param name="azureResourceManagerClient">The Azure Resource Manager client</param>
 /// <param name="queryRunInfoProvider">The query run information provider</param>
 /// <param name="stateRepositoryFactory">The state repository factory</param>
 /// <param name="tracer">The tracer</param>
 public SmartDetectorRunner(
     ISmartDetectorRepository smartDetectorRepository,
     ISmartDetectorLoader smartDetectorLoader,
     IInternalAnalysisServicesFactory analysisServicesFactory,
     IExtendedAzureResourceManagerClient azureResourceManagerClient,
     IQueryRunInfoProvider queryRunInfoProvider,
     IStateRepositoryFactory stateRepositoryFactory,
     IExtendedTracer tracer)
 {
     this.smartDetectorRepository    = Diagnostics.EnsureArgumentNotNull(() => smartDetectorRepository);
     this.smartDetectorLoader        = Diagnostics.EnsureArgumentNotNull(() => smartDetectorLoader);
     this.analysisServicesFactory    = Diagnostics.EnsureArgumentNotNull(() => analysisServicesFactory);
     this.azureResourceManagerClient = Diagnostics.EnsureArgumentNotNull(() => azureResourceManagerClient);
     this.queryRunInfoProvider       = Diagnostics.EnsureArgumentNotNull(() => queryRunInfoProvider);
     this.stateRepositoryFactory     = Diagnostics.EnsureArgumentNotNull(() => stateRepositoryFactory);
     this.tracer = tracer;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationInsightsTelemetryDataClient"/> class.
 /// </summary>
 /// <param name="tracer">The tracer</param>
 /// <param name="httpClientWrapper">The HTTP client wrapper</param>
 /// <param name="credentialsFactory">The credentials factory</param>
 /// <param name="azureResourceManagerClient">The Azure Resource Manager client</param>
 /// <param name="applicationsResourceIds">The resource IDs of the applications on which the queries will run.</param>
 /// <param name="queryTimeout">The query timeout.</param>
 public ApplicationInsightsTelemetryDataClient(
     IExtendedTracer tracer,
     IHttpClientWrapper httpClientWrapper,
     ICredentialsFactory credentialsFactory,
     IExtendedAzureResourceManagerClient azureResourceManagerClient,
     IEnumerable <string> applicationsResourceIds,
     TimeSpan queryTimeout)
     : base(
         tracer,
         httpClientWrapper,
         credentialsFactory,
         azureResourceManagerClient,
         ConfigurationManager.AppSettings["ApplicationInsightsUriFormat"] ?? UriFormat,
         queryTimeout,
         TelemetryDbType.ApplicationInsights,
         applicationsResourceIds)
 {
 }
コード例 #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogAnalyticsTelemetryDataClient"/> class.
 /// </summary>
 /// <param name="tracer">The tracer</param>
 /// <param name="httpClientWrapper">The HTTP client wrapper</param>
 /// <param name="credentialsFactory">The credentials factory</param>
 /// <param name="azureResourceManagerClient">The Azure Resource Manager client</param>
 /// <param name="workspacesResourceIds">The resource IDs of the workspaces on which the queries will run.</param>
 /// <param name="queryTimeout">The query timeout.</param>
 public LogAnalyticsTelemetryDataClient(
     IExtendedTracer tracer,
     IHttpClientWrapper httpClientWrapper,
     ICredentialsFactory credentialsFactory,
     IExtendedAzureResourceManagerClient azureResourceManagerClient,
     IEnumerable <string> workspacesResourceIds,
     TimeSpan queryTimeout)
     : base(
         tracer,
         httpClientWrapper,
         credentialsFactory,
         azureResourceManagerClient,
         ConfigurationManager.AppSettings["LogAnalyticsUriFormat"] ?? UriFormat,
         queryTimeout,
         TelemetryDbType.LogAnalytics,
         workspacesResourceIds)
 {
 }
        /// <summary>
        /// Trace relevant performance counters as metrics.
        /// </summary>
        /// <param name="tracer">The tracer to use</param>
        public static void TraceAppCounters(this IExtendedTracer tracer)
        {
            string countersJson = null;

            try
            {
                countersJson = Environment.GetEnvironmentVariable("WEBSITE_COUNTERS_APP");
                if (string.IsNullOrEmpty(countersJson))
                {
                    tracer.TraceWarning("Failed to trace counters: environment variable value is empty");
                    return;
                }

                // TEMP: need to parse this specially to work around bug where
                // sometimes an extra garbage character occurs after the terminal
                // brace
                int idx = countersJson.LastIndexOf('}');
                if (idx > 0)
                {
                    countersJson = countersJson.Substring(0, idx + 1);
                }

                JObject countersObject = (JObject)JsonConvert.DeserializeObject(countersJson);
                foreach (var counter in countersObject)
                {
                    // The metric name is the counter's category and name, excluding non-letters
                    string metricName = $"{PerformanceCounterMetricPrefix}_{counter.Key}";

                    // Try to parse the value
                    if (!double.TryParse(counter.Value.ToString(), out double metricValue))
                    {
                        tracer.TraceWarning($"Failed to trace counter {counter.Key}, value {counter.Value}");
                        continue;
                    }

                    // Report the metric
                    tracer.ReportMetric(metricName, metricValue);
                }
            }
            catch (Exception e)
            {
                tracer.TraceWarning($"Failed to trace counters: countersJson = {countersJson}, error message = {e.Message}");
            }
        }
        /// <summary>
        /// Creates a tracer object for the child process, based on the command line arguments received from the parent process.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        /// <returns>The tracer instance</returns>
        public IExtendedTracer CreateTracerForChildProcess(string[] args)
        {
            ChildProcessArguments arguments = ChildProcessArguments.FromCommandLineArguments(args);

            // Get sessionId from the arguments and create tracer
            IExtendedTracer tracerForChildProcess = TracerFactory.Create(arguments.SessionId, null, true);

            // Get custom dimensions from the arguments - do not override existing properties
            IReadOnlyDictionary <string, string> existingProperties = tracerForChildProcess.GetCustomProperties();

            foreach (var kv in arguments.CustomTracerProperties)
            {
                if (!existingProperties.ContainsKey(kv.Key))
                {
                    tracerForChildProcess.AddCustomProperty(kv.Key, kv.Value);
                }
            }

            return(tracerForChildProcess);
        }
コード例 #20
0
        protected TelemetryDataClientBase(
            IExtendedTracer tracer,
            IHttpClientWrapper httpClientWrapper,
            ICredentialsFactory credentialsFactory,
            IExtendedAzureResourceManagerClient azureResourceManagerClient,
            string queryUriFormat,
            TimeSpan queryTimeout,
            TelemetryDbType telemetryDbType,
            IEnumerable <string> telemetryResourceIds)
        {
            this.tracer                     = Diagnostics.EnsureArgumentNotNull(() => tracer);
            this.httpClientWrapper          = Diagnostics.EnsureArgumentNotNull(() => httpClientWrapper);
            this.credentialsFactory         = Diagnostics.EnsureArgumentNotNull(() => credentialsFactory);
            this.AzureResourceManagerClient = Diagnostics.EnsureArgumentNotNull(() => azureResourceManagerClient);
            this.queryUriFormat             = Diagnostics.EnsureStringNotNullOrWhiteSpace(() => queryUriFormat);
            this.Timeout                    = Diagnostics.EnsureArgumentInRange(() => queryTimeout, TimeSpan.FromMinutes(0), TimeSpan.FromHours(2));
            this.TelemetryDbType            = telemetryDbType;

            int maximumNumberOfTelemetryResources = int.Parse(ConfigurationManager.AppSettings["MaximumNumberOfTelemetryResources"] ?? "300", CultureInfo.InvariantCulture);

            this.TelemetryResourceIds = telemetryResourceIds?.Take(maximumNumberOfTelemetryResources).ToList() ?? new List <string>();

            this.retryPolicy = PolicyExtensions.CreateTransientHttpErrorPolicy(this.tracer, this.TelemetryDbType.ToString());
        }
コード例 #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MetricClient"/> class
 /// </summary>
 /// <param name="tracer">The tracer</param>
 /// <param name="credentialsFactory">The credentials factory</param>
 /// <param name="subscriptionId">The subscription Id</param>
 public MetricClient(IExtendedTracer tracer, ICredentialsFactory credentialsFactory, string subscriptionId)
     : this(tracer, subscriptionId, new MonitorManagementClient(credentialsFactory.Create("https://management.azure.com/")))
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BlobStateRepositoryFactory"/> class
 /// </summary>
 /// <param name="cloudStorageProviderFactory">The cloud storage provider factory</param>
 /// <param name="tracer">The tracer</param>
 public BlobStateRepositoryFactory(ICloudStorageProviderFactory cloudStorageProviderFactory, IExtendedTracer tracer)
 {
     this.cloudStorageProviderFactory = Diagnostics.EnsureArgumentNotNull(() => cloudStorageProviderFactory);
     this.tracer = tracer;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SmartDetectorLoader"/> class.
 /// </summary>
 /// <param name="tempFolder">The temp folder to use for storing assembly files</param>
 /// <param name="tracer">The tracer</param>
 public SmartDetectorLoader(string tempFolder, IExtendedTracer tracer)
 {
     this.tempFolder = Diagnostics.EnsureStringNotNullOrWhiteSpace(() => tempFolder);
     this.tracer     = Diagnostics.EnsureArgumentNotNull(() => tracer);
 }
        /// <summary>
        /// Cleanup the temp folders - delete all folders under the temp path and the specified sub folder, that were created before the specified duration.
        /// </summary>
        /// <param name="subFolderName">The sub folder name</param>
        /// <param name="maximalFolderAgeInHours">The maximal age of a folder, in hours - all folders that are older than this will be deleted</param>
        /// <param name="tracer">The tracer to use</param>
        public static void CleanupTempFolders(string subFolderName, int maximalFolderAgeInHours = 6, IExtendedTracer tracer = null)
        {
            // Delete the all folders under the temp path and sub folder that were created over 6 hours ago
            // This handles scenarios of a previous crash that prevented the folder from being deleted
            // All deletion errors are ignored - if the folder is in use, it should not be deleted
            DirectoryInfo parentFolder = new DirectoryInfo(GetUserTempFolder(subFolderName));

            parentFolder.GetDirectories()
            .Where(subFolder => (DateTime.UtcNow - subFolder.CreationTimeUtc).TotalHours > maximalFolderAgeInHours)
            .ToList()
            .ForEach(subFolder => TryDeleteFolder(subFolder.FullName, tracer));
        }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MsiCredentialsFactory"/> class
 /// </summary>
 /// <param name="httpClientWrapper">The HTTP client wrapper</param>
 /// <param name="tracer">The tracer</param>
 public MsiCredentialsFactory(IHttpClientWrapper httpClientWrapper, IExtendedTracer tracer)
 {
     this.httpClientWrapper = httpClientWrapper;
     this.tracer            = tracer;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SmartDetectorRunnerInChildProcess"/> class
 /// </summary>
 /// <param name="childProcessManager">The child process manager</param>
 /// <param name="tracer">The tracer</param>
 public SmartDetectorRunnerInChildProcess(IChildProcessManager childProcessManager, IExtendedTracer tracer)
 {
     this.childProcessManager = childProcessManager;
     this.tracer = tracer;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SmartDetectorRepository"/> class.
 /// </summary>
 /// <param name="tracer">Log wrapper</param>
 /// <param name="storageProviderFactory">The Azure storage provider factory</param>
 public SmartDetectorRepository(IExtendedTracer tracer, ICloudStorageProviderFactory storageProviderFactory)
 {
     this.tracer          = Diagnostics.EnsureArgumentNotNull(() => tracer);
     this.containerClient = storageProviderFactory.GetSmartDetectorGlobalStorageContainer();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ChildProcessManager"/> class
 /// </summary>
 /// <param name="tracer">The tracer</param>
 public ChildProcessManager(IExtendedTracer tracer)
 {
     this.tracer = Diagnostics.EnsureArgumentNotNull(() => tracer);
 }
        /// <summary>
        /// Creates a new tracer instance and register it with the specified container
        /// </summary>
        /// <param name="container">The unity container</param>
        /// <param name="logger">The logger</param>
        /// <param name="traceToConsole">Whether to trace to console</param>
        /// <returns>The unity container, after registering the new tracer</returns>
        public static IUnityContainer WithTracer(this IUnityContainer container, TraceWriter logger, bool traceToConsole)
        {
            IExtendedTracer tracer = TracerFactory.Create(null, logger, traceToConsole);

            return(container.RegisterInstance(tracer));
        }