コード例 #1
0
        public override async Task <ExecutionResult> HandleAsync(Message message, ExecutionResult?previousResult, Action onHandled)
        {
            this.logger.LogDebug($"Asked to execute code:\n{((ExecuteRequestContent)message.Content).Code}");

            if (previousResult != null && previousResult.Value.Status != ExecuteStatus.Ok)
            {
                this.logger.LogDebug("Aborting due to previous execution result indicating failure: {PreviousResult}", previousResult.Value);
                onHandled();
                await SendAbortMessage(message);

                return(ExecutionResult.Aborted);
            }

            var executionCount = IncrementExecutionCount();

            shellServer.NotifyBusyStatus(message, ExecutionState.Busy);

            try
            {
                var result = await ExecutionTaskForMessage(message, executionCount, onHandled);

                return(result);
            }
            catch (TaskCanceledException tce)
            {
                this.logger?.LogDebug(tce, "Task cancelled.");
                return(new ExecutionResult
                {
                    Output = null,
                    Status = ExecuteStatus.Abort
                });
            }
            catch (Exception e)
            {
                this.logger?.LogError(e, "Unable to process ExecuteRequest");
                return(new ExecutionResult
                {
                    Output = e,
                    Status = ExecuteStatus.Error
                });
            }
            finally
            {
                shellServer.NotifyBusyStatus(message, ExecutionState.Idle);
            }
        }
コード例 #2
0
        public ExecutionResult RunTarget(ApplePlatform platform, ExecutionMode mode, string project, string target, Dictionary <string, string>?properties = null)
        {
            ExecutionResult rv;

            var props = new Dictionary <string, string> (Properties);

            if (properties != null)
            {
                foreach (var kvp in properties)
                {
                    props [kvp.Key] = kvp.Value;
                }
            }

            switch (mode)
            {
            case ExecutionMode.MSBuild:
                rv = MSBuild(platform, project, target, props);
                break;

            case ExecutionMode.DotNet:
                rv = Dotnet(project, "Build", target, props);
                break;

            default:
                throw new InvalidOperationException($"Unknown execution mode: {mode}");
            }

            executionResult = rv;

            Console.WriteLine($"Binlog: {rv.BinLogPath}");

            if (File.Exists(rv.BinLogPath))
            {
                ParseBinLog(rv.BinLogPath);
            }

            return(rv);
        }
コード例 #3
0
        private async Task <ExecutionResult> CoreExecuteAsync(ExecutionOptions options)
        {
            if (options.Schema == null)
            {
                throw new InvalidOperationException("Cannot execute request if no schema is specified");
            }
            if (options.Query == null && options.Document == null)
            {
                return new ExecutionResult {
                           Errors = new ExecutionErrors {
                               new QueryMissingError()
                           }
                }
            }
            ;

            var metrics = (options.EnableMetrics ? new Metrics() : Metrics.None).Start(options.OperationName);

            ExecutionResult? result            = null;
            ExecutionContext?context           = null;
            bool             executionOccurred = false;

            try
            {
                if (!options.Schema.Initialized)
                {
                    using (metrics.Subject("schema", "Initializing schema"))
                    {
                        options.Schema.Initialize();
                    }
                }

                var document = options.Document;

                bool saveInCache       = false;
                bool analyzeComplexity = true;
                var  validationRules   = options.ValidationRules;
                using (metrics.Subject("document", "Building document"))
                {
                    if (document == null && (document = await _documentCache.GetAsync(options.Query !).ConfigureAwait(false)) != null)
                    {
                        // none of the default validation rules yet are dependent on the inputs, and the
                        // operation name is not passed to the document validator, so any successfully cached
                        // document should not need any validation rules run on it
                        validationRules   = options.CachedDocumentValidationRules ?? Array.Empty <IValidationRule>();
                        analyzeComplexity = false;
                    }
                    if (document == null)
                    {
                        document    = _documentBuilder.Build(options.Query !);
                        saveInCache = true;
                    }
                }

                if (document.OperationsCount() == 0)
                {
                    throw new NoOperationError();
                }

                var operation = GetOperation(options.OperationName, document);
                if (operation == null)
                {
                    throw new InvalidOperationError($"Query does not contain operation '{options.OperationName}'.");
                }
                metrics.SetOperationName(operation.Name);

                IValidationResult validationResult;
                Variables         variables;
                using (metrics.Subject("document", "Validating document"))
                {
                    (validationResult, variables) = await _documentValidator.ValidateAsync(
                        new ValidationOptions
                    {
                        Document          = document,
                        Rules             = validationRules,
                        Operation         = operation,
                        UserContext       = options.UserContext,
                        RequestServices   = options.RequestServices,
                        CancellationToken = options.CancellationToken,
                        Schema            = options.Schema,
                        Variables         = options.Variables ?? Inputs.Empty,
                        Extensions        = options.Extensions ?? Inputs.Empty,
                    }).ConfigureAwait(false);
                }

                if (options.ComplexityConfiguration != null && validationResult.IsValid && analyzeComplexity)
                {
                    using (metrics.Subject("document", "Analyzing complexity"))
                        _complexityAnalyzer.Validate(document, options.ComplexityConfiguration);
                }

                if (saveInCache && validationResult.IsValid)
                {
                    await _documentCache.SetAsync(options.Query !, document).ConfigureAwait(false);
                }

                context = BuildExecutionContext(options, document, operation, variables, metrics);

                foreach (var listener in options.Listeners)
                {
                    await listener.AfterValidationAsync(context, validationResult) // TODO: remove ExecutionContext or make different type ?
                    .ConfigureAwait(false);
                }

                if (!validationResult.IsValid)
                {
                    return(new ExecutionResult
                    {
                        Errors = validationResult.Errors,
                        Perf = metrics.Finish()
                    });
                }

                if (context.Errors.Count > 0)
                {
                    return(new ExecutionResult
                    {
                        Errors = context.Errors,
                        Perf = metrics.Finish()
                    });
                }

                executionOccurred = true;

                using (metrics.Subject("execution", "Executing operation"))
                {
                    if (context.Listeners != null)
                    {
                        foreach (var listener in context.Listeners)
                        {
                            await listener.BeforeExecutionAsync(context)
                            .ConfigureAwait(false);
                        }
                    }

                    var task = (context.ExecutionStrategy ?? throw new InvalidOperationException("Execution strategy not specified")).ExecuteAsync(context)
                               .ConfigureAwait(false);

                    result = await task;

                    if (context.Listeners != null)
                    {
                        foreach (var listener in context.Listeners)
                        {
                            await listener.AfterExecutionAsync(context)
                            .ConfigureAwait(false);
                        }
                    }
                }

                result.AddErrors(context.Errors);
            }
            catch (OperationCanceledException) when(options.CancellationToken.IsCancellationRequested)
            {
                throw;
            }
            catch (ExecutionError ex)
            {
                (result ??= new()).AddError(ex);
            }
            catch (Exception ex)
            {
                if (options.ThrowOnUnhandledException)
                {
                    throw;
                }

                UnhandledExceptionContext?exceptionContext = null;
                if (options.UnhandledExceptionDelegate != null)
                {
                    exceptionContext = new UnhandledExceptionContext(context, null, ex);
                    await options.UnhandledExceptionDelegate(exceptionContext).ConfigureAwait(false);

                    ex = exceptionContext.Exception;
                }

                (result ??= new()).AddError(ex is ExecutionError executionError ? executionError : new UnhandledError(exceptionContext?.ErrorMessage ?? "Error executing document.", ex));
            }
            finally
            {
                result ??= new();
                result.Perf = metrics.Finish();
                if (executionOccurred)
                {
                    result.Executed = true;
                }
                context?.Dispose();
            }

            return(result);
        }
コード例 #4
0
 public override async Task <ExecutionResult> HandleAsync(Message message, ExecutionResult?previousResult) =>
 await HandleAsync(message, previousResult, () => {});
コード例 #5
0
        public async Task <ExecutionResult> ConnectAsync(IChannel channel,
                                                         string subscriptionId,
                                                         string resourceGroupName,
                                                         string workspaceName,
                                                         string storageAccountConnectionString,
                                                         string location,
                                                         CredentialType credentialType,
                                                         CancellationToken?cancellationToken = null)
        {
            var             duration = Stopwatch.StartNew();
            ExecutionResult?result   = null;

            try
            {
                // Capture the console output, specifically for the case the user is trying to use DeviceCode credentials
                // so they can get the message for auth.
                var currentOut = channel?.CaptureConsole();
                try
                {
                    var credential = CredentialFactory.CreateCredential(credentialType, subscriptionId);

                    var connectionResult = await ConnectToWorkspaceAsync(channel, subscriptionId, resourceGroupName, workspaceName, location, credential);

                    if (connectionResult.Status != ExecuteStatus.Ok)
                    {
                        result = connectionResult;
                        return(result.Value);
                    }

                    if (ActiveWorkspace == null)
                    {
                        result = AzureClientError.WorkspaceNotFound.ToExecutionResult();
                        return(result.Value);
                    }

                    Credential = credential;
                }
                finally
                {
                    System.Console.SetOut(currentOut);
                }

                StorageConnectionString = storageAccountConnectionString;
                ActiveTarget            = null;
                MostRecentJobId         = string.Empty;

                channel?.Stdout($"Connected to Azure Quantum workspace {ActiveWorkspace.WorkspaceName} in location {ActiveWorkspace.Location}.");

                if (ValidExecutionTargets.Count() == 0)
                {
                    channel?.Stderr($"No valid quantum computing execution targets found in Azure Quantum workspace {ActiveWorkspace.WorkspaceName}.");
                }

                result = ValidExecutionTargets.ToExecutionResult();
                return(result.Value);
            }
            finally
            {
                duration.Stop();

                ExecuteStatus    status           = result?.Status ?? ExecuteStatus.Error;
                AzureClientError?error            = result?.Output as AzureClientError?;
                bool             useCustomStorage = !string.IsNullOrWhiteSpace(StorageConnectionString);

                ConnectToWorkspace?.Invoke(this, new ConnectToWorkspaceEventArgs(status, error, location, useCustomStorage, credentialType, duration.Elapsed));
            }
        }