public IActionResult ExecuteJS([FromBody] RunRequest request) { try { if (request.ResultType == ResultTypeEnum.FileStream) { _engine.Execute($"var result = {request.Method.ToLower()}({request.Params})"); object result = _engine.GetValue("result").ToObject(); if (result == null) { return(StatusCode(500)); } return(new FileStreamResult((FileStream)result, "audio/mpeg")); } _engine.Execute($"var result = {request.Method.ToLower()}({request.Params})"); //_engine.Execute($"var result = {request.TableName.ToLower()}.{request.Method.ToLower()}({request.Params});"); return(Ok(_engine.GetValue("result").ToObject())); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
public SbError Run(SbPlatformShellCommand command) { var grpcSbPlatformShellCommand = new GrpcSbPlatformShellCommand { Command = command.GetCommand() }; var request = new RunRequest { ShellCommand = grpcSbPlatformShellCommand }; RunResponse response = null; if (connection.InvokeRpc(() => { response = client.Run(request); })) { command.SetOutput(response.Output); command.SetSignal(response.Signal); command.SetStatus(response.Status); return(sbErrorFactory.Create(response.Error)); } var grpcSbError = new GrpcSbError { Success = false, Error = "Rpc error while calling Run. Inspect the logs for more information." }; return(sbErrorFactory.Create(grpcSbError)); }
private void RunInVm() { // (1) Serialize sandboxed prosess info. SerializeSandboxedProcessInfoToFile(); // (2) Create and serialize run request. var runRequest = new RunRequest { AbsolutePath = m_tool.ExecutablePath, Arguments = m_tool.CreateArguments(GetSandboxedProcessInfoFile(), GetSandboxedProcessResultsFile()), WorkingDirectory = GetOutputDirectory() }; VmSerializer.SerializeToFile(RunRequestPath, runRequest); // (2) Create a process to execute VmCommandProxy. string arguments = $"{VmCommands.Run} /{VmCommands.Params.InputJsonFile}:\"{RunRequestPath}\" /{VmCommands.Params.OutputJsonFile}:\"{RunOutputPath}\""; var process = CreateVmCommandProxyProcess(arguments); LogExternalExecution($"call (wd: {process.StartInfo.WorkingDirectory}) {m_vmInitializer.VmCommandProxy} {arguments}"); m_processExecutor = new AsyncProcessExecutor( process, TimeSpan.FromMilliseconds(-1), // Timeout should only be applied to the process that the external tool executes. line => AppendLineIfNotNull(m_output, line), line => AppendLineIfNotNull(m_error, line), SandboxedProcessInfo.Provenance, message => LogExternalExecution(message)); m_processExecutor.Start(); }
protected override void ProcessRecord() { base.ProcessRecord(); RunRequest request; try { request = new RunRequest { NamespaceName = NamespaceName, ScheduledTaskId = ScheduledTaskId, TimeStart = TimeStart, TimeEnd = TimeEnd, OpcRequestId = OpcRequestId, OpcRetryToken = OpcRetryToken }; response = client.Run(request).GetAwaiter().GetResult(); WriteOutput(response); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
private async Task <Dictionary <string, PoolResult> > GetPoolMapAsync(RunRequest request) { using var channel = GrpcChannel.ForAddress(QueryUrl); var client = new QueryServiceClient(channel); var poolMap = new Dictionary <string, PoolResult>(); foreach (var pool in request.Profile.Pools) { var queryTicketRequest = new QueryTicketsRequest() { Pool = pool }; using var stream = client.QueryTickets(queryTicketRequest); var cts = new CancellationTokenSource(TimeSpan.FromSeconds(ApiTimeout)); var poolTickets = new List <Ticket>(); while (await stream.ResponseStream.MoveNext(cts.Token)) { poolTickets.AddRange(stream.ResponseStream.Current.Tickets); } if (0 == poolTickets.Count) { continue; } var result = new PoolResult(); result.Name = pool.Name; result.Tickets = poolTickets.ToList(); poolMap.Add(pool.Name, result); } return(poolMap); }
public override async Task <RunResponse> Run(RunRequest request, ServerCallContext context) { if (this._callerContext.CancellationToken.IsCancellationRequested || // if caller of UpAsync has cancelled context.CancellationToken.IsCancellationRequested) // if CLI has cancelled { return(new RunResponse()); } var args = request.Args; var engineAddr = args != null && args.Any() ? args[0] : ""; var settings = new InlineDeploymentSettings( engineAddr, request.MonitorAddress, request.Config, request.Project, request.Stack, request.Parallel, request.DryRun, request.ConfigSecretKeys); using var cts = CancellationTokenSource.CreateLinkedTokenSource( this._callerContext.CancellationToken, context.CancellationToken); this._callerContext.ExceptionDispatchInfo = await Deployment.RunInlineAsync( settings, runner => this._callerContext.Program.InvokeAsync(runner, cts.Token)) .ConfigureAwait(false); return(new RunResponse()); }
public async Task <ResponseContext <string> > RunAction(JobContext context) { IRestClient _client = Create(context.ClientHostUrl); var request = new RestRequest($"{_options.ApiUriSegments}/run", Method.POST); if (_options.Token.NotNullOrEmpty()) { request.AddHeader(JobConstant.Token, _options.Token); } var runRequest = new RunRequest() { JobId = context.Id, ExecutorHandler = context.Detail.ExecutorHandler, ExecutorParams = context.Detail.ExecutorParam, LogId = context.LogId, LogDateTime = context.LogDateTime }; request.AddRequestBody(_options.InputMessageType, runRequest); var response = await _client.ExecuteAsync(request); _logger.LogInformation($"core job run 请求完成,{response.IsSuccessful}, {response.StatusCode}"); return(response.GetResponseData <string>()); }
public void Run(RunRequest runRequest) { foreach (var nodeId in runRequest.NodeIds) { //TODO run list id begire dataFlowFacade.Run(nodeId); } }
/// <summary> /// Start a test run request. /// </summary> public async Task StartTestRunAsync(IEnumerable <TestCase> aTestCases, string aRevitVersion, Action <ProcessResult> aCallback, CancellationToken aCancellationToken) { RunRequest request = new RunRequest { Cases = aTestCases.ToArray() }; await StartTestRunAsync(request, aRevitVersion, aCallback, aCancellationToken); }
public RunResponse Run(RunRequest r) { var res = Run(r.NameFilter, r.Path, r.SuiteName, r.SupportAssemblies, r.TestRunnerType, r.TestRunnerAssembly, r.CrashLogFile); return(new RunResponse() { Result = res }); }
private async Task RunTests(RunRequest request, string aRevitVersion) { request.ClientName = Assembly.GetExecutingAssembly().GetCustomAttribute <AssemblyProductAttribute>().Product; request.ClientVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); TimeSpan duration = TimeSpan.Zero; System.Console.WriteLine($"App dir {FileNames.WatchDirectory}"); System.Console.WriteLine($"Start test run {DateTime.Now}; preferred on Revit {aRevitVersion}"); System.Console.WriteLine(); var complete = new List <TestCase>(); Client client = new Client(ProgramName, ProgramVersion); await client.StartTestRunAsync(request, aRevitVersion, result => { try { if (result.Result != null) { foreach (var test in result.Result.Cases.Where(c => c.State == TestState.Passed || c.State == TestState.Failed)) { if (complete.All(t => t.Id != test.Id)) { complete.Add(test); string testString = $"{test.Id,-8} Test {test.State,-7} - {test.TestClass}.{test.MethodName}"; System.Console.WriteLine(testString); if (!string.IsNullOrEmpty(test.Message)) { System.Console.WriteLine($"\t{test.Message}"); } if (!string.IsNullOrEmpty(test.StackTrace)) { System.Console.WriteLine($"\t{test.StackTrace}"); } duration = result.Duration; } } } } catch (Exception e) { System.Console.WriteLine($"Callback Exception: {e}"); } if (!string.IsNullOrEmpty(result.Message)) { System.Console.WriteLine(result.Message); } }, CancellationToken.None); int passedCount = complete.Count(t => t.State == TestState.Passed); System.Console.WriteLine(); System.Console.WriteLine($"Run finished - duration {duration:g} - {passedCount} of {complete.Count} Tests passed ({Math.Round( 100 * (double)passedCount / complete.Count )}%)"); }
public void RejectEmptyTempPath() { using (var temp = new TempRoot()) { var host = new TestableCompilerServerHost(); var request = new RunRequest(LanguageNames.CSharp, currentDirectory: temp.CreateDirectory().Path, tempDirectory: null, libDirectory: null, arguments: Array.Empty <string>()); var response = host.RunCompilation(request, CancellationToken.None); Assert.Equal(ResponseType.Rejected, response.Type); } }
public void RejectEmptyTempPath() { using (var temp = new TempRoot()) { var host = new TestableCompilerServerHost(); var request = new RunRequest(LanguageNames.CSharp, currentDirectory: temp.CreateDirectory().Path, tempDirectory: null, libDirectory: null, arguments: Array.Empty<string>()); var response = host.RunCompilation(request, CancellationToken.None); Assert.Equal(ResponseType.Rejected, response.Type); } }
public int Run(RunRequest request) { if (PTMKernelService.IsTestSuiteRunning()) { throw new NotSupportedException("PTMService does not support parallel run right now, please wait for the current running job to be completed and then try again."); } var result = PTMKernelService.CreateTestRun(request.ConfigurationId, request.SelectedTestCases); return(result); }
private async Task MainAsync(string[] args) { RunRequest request = null; string requestFile = GetFile(args); string revitVersion = GetVersion(args); if (!string.IsNullOrEmpty(requestFile)) { request = GetRequestFromFile(requestFile); } await RunTests(request, revitVersion); }
public ActionResult <AiResult> Post([FromBody] RunRequest request) { var compilationResult = _compiler.Compile(request.Code); if (!compilationResult.IsOk) { return(BadRequest(compilationResult)); } var ai = compilationResult.Ai; var aiResult = ai.Run(request.TrackState); return(Ok(aiResult)); }
public void TestRunExpression() { var handler = new CSScriptHandler(); var rr = new RunRequest { Kind = ScriptKind.Expression, Code = @" System.Environment.OSVersion.Platform " }; var rsp = handler.Process(rr) as RunResponse; Assert.AreEqual("Win32NT", rsp.Result + ""); }
public string Run(Application app, RunRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var stringBuilder = new StringBuilder(); ReflectionRunner runner = new ReflectionRunner(); foreach (TestCase test in request.Cases) { stringBuilder.Append(Run(app, runner, test)); } return(stringBuilder.ToString()); }
public void TestRunMethod() { var handler = new CSScriptHandler(); var rr = new RunRequest { Kind = ScriptKind.Method, Code = @" public object Run(params object[] args) { return System.Environment.OSVersion.Platform; } " }; var rsp = handler.Process(rr) as RunResponse; Assert.AreEqual("Win32NT", rsp.Result + ""); }
public async override Task Run(RunRequest request, grpc::IServerStreamWriter <global::OpenMatch.RunResponse> responseStream, grpc::ServerCallContext context) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var poolMap = await GetPoolMapAsync(request); if (0 == poolMap.Count) { return; } var matches = MakeMatches(request, poolMap); foreach (var match in matches) { await responseStream.WriteAsync(new RunResponse { Proposal = match }); } }
public RunResponse Run (RunRequest r) { EventListenerWrapper listenerWrapper = new EventListenerWrapper (server); UnhandledExceptionEventHandler exceptionHandler = (object sender, UnhandledExceptionEventArgs e) => { var ex = e.ExceptionObject; File.WriteAllText (r.CrashLogFile, e.ToString ()); }; AppDomain.CurrentDomain.UnhandledException += exceptionHandler; try { var res = Run (listenerWrapper, r.NameFilter, r.Path, r.SuiteName, r.SupportAssemblies, r.TestRunnerType, r.TestRunnerAssembly); res = res.SelectSingleNode ("test-suite"); return new RunResponse () { Result = listenerWrapper.GetLocalTestResult (res) }; } finally { AppDomain.CurrentDomain.UnhandledException -= exceptionHandler; } }
public override async Task <RunResponse> Run(RunRequest request, ServerCallContext context) { if (this._callerContext.CancellationToken.IsCancellationRequested || // if caller of UpAsync has cancelled context.CancellationToken.IsCancellationRequested) // if CLI has cancelled { return(new RunResponse()); } var args = request.Args; var engineAddr = args != null && args.Any() ? args[0] : ""; var settings = new InlineDeploymentSettings( _callerContext.Logger, engineAddr, request.MonitorAddress, request.Config, request.ConfigSecretKeys, request.Project, request.Stack, request.Parallel, request.DryRun); using var cts = CancellationTokenSource.CreateLinkedTokenSource( this._callerContext.CancellationToken, context.CancellationToken); var result = await Deployment.RunInlineAsync( settings, // ReSharper disable once AccessToDisposedClosure runner => this._callerContext.Program.InvokeAsync(runner, cts.Token)) .ConfigureAwait(false); if (result.ExitCode != 0 || result.ExceptionDispatchInfo != null) { this._callerContext.ExceptionDispatchInfo = result.ExceptionDispatchInfo; return(new RunResponse() { Bail = true, Error = result.ExceptionDispatchInfo?.SourceException.Message ?? "One or more errors occurred.", }); } return(new RunResponse()); }
/// <summary> /// Run report background job by id 83001 and wait until job finished as succeed or failed and get result /// </summary> public static DetailsResponse RunReportBackgroundJob() { const int reportId = 83001; var reportExportFormat = new RunRequest("xlsx"); var jobId = ApiClient.RunReport(reportId, reportExportFormat).JobId; while (true) { var jobState = ApiClient.GetJobById(jobId).JobState; if (jobState == StateType.Succeeded || jobState == StateType.Failed) { return(ApiClient.GetJobById(jobId)); } Thread.Sleep(millisecondsTimeout: 1000); } }
private List <Match> MakeMatches(RunRequest request, Dictionary <string, PoolResult> poolMap) { var matches = new List <Match>(); while (true) { var insufficientTickets = false; var matchTickets = new List <Ticket>(); foreach (var key in poolMap.Keys) { var pool = poolMap[key]; var tickets = pool.Tickets.ToList(); if (tickets.Count < MatchingCount) { insufficientTickets = true; break; } for (var i = 0; i < MatchingCount; i++) { var ticket = tickets[i]; matchTickets.Add(ticket); pool.Tickets.Remove(ticket); } } if (insufficientTickets) { break; } var match = new Match(); match.MatchId = $"profile-{request.Profile.Name}-{Guid.NewGuid().ToString()}"; match.MatchProfile = request.Profile.Name; match.MatchFunction = MatchFunctionName; match.Tickets.AddRange(matchTickets); matches.Add(match); } return(matches); }
public async Task <UnitTestResult> Run(IRemoteEventListener listener, string[] nameFilter, string path, string suiteName, List <string> supportAssemblies, string testRunnerType, string testRunnerAssembly, string crashLogFile) { this.listener = listener; var msg = new RunRequest { NameFilter = nameFilter, Path = path, SuiteName = suiteName, SupportAssemblies = supportAssemblies.ToArray(), TestRunnerType = testRunnerType, TestRunnerAssembly = testRunnerAssembly, CrashLogFile = crashLogFile }; var r = (await connection.SendMessage(msg)).Result; await connection.ProcessPendingMessages(); return(ToUnitTestResult(r)); }
public async Task<UnitTestResult> Run (IRemoteEventListener listener, string[] nameFilter, string path, string suiteName, List<string> supportAssemblies, string testRunnerType, string testRunnerAssembly, string crashLogFile) { this.listener = listener; var msg = new RunRequest { NameFilter = nameFilter, Path = path, SuiteName = suiteName, SupportAssemblies = supportAssemblies.ToArray (), TestRunnerType = testRunnerType, TestRunnerAssembly = testRunnerAssembly, CrashLogFile = crashLogFile }; var r = (await connection.SendMessage (msg)).Result; await connection.ProcessPendingMessages (); return ToUnitTestResult (r); }
// Run the specified command. public override Task <RunResponse> Run(RunRequest request, ServerCallContext context) { PreconditionCheck(); var shellCommand = sbPlatformShellCommandFactory.Create(request.ShellCommand.Command); var error = sbPlatform.Run(shellCommand); var grpcError = new GrpcSbError { Success = error.Success(), Error = error.GetCString() }; var response = new RunResponse { Error = grpcError, Output = shellCommand.GetOutput(), Signal = shellCommand.GetSignal(), Status = shellCommand.GetStatus() }; return(Task.FromResult(response)); }
public RunResponse Run(RunRequest r) { EventListenerWrapper listenerWrapper = new EventListenerWrapper(server); UnhandledExceptionEventHandler exceptionHandler = (object sender, UnhandledExceptionEventArgs e) => { var ex = e.ExceptionObject; File.WriteAllText(r.CrashLogFile, e.ToString()); }; AppDomain.CurrentDomain.UnhandledException += exceptionHandler; try { var res = Run(listenerWrapper, r.NameFilter, r.Path, r.SuiteName, r.SupportAssemblies, r.TestRunnerType, r.TestRunnerAssembly); res = res.SelectSingleNode("test-suite"); return(new RunResponse() { Result = listenerWrapper.GetLocalTestResult(res) }); } finally { AppDomain.CurrentDomain.UnhandledException -= exceptionHandler; } }
public RunRequest GetRequestFromAssembly(string assemblyPath) { var node = GetXmlNodeFromAssembly(assemblyPath); if (node == null) { return(null); } Console.WriteLine("****Node: "); Console.WriteLine(node.OuterXml); Console.WriteLine("**********"); var nunitTestSuite = new NUnitTestSuite(node); var nUnitCases = nUnitCaseFlattenService.Flatten(nunitTestSuite); var testCases = new List <TestCase>(); foreach (var nUnitCase in nUnitCases) { var testCase = new TestCase { Id = nUnitCase.Id, AssemblyPath = assemblyPath, TestClass = nUnitCase.ClassName, MethodName = nUnitCase.MethodName }; testCases.Add(testCase); } RunRequest request = new RunRequest { ClientName = "Revit", Timestamp = DateTime.Now, Cases = testCases.ToArray() }; return(request); }
public async Task <Result> RunSolution(RunRequest request) { var challenge = await _challengeService.Get(request.ChallengeId); var result = new Result { TestResults = new List <Models.Competition.TestResult>() }; foreach (var test in challenge.Tests) { var compileRequest = CreateCompileRequest(challenge, request.Language, request.SolutionCode, test.InputParameter); var compileResult = await _codeCompiler.RunCode(compileRequest); if (!string.IsNullOrEmpty(compileResult.Errors)) { result.Errors = compileResult.Errors; result.Warnings = compileResult.Warnings; break; } if (string.IsNullOrEmpty(result.Runtime)) { result.Runtime = compileResult.Statistic; } result.TestResults.Add(new Models.Competition.TestResult { Success = compileResult.Result == test.ExpectedResult, ActualResult = compileResult.Result, ExpectedResult = test.ExpectedResult, InputParameter = test.InputParameter, }); } result.Success = result.TestResults.Count(x => x.Success) == challenge.Tests.Count; result.Message = $"Passed {result.TestResults.Count(x => x.Success)} of {challenge.Tests.Count}"; return(result); }
private RunRequest GetRequestFromFile(string path) { RunRequest request = null; if (File.Exists(path)) { try { request = JsonHelper.FromFile <RunRequest>(path); System.Console.WriteLine($"Request loaded from '{path}'"); } catch (Exception e) { System.Console.WriteLine($"Can not create Request from '{path}' - {e}"); } } else { System.Console.WriteLine($"File does not exist '{path}'"); } return(request); }
public void TestRunClass() { var handler = new CSScriptHandler(); var rr = new RunRequest { Kind = ScriptKind.Class, Code = @" using System; using Stinkhorn.Script.API; public class Example : MarshalByRefObject, IRunnable { public object Run(params object[] args) { return System.Environment.OSVersion.Platform; } } " }; var rsp = handler.Process(rr) as RunResponse; Assert.AreEqual("Win32NT", rsp.Result + ""); }
/// <summary> /// Start a test run request. /// </summary> public async Task StartTestRunAsync(RunRequest aRequest, string aRevitVersion, Action <ProcessResult> aCallback, CancellationToken aCancellationToken) { aRequest.Timestamp = DateTime.Now; aRequest.Id = GenerateId(); aRequest.ClientName = mClientName; aRequest.ClientVersion = mClientVersion; var revit = RevitHelper.StartRevit(aRevitVersion); bool isRunnerAvailable = await IsRunnerAvailable(aCancellationToken); if (isRunnerAvailable) { string requestFilePath = FileNames.RunRequestFilePath(aRequest.Id); JsonHelper.ToFile(requestFilePath, aRequest); var responseDirectoryPath = await GetResponseDirectory(aRequest.Id); if (Directory.Exists(responseDirectoryPath)) { bool run = true; while (run && !aCancellationToken.IsCancellationRequested) { var runResult = JsonHelper.FromFile <RunResult>(Path.Combine(responseDirectoryPath, FileNames.RunResult)); if (runResult != null) { bool isCompleted = runResult.State == TestState.Passed || runResult.State == TestState.Failed; ProcessResult result = new ProcessResult(runResult, isCompleted); aCallback(result); run = !isCompleted; if (run) { await Task.Delay(500, aCancellationToken); } } } } else { FileHelper.DeleteWithLock(requestFilePath); aCallback(new ProcessResult(null, true) { Message = "Tests not executed! Service may not be running." }); } if (revit.IsNew) { RevitHelper.KillRevit(revit.ProcessId); } } else { aCallback(new ProcessResult(null, true) { Message = "Runner not available!" }); } }
BuildResponse ICompilerServerHost.RunCompilation(RunRequest request, CancellationToken cancellationToken) { return RunCompilation(request, cancellationToken); }
public RunResponse Run (RunRequest r) { var res = Run (r.NameFilter, r.Path, r.SuiteName, r.SupportAssemblies, r.TestRunnerType, r.TestRunnerAssembly, r.CrashLogFile); return new RunResponse () { Result = res }; }
public RunRequestHandler(IContainerManager containerManager, Request request) : base(containerManager, request) { this.request = (RunRequest)request; }