public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = new ExecuteResult();

        result.Status = StatusType.Success;
        int cheapSequence = 0;

        // TODO : Implement DryRun Functionality
        if (startInfo.IsDryRun)
        {
            throw new NotImplementedException("Dry Run Functionality Has Not Yet Been Implemented.");
        }

        OnProgress("DeleteFileHandler", "Handler Execution Begins.", StatusType.Running, 0, cheapSequence++);
        try
        {
            if (startInfo.Parameters != null)
            {
                parameters = HandlerUtils.Deserialize <DeleteFileHandlerParameters>(startInfo.Parameters);
            }

            bool isValid = Validate();

            if (isValid)
            {
                if (parameters.Targets != null)
                {
                    OnLogMessage("DeleteFileHandler", $"Starting Delete Of [{string.Join(",", parameters.Targets.ToArray())}]");
                    foreach (String target in parameters.Targets)
                    {
                        if (Utilities.IsDirectory(target))
                        {
                            ZephyrDirectory dir = Utilities.GetZephyrDirectory(target, clients);
                            dir.Delete(config.Recurse, config.StopOnError, config.Verbose, "DeleteFileHandler", Logger);
                        }
                        else
                        {
                            ZephyrFile file = Utilities.GetZephyrFile(target, clients);
                            file.Delete(config.StopOnError, config.Verbose, "DeleteFileHandler", Logger);
                        }
                    }
                    OnLogMessage("DeleteFileHandler", $"Finished Delete Of [{string.Join(",", parameters.Targets.ToArray())}]");
                }
            }
            else
            {
                OnLogMessage("DeleteFileHandler", "Validation Failed.", LogLevel.Error);
                throw new Exception("Invalid Input Received");
            }
        }
        catch (Exception e)
        {
            OnProgress("DeleteFileHandler", "Handler Execution Failed.", StatusType.Failed, 0, cheapSequence++, false, e);
            throw e;
        }

        OnProgress("DeleteFileHandler", "Handler Execution Completed.", StatusType.Complete, 0, cheapSequence++);
        return(result);
    }
Пример #2
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = new ExecuteResult();

        result.Status = StatusType.Success;
        int cheapSequence = 0;

        // TODO : Implement DryRun Functionality
        if (startInfo.IsDryRun)
        {
            throw new NotImplementedException("Dry Run Functionality Has Not Yet Been Implemented.");
        }

        try
        {
            OnProgress("ModifyFileHandler", "Handler Execution Begins.", StatusType.Running, 0, cheapSequence++);
            if (startInfo.Parameters != null)
            {
                parameters = HandlerUtils.Deserialize <MungeFileHandlerParameters>(startInfo.Parameters);
            }

            bool isValid = Validate();

            if (isValid)
            {
                if (parameters.Files != null)
                {
                    if (config.RunSequential || parameters.Files.Count == 1)
                    {
                        foreach (ModifyFileType file in parameters.Files)
                        {
                            ProcessFile(file, startInfo);
                        }
                    }
                    else
                    {
                        Parallel.ForEach(parameters.Files, file => ProcessFile(file, startInfo));
                    }
                }
            }
        }
        catch (Exception e)
        {
            OnProgress("ModifyFileHandler", "Handler Execution Failed.", StatusType.Failed, 0, cheapSequence++, false, e);
            if (e.InnerException != null)
            {
                OnProgress("ModifyFileHandler", "Inner Exception.", StatusType.Failed, 0, cheapSequence++, false, e.InnerException);
            }
            throw e;
        }

        OnProgress("ModifyFileHandler", "Handler Execution Ends.", StatusType.Running, 0, cheapSequence++);
        return(result);
    }
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        OnProgress("CopyFileHandler", "Handler Execution Begins.", StatusType.Running, 0, cheapSequence++);
        ExecuteResult result = new ExecuteResult();

        result.Status = StatusType.Success;

        // TODO : Implement DryRun Functionality
        if (startInfo.IsDryRun)
        {
            throw new NotImplementedException("Dry Run Functionality Has Not Yet Been Implemented.");
        }

        try
        {
            if (startInfo.Parameters != null)
            {
                parameters = HandlerUtils.Deserialize <CopyFileHandlerParameters>(startInfo.Parameters);
            }

            bool isValid = Validate();

            if (isValid)
            {
                if (parameters.FileSets != null)
                {
                    foreach (FileSet set in parameters.FileSets)
                    {
                        if (set != null && set.Sources != null && set.Destinations != null)
                        {
                            OnLogMessage("CopyFileHandler", $"Starting {config.Action} From [{string.Join(",", set.Sources.ToArray())}] To [{string.Join(",", set.Destinations)}].");
                            foreach (String destination in set.Destinations)
                            {
                                if (Utilities.IsDirectory(destination) && config.PurgeDestination)
                                {
                                    ZephyrDirectory clearDir = Utilities.GetZephyrDirectory(destination, clients);
                                    clearDir.Purge(config.StopOnError, config.Verbose, "Purge", Logger);
                                    OnLogMessage("CopyFileHandler", $"Directory [{destination}] Was Purged.");
                                }

                                foreach (String source in set.Sources)
                                {
                                    if (Utilities.IsDirectory(source))
                                    {
                                        ZephyrDirectory sourceDir = Utilities.GetZephyrDirectory(source, clients);
                                        if (Utilities.IsDirectory(destination))
                                        {
                                            // Copy/Move Directory To Directory
                                            ZephyrDirectory destDir = Utilities.GetZephyrDirectory(destination, clients);
                                            if (config.Action == FileAction.Copy)
                                            {
                                                sourceDir.CopyTo(destDir, config.Recurse, config.OverwriteExisting, config.StopOnError, config.Verbose, "Copy", Logger);
                                            }
                                            else
                                            {
                                                sourceDir.MoveTo(destDir, config.OverwriteExisting, config.StopOnError, config.Verbose, "Move", Logger);
                                            }
                                        }
                                        else
                                        {
                                            // This should never occur, as this scenario is addressed in "Validate".
                                            throw new Exception($"Can Not Copy Directory [{source}] To File [{destination}]");
                                        }
                                    }
                                    else
                                    {
                                        ZephyrFile sourceFile = Utilities.GetZephyrFile(source, clients);
                                        if (Utilities.IsDirectory(destination))
                                        {
                                            // Copy/Move File To Directory
                                            ZephyrDirectory destDir = Utilities.GetZephyrDirectory(destination, clients);
                                            if (config.Action == FileAction.Copy)
                                            {
                                                sourceFile.CopyTo(destDir, config.OverwriteExisting, true, config.StopOnError, config.Verbose, "Copy", Logger);
                                            }
                                            else
                                            {
                                                sourceFile.MoveTo(destDir, config.OverwriteExisting, true, config.StopOnError, config.Verbose, "Move", Logger);
                                            }
                                        }
                                        else
                                        {
                                            // Copy/Move File To File
                                            ZephyrFile destFile = Utilities.GetZephyrFile(destination, clients);
                                            if (config.Action == FileAction.Copy)
                                            {
                                                sourceFile.CopyTo(destFile, config.OverwriteExisting, true, config.StopOnError, config.Verbose, "Copy", Logger);
                                            }
                                            else
                                            {
                                                sourceFile.MoveTo(destFile, config.OverwriteExisting, true, config.StopOnError, config.Verbose, "Move", Logger);
                                            }
                                        }
                                    }
                                }
                            }
                            OnLogMessage("CopyFileHandler", $"Finished {config.Action} From [{string.Join(",", set.Sources.ToArray())}] To [{string.Join(",", set.Destinations)}].");
                        }
                    }
                }
            }
            else
            {
                OnLogMessage("CopyFileHandler", "Validation Failed.", LogLevel.Error);
                throw new Exception("Validation Failed.");
            }
        }
        catch (Exception e)
        {
            OnProgress("CopyFileHandler", "Handler Execution Failed.", StatusType.Failed, 0, cheapSequence++, false, e);
            throw e;
        }

        OnProgress("CopyFileHandler", "Handler Execution Completed.", StatusType.Complete, 0, cheapSequence++);
        return(result);
    }
 public override IHandlerRuntime Initialize(string configStr)
 {
     config      = HandlerUtils.Deserialize <CopyFileHandlerConfig>(configStr);
     clients.aws = HandlerUtils.InitAwsClient(config.Aws);
     return(base.Initialize(configStr));
 }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = null;

        if (startInfo.Parameters != null)
        {
            parameters = HandlerUtils.Deserialize <CommandHandlerParameters>(startInfo.Parameters);
        }

        try
        {
            OnLogMessage("Execute", $"Running Handler As User [{System.Security.Principal.WindowsIdentity.GetCurrent().Name}]");

            Validate();

            // Replace Any "Special" Handler Variables In Arguments or ReplaceWith elements
            variables            = HandlerUtils.GatherVariables(this, startInfo);
            parameters.Arguments = HandlerUtils.ReplaceHandlerVariables(parameters.Arguments, variables);
            if (parameters.Expressions != null)
            {
                foreach (RegexArguments expression in parameters.Expressions)
                {
                    expression.ReplaceWith = HandlerUtils.ReplaceHandlerVariables(expression.ReplaceWith, variables);
                }
            }

            String args = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);

            bool isDryRun = startInfo.IsDryRun && !(config.SupportsDryRun);
            if (startInfo.IsDryRun && config.SupportsDryRun)
            {
                OnLogMessage("Execute", "DryRun Flag is set, but plan config indicates the command supports DryRun.  Command will execute.");
            }

            if (String.IsNullOrEmpty(config.RunOn))
            {
                SecurityContext runAs = startInfo.RunAs;
                if (runAs != null && runAs.HasCrypto)
                {
                    runAs = startInfo.RunAs.GetCryptoValues(startInfo.RunAs.Crypto, false);
                }
                result = LocalProcess.RunCommand(config.Command, args, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, SynapseLogger, null, isDryRun, config.ReturnStdout, runAs?.Domain, runAs?.UserName, runAs?.Password);
            }
            else
            {
                result = WMIUtil.RunCommand(config.Command, args, config.RunOn, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, config.KillRemoteProcessOnTimeout, SynapseLogger, config.RunOn, isDryRun, config.ReturnStdout);
            }

            if (result.Status == StatusType.None)
            {
                result.Status = HandlerUtils.GetStatusType(result.ExitCode, config.ValidExitCodes);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            throw e;
        }

        OnLogMessage(config.RunOn, "Command finished with exit code = " + result.ExitCode + ".  Returning status [" + result.Status + "].");

        return(result);
    }
 public override IHandlerRuntime Initialize(string configStr)
 {
     config = HandlerUtils.Deserialize <CommandHandlerConfig>(configStr);
     return(base.Initialize(configStr));
 }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = null;

        if (startInfo.Parameters != null)
        {
            parameters = HandlerUtils.Deserialize <ScriptHandlerParameters>(startInfo.Parameters);
        }
        String script = null;

        try
        {
            String command      = null;
            String args         = null;
            bool   isTempScript = false;

            OnLogMessage("Execute", $"Running Handler As User [{System.Security.Principal.WindowsIdentity.GetCurrent().Name}]");

            Validate();

            // Replace Any "Special" Handler Variables In Arguments or ReplaceWith elements
            variables            = HandlerUtils.GatherVariables(this, startInfo);
            parameters.Arguments = HandlerUtils.ReplaceHandlerVariables(parameters.Arguments, variables);
            if (parameters.Expressions != null)
            {
                foreach (RegexArguments expression in parameters.Expressions)
                {
                    expression.ReplaceWith = HandlerUtils.ReplaceHandlerVariables(expression.ReplaceWith, variables);
                }
            }

            switch (config.Type)
            {
            case ScriptType.Powershell:
                command = "powershell.exe";
                if (!String.IsNullOrWhiteSpace(parameters.Script))
                {
                    isTempScript = false;
                    script       = parameters.Script;
                }
                else
                {
                    isTempScript = true;
                    script       = CreateTempScriptFile(parameters.ScriptBlock, "ps1");
                }
                args = config.Arguments + @" -File """ + script + @"""";
                if (!String.IsNullOrWhiteSpace(parameters.Arguments))
                {
                    String scriptArgs = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);
                    args += " " + scriptArgs;
                }
                break;

            case ScriptType.Batch:
                command = "cmd.exe";
                if (!String.IsNullOrWhiteSpace(parameters.Script))
                {
                    isTempScript = false;
                    script       = parameters.Script;
                }
                else
                {
                    isTempScript = true;
                    script       = CreateTempScriptFile(parameters.ScriptBlock, "bat");
                }
                args = config.Arguments + @" """ + script + @"""";
                if (!String.IsNullOrWhiteSpace(parameters.Arguments))
                {
                    String scriptArgs = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);
                    args += " " + scriptArgs;
                }

                break;

            default:
                throw new Exception("Unknown ScriptType [" + config.Type.ToString() + "] Received.");
            }

            bool isDryRun = startInfo.IsDryRun && !(config.SupportsDryRun);
            if (startInfo.IsDryRun && config.SupportsDryRun)
            {
                OnLogMessage("Execute", "DryRun Flag is set, but plan config indicates the script supports DryRun.  Script will execute.");
            }

            if (String.IsNullOrEmpty(config.RunOn))
            {
                SecurityContext runAs = startInfo.RunAs;
                if (runAs != null && runAs.HasCrypto)
                {
                    runAs = startInfo.RunAs.GetCryptoValues(startInfo.RunAs.Crypto, false);
                }
                result = LocalProcess.RunCommand(command, args, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, SynapseLogger, null, isDryRun, config.ReturnStdout, runAs?.Domain, runAs?.UserName, runAs?.Password);
            }
            else
            {
                result = WMIUtil.RunCommand(command, args, config.RunOn, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, config.KillRemoteProcessOnTimeout, SynapseLogger, config.RunOn, isDryRun, config.ReturnStdout);
            }

            if (result.Status == StatusType.None)
            {
                result.Status = HandlerUtils.GetStatusType(result.ExitCode, config.ValidExitCodes);
            }

            if (File.Exists(script) && isTempScript)
            {
                File.Delete(script);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            if (File.Exists(script))
            {
                File.Delete(script);
            }
            throw e;
        }

        OnLogMessage(config.RunOn, "Command finished with exit code = " + result.ExitCode + ".  Returning status [" + result.Status + "].");
        return(result);
    }