Example #1
0
        void TestArithmetic(MachineInfo mi, string type1, string type2, CBasicType result)
        {
            var report = new Report(new TestPrinter());

            var compiler = new Compiler.CCompiler(mi, report);

            compiler.AddCode("test.c", type1 + " v1; " + type2 + " v2;");
            var exe     = compiler.Compile();
            var context = new ExecutableContext(new Executable(mi), report);

            var ty1 = exe.Globals.First(x => x.Name == "v1").VariableType;

            Assert.IsInstanceOfType(ty1, typeof(CBasicType));
            var ty2 = exe.Globals.First(x => x.Name == "v2").VariableType;

            Assert.IsInstanceOfType(ty2, typeof(CBasicType));

            var bty1 = (CBasicType)ty1;
            var bty2 = (CBasicType)ty2;

            Assert.IsTrue(bty1.IsIntegral);
            Assert.IsTrue(bty2.IsIntegral);

            var aty1 = bty1.ArithmeticConvert(bty2, context);
            var aty2 = bty2.ArithmeticConvert(bty1, context);

            Assert.AreEqual(aty1.Signedness, result.Signedness);
            Assert.AreEqual(aty1.GetByteSize(context), result.GetByteSize(context));
            Assert.AreEqual(aty2.Signedness, result.Signedness);
            Assert.AreEqual(aty2.GetByteSize(context), result.GetByteSize(context));
        }
Example #2
0
        protected override void OnExecute(ExecutableContext context, IFile file)
        {
            context.Log($"Executing SQL script at '{file.FullPath}'...");

            string sql = FileStorage.Read(file.FullPath);

            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();

                using (var command = new SqlCommand(sql, conn))
                {
                    command.CommandType    = _commandType;
                    command.CommandTimeout = context.Timeout;
                    command.AddParameters(context.Parameters);

                    context.Log($"Parameter Arguments: {context.Parameters}");

                    var result = command.ExecuteNonQuery();

                    context.Log($"SQL command executed. Number of records affected: {result}.");
                }

                conn.Close();
            }
        }
Example #3
0
        public string ExecutePlugin()
        {
            bool success = false;

            try
            {
                var plugin = _pluginFactory.Create(_settings.TypeName, _settings.AssemblyName);
                if (plugin == null)
                {
                    throw new ArgumentNullException("Plugin instance empty.");
                }

                var context = new ExecutableContext(
                    _settings.IntegrationDirectory,
                    _settings.ExecutablesDirectory,
                    _settings.Parameters,
                    0,                 // default timeout to 0 as the timeout value will be used outside the scope of the plugin
                    Log);

                plugin.Execute(context);
                success = true;
            }
            catch (Exception ex)
            {
                success = false;
                Log($"Exception: {ex}");
            }

            return(Result(success));
        }
        public static void LogStartupHeading(this ExecutableContext context, string executableName)
        {
            string headingMessage = $"EXECUTABLE - {executableName}";

            context.Log(LogFormatter.GenerateHeadingLineSeparator(headingMessage));
            context.Log(headingMessage);
            context.Log(LogFormatter.GenerateHeadingLineSeparator(headingMessage));
        }
        public void Log_ThrowsException_WhenSuppliedLogActionIsNull()
        {
            var context   = new ExecutableContext("integrationDirectory", "executablesDirectory", parameters: null, timeout: 30, logAction: null);
            var exception = Record.Exception(() => context.Log("my_message"));

            Assert.NotNull(exception);
            Assert.IsType <ArgumentNullException>(exception);
        }
        private void LogOutput(string output, ExecutableContext context)
        {
            context.Log($"Plugin output:");
            string divider = $"----- PLUGIN {_typeName} -----";

            context.Log(divider);
            context.Log(output?.Trim());
            context.Log(new string('-', divider.Length));
        }
 protected override void OnExecute(ExecutableContext context)
 {
     ExecuteProcess(new ProcessStartInfo(_pluginExectorPath)
     {
         CreateNoWindow         = false,
         UseShellExecute        = false,
         RedirectStandardError  = true,
         RedirectStandardOutput = true,
         Arguments = BuildArguments(context)
     }, context);
 }
Example #8
0
        protected override void OnExecute(ExecutableContext context)
        {
            var file = FileStorage.GetFile(Path.Combine(context.ExecutablesDirectory, File));

            if (!file.Exists)
            {
                throw new FileNotFoundException($"Executable file '{file.FullPath}' not found.");
            }

            OnExecute(context, file);
        }
        public void Log_CallsLogAction_WhenSuppliedLogActionIsValid()
        {
            string          testingChangeValue = "not_my_message";
            Action <string> logAction          = (msg) =>
            {
                testingChangeValue = msg;
                return;
            };

            var context = new ExecutableContext("integrationDirectory", "executablesDirectory", parameters: null, timeout: 30, logAction: logAction);

            context.Log("my_message");

            Assert.Equal("my_message", testingChangeValue);
        }
Example #10
0
        protected override void OnExecute(ExecutableContext context, IFile file)
        {
            context.Log($"Executing batch file at '{file.FullPath}'...");

            var processInfo = new ProcessStartInfo("cmd.exe")
            {
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                Arguments = BuildArguments(file.FullPath, context)
            };

            ExecuteProcess(processInfo, context);
        }
        private void ExecuteProcess(ProcessStartInfo processStartInfo, ExecutableContext context)
        {
            context.Log("Starting new process for Plugin Executor...");
            context.Log($"Arguments: {processStartInfo.Arguments}");

            using (var process = System.Diagnostics.Process.Start(processStartInfo))
            {
                string output = process.StandardOutput.ReadToEnd();

                if (!process.WaitForExit(context.Timeout))
                {
                    try
                    {
                        process.Kill();
                    }
                    catch (Exception ex)
                    {
                        context.Log($"Killing process '{process?.Id}' FAILED. Exception: {ex}");
                    }
                    finally
                    {
                        throw new TimeoutException($"Plugin Executor process failed to process plugin '{TypeFullName}' in allotted timeout of {context.Timeout} seconds.");
                    }
                }
                else
                {
                    if (process.HasExited)
                    {
                        context.Log($"Plugin Executor process finished. ExitCode: {process.ExitCode}");
                    }
                    else
                    {
                        context.Log($"Plugin Executor process finished. NOT EXITED.");
                    }

                    process.Close();
                }

                LogOutput(output, context);

                if (!string.IsNullOrWhiteSpace(output) && output.StartsWith(LogFormatter.FailedResultCode))
                {
                    throw new ApplicationException($"CSharp Plugin '{TypeFullName}' failed execution. See plugin output in logs for details.");
                }
            }

            context.Log("Closed Plugin Executor process.");
        }
Example #12
0
        private void ExecuteProcess(ProcessStartInfo processStartInfo, ExecutableContext context)
        {
            context.Log($"Starting new process...");
            context.Log($"Arguments: {processStartInfo.Arguments}");

            using (var process = System.Diagnostics.Process.Start(processStartInfo))
            {
                process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => context.Log($"Batch file '{File}' OUTPUT => {e.Data}");
                process.BeginOutputReadLine();

                process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => context.Log($"Batch file '{File}' ERROR => {e.Data}");
                process.BeginErrorReadLine();

                if (!process.WaitForExit(context.Timeout))
                {
                    try
                    {
                        process.Kill();
                    }
                    catch (Exception ex)
                    {
                        context.Log($"Killing process '{process?.Id}' FAILED. Exception: {ex}");
                    }
                    finally
                    {
                        throw new TimeoutException($"Batch file '{File}' failed to execute in allotted timeout of {context.Timeout} seconds.");
                    }
                }
                else
                {
                    if (process.HasExited)
                    {
                        context.Log($"Batch file '{File}' ExitCode: {process.ExitCode}");
                    }
                    else
                    {
                        context.Log($"Batch file '{File}' NOT EXITED.");
                    }

                    process.Close();
                }

                context.Log($"Windows process for batch file '{File}' complete.");
            }
        }
Example #13
0
        private string BuildArguments(string filePath, ExecutableContext context)
        {
            string arguments = $"/c \"{filePath}\" \"{context.IntegrationDirectory}\"";

            if (context.Parameters == null || context.Parameters.Count == 0)
            {
                return(arguments);
            }

            var sb = new StringBuilder();

            foreach (var parameter in context.Parameters)
            {
                sb.Append(" ");
                sb.Append(parameter.Value);
            }

            return(string.Concat(arguments, sb.ToString().TrimEnd()));
        }
Example #14
0
        public void Sizes()
        {
            var printer = new TestPrinter();
            var mi      = new TestMachineInfo();
            var ec      = new ExecutableContext(new Executable(mi), new Report(printer));

            Interpreter.CompiledVariable ParseVariable(string code)
            {
                var exe = Compile(code, mi, printer);

                return(exe.Globals.Skip(1).First());
            }

            var charV = ParseVariable("char v;");

            Assert.AreEqual(1, charV.VariableType.GetByteSize(ec));

            var intV = ParseVariable("int v;");

            Assert.AreEqual(2, intV.VariableType.GetByteSize(ec));

            var shortIntV = ParseVariable("short int v;");

            Assert.AreEqual(2, shortIntV.VariableType.GetByteSize(ec));

            var unsignedLongV = ParseVariable("unsigned long v;");

            Assert.AreEqual(4, unsignedLongV.VariableType.GetByteSize(ec));

            var unsignedLongLongV = ParseVariable("unsigned long long v;");

            Assert.AreEqual(8, unsignedLongLongV.VariableType.GetByteSize(ec));

            var intPV = ParseVariable("int *v;");

            Assert.AreEqual(2, intPV.VariableType.GetByteSize(ec));

            var longPV = ParseVariable("long *v;");

            Assert.AreEqual(2, longPV.VariableType.GetByteSize(ec));
        }
        protected override void OnExecute(ExecutableContext context, IFile file)
        {
            context.Log($"Executing Powershell script at '{file.FullPath}'...");

            using (PowerShell instance = PowerShell.Create())
            {
                instance.AddCommand(file.FullPath);
                instance.AddParameters(context.Parameters);

                context.Log($"Parameter Arguments: {context.Parameters}");

                var success = instance.Execute(out string result);

                context.Log(result);

                if (!success)
                {
                    throw new ApplicationException($"PowerShell script '{File}' failed execution. See output in logs for details.");
                }
            }
        }
Example #16
0
        void TestPromote(MachineInfo mi, string type, int resultBytes, Signedness signedness)
        {
            var report  = new Report(new TestPrinter());
            var context = new ExecutableContext(new Executable(mi), report);

            var compiler = new Compiler.CCompiler(mi, report);

            compiler.AddCode("test.c", type + " v;");
            var exe = compiler.Compile();

            var ty = exe.Globals.First(x => x.Name == "v").VariableType;

            Assert.IsInstanceOfType(ty, typeof(CBasicType));
            var bty = (CBasicType)ty;

            Assert.IsTrue(bty.IsIntegral);
            var pty = bty.IntegerPromote(context);

            Assert.AreEqual(pty.Signedness, signedness);
            Assert.AreEqual(pty.GetByteSize(context), resultBytes);
        }
Example #17
0
        public void Execute(ExecutableContext context)
        {
            Guard.IsNotNull(context, nameof(context));

            context.LogStartupHeading(Name);

            if (context.Timeout > 0)
            {
                var task = Task.Run(() => OnExecute(context));
                if (!task.Wait(TimeSpan.FromSeconds(context.Timeout)))
                {
                    throw new TimeoutException($"Executable {Name} failed to finish executing within allotted timeout of {context.Timeout} seconds.");
                }
            }
            else
            {
                OnExecute(context);
            }

            context.Log($"** Executable {Name} completed. **");
        }
        private string BuildArguments(ExecutableContext context)
        {
            var sb = new StringBuilder();

            string libraryPath = Path.Combine(context.ExecutablesDirectory, "plugins", GetAssemblyFileName(_typeAssemblyName));

            sb.AppendKeyValueArgument("integrationdirectory", context.IntegrationDirectory);
            sb.AppendKeyValueArgument("executablesdirectory", context.ExecutablesDirectory);
            sb.AppendKeyValueArgument("library", libraryPath);
            sb.AppendKeyValueArgument("type", _typeName);
            sb.AppendKeyValueArgument("assembly", _typeAssemblyName);

            if (context.Parameters != null)
            {
                foreach (var parameter in context.Parameters)
                {
                    sb.AppendKeyValueArgument(parameter.Key, parameter.Value.ToString());
                }
            }

            return(sb.ToString().Trim());
        }
        public void Timeout_ReturnNumberGreaterThanZero_WhenZeroOrLessIsSupplied(int timeout)
        {
            var context = new ExecutableContext("integrationDirectory", "executablesDirectory", parameters: null, timeout: timeout, logAction: null);

            Assert.True(context.Timeout > 0, $"Timeout ({context.Timeout}) not greater than zero.");
        }
        public void Timeout_ReturnsSuppliedTimeout_WhenSuppliedTimeoutIsGreaterThanZero(int timeout)
        {
            var context = new ExecutableContext("integrationDirectory", "executablesDirectory", parameters: null, timeout: timeout, logAction: null);

            Assert.Equal(timeout, context.Timeout);
        }
        public void Parameters_ReturnEmpty_WhenNullParametersSupplied()
        {
            var context = new ExecutableContext("integrationDirectory", "executablesDirectory", parameters: null, timeout: 30, logAction: null);

            Assert.NotNull(context.Parameters);
        }
Example #22
0
 protected abstract void OnExecute(ExecutableContext context, IFile file);
Example #23
0
 protected abstract void OnExecute(ExecutableContext context);