private static string[] ExecuteScript(string code, params string[] arguments) { TextWriter output = Console.Out; TextWriter error = Console.Error; try { using (StringWriter writer = new StringWriter()) { Console.SetError(writer); Console.SetOut(writer); ExecuteScript((fileName, args) => ScriptExecution.Execute(fileName, args), code, arguments); writer.Flush(); string text = writer.GetStringBuilder().ToString(); return(text.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); } } finally { Console.SetOut(output); Console.SetError(error); } }
public static int Execute(IntPtr client, [MarshalAs(UnmanagedType.LPStr)] string args) { string[] arguments = args.Split(" ".ToCharArray()); return(ExecuteAction(client, () => { ScriptExecution.Execute(arguments[0], arguments.Skip(1).ToArray()); })); }
public static int Execute(string binaryPath, string parameters, TextWriter outStream, TextWriter errStream, StreamReader inputStream, int timeoutInMS, string workingDirectory) { ScriptExecution se = new ScriptExecution(outStream, errStream); int returnCode = -1; LogUtils.WriteTrace(DateTime.UtcNow, string.Format("Binary path : {0}", binaryPath)); LogUtils.WriteTrace(DateTime.UtcNow, string.Format("Binary parameters : {0}", parameters)); LogUtils.WriteTrace(DateTime.UtcNow, string.Format("Working directory : {0}", workingDirectory)); using (Process proc = CreateProcess(binaryPath, parameters, outStream, errStream, inputStream, workingDirectory)) { if (-1 != timeoutInMS) { if (!proc.WaitForExit(timeoutInMS)) { proc.ErrorDataReceived -= se.ErrorDataHandler; proc.OutputDataReceived -= se.OutputDataHandler; // The ScriptingHelper before throwing TimeoutException exception should // disable the output/input handlers of the ScriptExecution class as there // can be already scheduled output write events by the Process object in // the ThreadPool that will be executed asynchronously after the exception // is thrown. // As throwing the exception usually causes the output/input streams in // upper layer to be disposed the scheduled output write events by the // Process in the ThreadPool that are executed after the disposing would // throw in the background thread the ObjectDisposed exception that would cause the process to crash. // Therefore disabling here the handlers explicitly before throwing. se.DisableDataHandlers = true; LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "process {0} {1} timed out!", binaryPath, parameters)); throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "process {0} {1} timed out!", binaryPath, parameters)); } // Call to WaitForExit(Int32) returned >>>TRUE<<<, so we've exited without a timeout. But according to documentation, we're not guaranteed to // have completed processing of asynchronous events when redirecting stdout. // // Workaround is to call WaitForExit(void) a second time which won't return until async events finish processing. Waiting is important // so we can safely call StringBuilder.ToString() which is not thread safe, and we don't want event handlers to call StringBuilder.AppendLine // from parallel threads. // COMMENTED OUT: This blocks on opened handles if the child process starts another child process and then exists. // proc.WaitForExit(); proc.ErrorDataReceived -= se.ErrorDataHandler; proc.OutputDataReceived -= se.OutputDataHandler; se.DisableDataHandlers = true; } else { proc.WaitForExit(); } returnCode = proc.ExitCode; } return(returnCode); }
static void Main(string[] args) { Options options = null; Parser.Default.ParseArguments <Options>(args) .WithParsed(o => options = o); if (options == null) { return; } DebuggerInitialization.OpenDump(options.DumpPath, options.SymbolPath); Console.WriteLine("Threads: {0}", Thread.All.Length); Console.WriteLine("Current thread: {0}", Thread.Current.Id); var frames = Thread.Current.StackTrace.Frames; Console.WriteLine("Call stack:"); foreach (var frame in frames) { try { Console.WriteLine(" {0,3:x} {1}+0x{2:x} ({3}:{4})", frame.FrameNumber, frame.FunctionName, frame.FunctionDisplacement, frame.SourceFileName, frame.SourceFileLine); } catch (Exception) { Console.WriteLine(" {0,3:x} {1}+0x{2:x}", frame.FrameNumber, frame.FunctionName, frame.FunctionDisplacement); } } // In order to use console output and error in scripts, we must set it to debug client DebugOutput captureFlags = DebugOutput.Normal | DebugOutput.Error | DebugOutput.Warning | DebugOutput.Verbose | DebugOutput.Prompt | DebugOutput.PromptRegisters | DebugOutput.ExtensionWarning | DebugOutput.Debuggee | DebugOutput.DebuggeePrompt | DebugOutput.Symbols | DebugOutput.Status; var callbacks = DebuggerOutputToTextWriter.Create(Console.Out, captureFlags); using (OutputCallbacksSwitcher switcher = OutputCallbacksSwitcher.Create(callbacks)) { Action action = () => { ScriptExecution.Execute(@"..\..\samples\script.csx", args); }; DbgEngDll dbgEngDll = Context.Debugger as DbgEngDll; if (dbgEngDll != null) { dbgEngDll.ExecuteAction(action); } else { action(); } } }
internal void CompareScriptExecution(ScriptExecution a, ScriptExecution b) { if (a == null) { Assert.Null(b); } else { Assert.Equal(a.EnableScripts, b.EnableScripts); Assert.Equal(a.ExecutionPolicy, b.ExecutionPolicy); } }
public void ExecutionTest() { IScriptExecution execution = new ScriptExecution(Execution()); Assert.IsTrue(execution.IsAlive); Assert.AreEqual(0, execution.ExecuteNext()); Assert.IsTrue(execution.IsAlive); Assert.IsNull(execution.ExecuteNext()); Assert.IsTrue(execution.IsAlive); Assert.AreEqual("test", execution.ExecuteNext()); Assert.IsTrue(execution.IsAlive); Assert.AreEqual(12.5f, execution.ExecuteNext()); }
public static Process CreateProcess(string binaryPath, string parameters, TextWriter outStream, TextWriter errStream, StreamReader inputStream, string workingDirectory) { ScriptExecution se = new ScriptExecution(outStream, errStream); Process proc = new Process(); proc.EnableRaisingEvents = true; proc.ErrorDataReceived += se.ErrorDataHandler; proc.OutputDataReceived += se.OutputDataHandler; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.RedirectStandardOutput = true; if (inputStream != null) { proc.StartInfo.RedirectStandardInput = true; } proc.StartInfo.Arguments = parameters + string.Empty; proc.StartInfo.FileName = binaryPath; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; if (!string.IsNullOrEmpty(workingDirectory)) { proc.StartInfo.WorkingDirectory = workingDirectory; } proc.Start(); proc.BeginErrorReadLine(); proc.BeginOutputReadLine(); if (inputStream != null) { using (StreamWriter destinationStream = proc.StandardInput) { while (!inputStream.EndOfStream) { destinationStream.WriteLine(inputStream.ReadLine()); } } } return(proc); }
public override void Execute(ScriptEnvironment env) { var newEnv = env.Split(); var args = new object[ArgumentCount]; for (var i = 0; i < ArgumentCount; i++) { args[i] = env.Pop(); } for(var i = ArgumentCount - 1; i >= 0; i--) { newEnv.Push(args[i]); } newEnv.JumpToLabel(Label); newEnv.ProgramCounter++; var exec = new ScriptExecution(newEnv); env.ExecutionManager.Add(exec); }
public override void Execute(ScriptEnvironment env) { var newEnv = env.Split(); var args = new object[ArgumentCount]; for (var i = 0; i < ArgumentCount; i++) { args[i] = env.Pop(); } for (var i = ArgumentCount - 1; i >= 0; i--) { newEnv.Push(args[i]); } newEnv.JumpToLabel(Label); newEnv.ProgramCounter++; var exec = new ScriptExecution(newEnv); env.ExecutionManager.Add(exec); }
public void ScriptExecutionsAll() { using var context = MockContext.Start(this.GetType()); string rgName = "anullian-rg"; string cloudName = "anullian-southcentralus-runcommand"; string executionName = TestUtilities.GenerateName("scripting_execution"); using var avsClient = context.GetServiceClient <AvsClient>(); ScriptExecution execution = avsClient.ScriptExecutions.CreateOrUpdate(rgName, cloudName, executionName, new ScriptExecution { Timeout = "PT1H", ScriptCmdletId = "JSDR.Configuration/1.0.16/invoke-preflightjetdrsystemcheck" }); avsClient.ScriptExecutions.Get(rgName, cloudName, executionName); string[] outputStream = { "Output" }; avsClient.ScriptExecutions.GetExecutionLogs(rgName, cloudName, executionName, outputStream); avsClient.ScriptExecutions.List(rgName, cloudName); avsClient.ScriptExecutions.Delete(rgName, cloudName, executionName); }
/// <summary> /// Create or update a script execution resource in a private cloud /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// The name of the private cloud. /// </param> /// <param name='scriptExecutionName'> /// Name of the user-invoked script execution resource /// </param> /// <param name='scriptExecution'> /// A script running in the private cloud /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <ScriptExecution> BeginCreateOrUpdateAsync(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, ScriptExecution scriptExecution, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptExecution, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Create or update a script execution resource in a private cloud /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='privateCloudName'> /// The name of the private cloud. /// </param> /// <param name='scriptExecutionName'> /// Name of the user-invoked script execution resource /// </param> /// <param name='scriptExecution'> /// A script running in the private cloud /// </param> public static ScriptExecution BeginCreateOrUpdate(this IScriptExecutionsOperations operations, string resourceGroupName, string privateCloudName, string scriptExecutionName, ScriptExecution scriptExecution) { return(operations.BeginCreateOrUpdateAsync(resourceGroupName, privateCloudName, scriptExecutionName, scriptExecution).GetAwaiter().GetResult()); }
public override void Execute() { reqId = RandomRequest.GenerateId(); int min = this.min.StartsWith("$") ? ScriptEngine.GetVariable<int>(this.min) : int.Parse(this.min); int max = this.max.StartsWith("$") ? ScriptEngine.GetVariable<int>(this.max) : int.Parse(this.max); RandomRequest.Completed += Continue; Program.Client.Rpc.RandomReq(reqId, min, max); script = Script.ScriptEngine.Suspend(); }
private async System.Threading.Tasks.Task <SnowflakeTenant> ProcessInternalAsync(YamlJob job, string client) { ScriptExecution se = new ScriptExecution(); foreach (Step step in job.Steps) { job.Connection.User = Environment.GetEnvironmentVariable("SnowflakeUser"); job.Connection.Password = Environment.GetEnvironmentVariable("SnowflakePassword"); if (step.Ddl != null) { if (step.Ddl.Contains("!!locator!!")) { step.Ddl = step.Ddl.Replace("!!locator!!", _templateService.Tenant.Locator); } Console.WriteLine(step.Ddl); se.Command = step.Ddl; se.Message = await _snowflakeService.DdlAsync(job.Connection, step.Ddl, client); se.Status = ScriptStatus.Success.ToString(); } else if (step.Share != null) { Console.WriteLine(step.Share); se.Command = step.Share; se.Type = CommandType.Share.ToString(); se.Message = await _snowflakeService.CreateReaderAsync(job.Connection, step.Share, client); se.Status = ScriptStatus.Success.ToString(); _templateService.Tenant.Locator = se.Message; } } return(null); //try //{ // if (step.Ddl != null) // { // if (step.Ddl.Contains("!!locator!!")) // { // step.Ddl = step.Ddl.Replace("!!locator!!", c.Locator); // } // Console.WriteLine(step.Ddl); // se.Command = step.Ddl; // se.Type = CommandType.DdlStatement.ToString(); // se.Message = await sf.DdlAsync(job.Connection, step.Ddl); // se.Status = ScriptStatus.Success.ToString(); // } // else if (step.Share != null) // { // Console.WriteLine(step.Share); // se.Command = step.Share; // se.Type = CommandType.Share.ToString(); // se.Message = await sf.CreateReaderAsync(job.Connection, step.Share, client); // se.Status = ScriptStatus.Success.ToString(); // c.Locator = se.Message; // } // else if (step.File != null) // { // Console.WriteLine(step.File); // se.Command = step.File; // se.Type = CommandType.File.ToString(); // string scriptFile = System.IO.Path.Combine(path, step.File); // se.Message = await sf.FileAsync(job.Connection, scriptFile, ovcId, variables); // se.Status = ScriptStatus.Success.ToString(); // } // else // { // // ct = CommandType.Unknown; // } //} //catch (Exception ex) //{ // se.Message = ex.Message; // se.Status = ScriptStatus.Failure.ToString(); // tasks.Add(se); // break; //} // tasks.Add(se); //} //pr.Client = c; //pr.Steps = tasks; //return pr; }