public async Task WhenRunningSmartDetectorCheckResolutionForNonSupportingDetectorThenExceptionIsThrown()
        {
            // Initialize the resolution state
            this.InitializeResolutionState();

            // Set the detector to be non supporting
            this.alertResolutionCheckRequest.OriginalAnalysisRequest.SmartDetectorId = "1";

            // Run the Smart Detector and validate results
            ISmartDetectorRunner runner = this.testContainer.Resolve <ISmartDetectorRunner>();
            await runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, default(CancellationToken));
        }
        public async Task WhenRunningSmartDetectorCheckResolutionThenCustomExceptionsAreHandledCorrectly()
        {
            // Initialize the resolution state
            this.InitializeResolutionState();

            // Notify the Smart Detector that it should throw a custom exception
            this.autoResolveSmartDetector.ShouldThrowCustom = true;

            // Run the Smart Detector
            ISmartDetectorRunner runner = this.testContainer.Resolve <ISmartDetectorRunner>();
            await runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, default(CancellationToken));
        }
        public async Task WhenRunningSmartDetectorCheckResolutionItIsDisposedIfItImplementsIDisposable()
        {
            // Initialize the resolution state
            this.InitializeResolutionState();

            // Make the detector  a disposable one
            this.autoResolveSmartDetector = new DisposableTestAutoResolveSmartDetector {
                ExpectedResourceType = ResourceType.VirtualMachine
            };

            // Run the Smart Detector
            ISmartDetectorRunner runner = this.testContainer.Resolve <ISmartDetectorRunner>();
            await runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, default(CancellationToken));

            Assert.IsTrue(((DisposableTestAutoResolveSmartDetector)this.autoResolveSmartDetector).WasDisposed);
        }
        /// <summary>
        /// Run the Smart Detector, by delegating the call to the registered <see cref="ISmartDetectorRunner"/>
        /// </summary>
        /// <param name="request">The Smart Detector request</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A <see cref="Task{TResult}"/>, returning the result of the call to the runner.</returns>
        private static async Task <object> RunSmartDetectorAsync(SmartDetectorRunnerChildProcessInput request, CancellationToken cancellationToken)
        {
            ISmartDetectorRunner smartDetectorRunner = container.Resolve <ISmartDetectorRunner>();
            bool shouldDetectorTrace = bool.Parse(ConfigurationReader.ReadConfig("ShouldDetectorTrace", required: true));

            if (request.AnalysisRequest != null)
            {
                return(await smartDetectorRunner.AnalyzeAsync(request.AnalysisRequest, shouldDetectorTrace, cancellationToken));
            }
            else if (request.AlertResolutionCheckRequest != null)
            {
                return(await smartDetectorRunner.CheckResolutionAsync(request.AlertResolutionCheckRequest, shouldDetectorTrace, cancellationToken));
            }

            throw new ArgumentException("Unable to determine flow to run for Smart Detector", nameof(request));
        }
        public async Task WhenRunningSmartDetectorCheckResolutionAndAlertIsResolvedThenTheCorrectResponseIsReturned()
        {
            // Initialize the resolution state
            this.InitializeResolutionState();

            // Setup the detector to resolve the alert
            this.autoResolveSmartDetector.ShouldResolve = true;

            // Run the Smart Detector and validate results
            ISmartDetectorRunner runner = this.testContainer.Resolve <ISmartDetectorRunner>();
            ContractsAlertResolutionCheckResponse alertResolutionCheckResponse =
                await runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, default(CancellationToken));

            Assert.IsTrue(alertResolutionCheckResponse.ShouldBeResolved);
            Assert.IsNull(alertResolutionCheckResponse.ResolutionParameters);

            // Assert the detector's state
            Assert.AreEqual(1, this.stateRepository.Count);
            Assert.AreEqual("test state", this.stateRepository["test auto resolve key"]);
        }
        public async Task WhenRunningSmartDetectorCheckResolutionThenExceptionsAreHandledCorrectly()
        {
            // Initialize the resolution state
            this.InitializeResolutionState();

            // Notify the Smart Detector that it should throw an exception
            this.autoResolveSmartDetector.ShouldThrow = true;

            // Run the Smart Detector
            ISmartDetectorRunner runner = this.testContainer.Resolve <ISmartDetectorRunner>();

            try
            {
                await runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, default(CancellationToken));
            }
            catch (FailedToRunSmartDetectorException e)
            {
                // Expected exception
                Assert.IsNull(e.InnerException, "e.InnerException != null");
                Assert.IsTrue(e.Message.Contains(typeof(DivideByZeroException).Name), "e.Message.Contains(typeof(DivideByZeroException).Name)");
                throw;
            }
        }
        public async Task WhenRunningSmartDetectorCheckResolutionThenCancellationIsHandledGracefully()
        {
            // Initialize the resolution state
            this.InitializeResolutionState();

            // Notify the Smart Detector that it should get stuck and wait for cancellation
            this.autoResolveSmartDetector.ShouldStuck = true;

            // Run the Smart Detector asynchronously
            ISmartDetectorRunner    runner = this.testContainer.Resolve <ISmartDetectorRunner>();
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            Task t = runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, cancellationTokenSource.Token);

            SpinWait.SpinUntil(() => this.autoResolveSmartDetector.IsRunning);

            // Cancel and wait for expected result
            cancellationTokenSource.Cancel();
            FailedToRunSmartDetectorException ex = await Assert.ThrowsExceptionAsync <FailedToRunSmartDetectorException>(() => t);

            Assert.IsNull(ex.InnerException, "e.InnerException != null");
            Assert.IsTrue(ex.Message.Contains(typeof(TaskCanceledException).Name), "e.Message.Contains(typeof(TaskCanceledException).Name)");
            Assert.IsTrue(this.autoResolveSmartDetector.WasCanceled, "The Smart Detector was not canceled!");
        }
 public async Task WhenRunningSmartDetectorCheckResolutionAndStateIsNotFoundThenExceptionIsThrown()
 {
     // Run the Smart Detector and validate results
     ISmartDetectorRunner runner = this.testContainer.Resolve <ISmartDetectorRunner>();
     await runner.CheckResolutionAsync(this.alertResolutionCheckRequest, true, default(CancellationToken));
 }
Example #9
0
        public static async Task <HttpResponseMessage> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "checkResolution")] 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)
                ITracer tracer = childContainer.Resolve <ITracer>();
                tracer.TraceInformation($"CheckResolution 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
                    AlertResolutionCheckRequest alertResolutionCheckRequest = await request.Content.ReadAsAsync <AlertResolutionCheckRequest>(cancellationToken);

                    tracer.AddCustomProperty("SmartDetectorId", alertResolutionCheckRequest.OriginalAnalysisRequest.SmartDetectorId);
                    tracer.TraceInformation($"CheckResolution request received: {JsonConvert.SerializeObject(alertResolutionCheckRequest)}");

                    // Process the request
                    ISmartDetectorRunner runner = childContainer.Resolve <ISmartDetectorRunner>();
                    bool shouldDetectorTrace    = bool.Parse(ConfigurationReader.ReadConfig("ShouldDetectorTrace", required: true));
                    AlertResolutionCheckResponse alertResolutionCheckResponse =
                        await runner.CheckResolutionAsync(alertResolutionCheckRequest, shouldDetectorTrace, cancellationToken);

                    tracer.TraceInformation($"CheckResolution completed, alert {(alertResolutionCheckResponse.ShouldBeResolved ? "should" : "should not")} be resolved");

                    // 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(alertResolutionCheckResponse), 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();
                }
            }
        }