public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        string message;

        try
        {
            message = "Deserializing incoming requests...";
            UpdateProgress(message, StatusType.Initializing);
            GroupMembershipRequest parms = DeserializeOrNew <GroupMembershipRequest>(startInfo.Parameters);

            message = "Processing individual child request...";
            UpdateProgress(message, StatusType.Running);
            ProcessAddRequests(parms, startInfo.IsDryRun);
            ProcessDeleteRequests(parms, startInfo.IsDryRun);

            message = (startInfo.IsDryRun ? "Dry run execution is completed" : "Execution is completed")
                      + (_encounteredFailure ? " with errors encountered" : "") + ".";
            UpdateProgress(message, _encounteredFailure ? StatusType.CompletedWithErrors : StatusType.Success);
        }
        catch (Exception ex)
        {
            message = $"Execution has been aborted due to: {ex.Message}";
            UpdateProgress(message, StatusType.Failed);
            _encounteredFailure = true;
        }
        _response.Status = message;

        message = "Serializing response...";
        UpdateProgress(message, StatusType.Any, true);
        _result.ExitData = JsonConvert.SerializeObject(_response);
        _result.ExitCode = _encounteredFailure ? -1 : 0;

        return(_result);
    }
Esempio n. 2
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        int seq = 1;

        string x = $"{startInfo.ParentExitData}";

        System.Threading.Thread.Sleep(5000);
        StatusType st     = StatusType.Complete;
        bool       cancel = OnProgress("BarExecute", getMsg(StatusType.Initializing, startInfo), StatusType.Initializing, startInfo.InstanceId, seq++);

        OnLogMessage("BarExecute", $"   ----------   {startInfo.ParentExitData}   ---------- working ----------");
        if (!cancel)
        {
            OnProgress("BarExecute", getMsg(StatusType.Running, startInfo), StatusType.Running, startInfo.InstanceId, seq++);
            if (!startInfo.IsDryRun)
            {
                OnProgress("BarExecute", "...Progress...", StatusType.Running, startInfo.InstanceId, seq++);
            }
            OnProgress("BarExecute", "Finished", st, startInfo.InstanceId, seq++);
        }
        else
        {
            st = StatusType.Cancelled;
            OnProgress("BarExecute", "Cancelled", st, startInfo.InstanceId, seq++);
        }
        WriteFile("BarHandler", $"parms:{startInfo.Parameters}\r\nstatus:{st}\r\n-->CurrentPrincipal:{System.Security.Principal.WindowsIdentity.GetCurrent().Name}");
        return(new ExecuteResult()
        {
            Status = st, ExitData = "bar"
        });
    }
Esempio n. 3
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = new ExecuteResult();

        result.Status = StatusType.Success;

        if (startInfo.Parameters != null)
        {
            parameters = this.DeserializeOrDefault <HandlerParameters>(startInfo.Parameters);
        }

        OnLogMessage("ConfigValues", "================================");
        OnLogMessage("ConfigValues", "ConfigValue1 = " + config.ConfigValue1);
        OnLogMessage("ConfigValues", "ConfigValue2 = " + config.ConfigValue2);
        foreach (String value in config.ConfigValues3)
        {
            OnLogMessage("ConfigValues", "ConfigValue3 = " + value);
        }

        OnLogMessage("ParamValues", "================================");
        OnLogMessage("ParamValues", "ParamValue1  = " + parameters.ParamValue1);
        OnLogMessage("ParamValues", "ParamValue2  = " + parameters.ParamValue2);
        foreach (String param in parameters.ParamValues3)
        {
            OnLogMessage("ParamValues", "ParamValue3  = " + param);
        }

        return(result);
    }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = new ExecuteResult()
        {
            Status = StatusType.Complete
        };
        string    msg       = string.Empty;
        Exception exception = null;

        UriHandlerParameters parms = DeserializeOrNew <UriHandlerParameters>(startInfo.Parameters);

        try
        {
            result.ExitData = GetUri(parms.Uri).Result;
            msg             = $"Successfully executed HttpClient.Get( {parms.Uri} ).";
        }
        catch (Exception ex)
        {
            result.Status   = StatusType.Failed;
            result.ExitData = msg = ex.Message;
            exception       = ex;
        }

        OnProgress("Execute", msg, result.Status, startInfo.InstanceId, Int32.MaxValue, false, exception);

        return(result);
    }
Esempio n. 5
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        XmlSerializer      ser    = new XmlSerializer(typeof(WorkflowParameters));
        WorkflowParameters wfp    = new WorkflowParameters();
        TextReader         reader = new StringReader(startInfo.Parameters);

        wfp = (WorkflowParameters)ser.Deserialize(reader);

        Workflow wf = new Workflow(wfp);

        wf.OnLogMessage = this.OnLogMessage;
        wf.OnProgress   = this.OnProgress;

        if (config.Aws != null)
        {
            wf.InitializeS3Client(config.Aws.AccessKey, config.Aws.SecretKey, config.Aws.AwsRegion);
        }

        wf.ExecuteAction(startInfo);

        return(new ExecuteResult()
        {
            Status = StatusType.Complete
        });
    }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        XmlSerializer      ser    = new XmlSerializer(typeof(WorkflowParameters));
        WorkflowParameters wfp    = new WorkflowParameters();
        TextReader         reader = new StringReader(startInfo.Parameters);

        wfp = (WorkflowParameters)ser.Deserialize(reader);

        Workflow wf = null;

        if (wfp.Oracle != null)
        {
            wf = new OracleWorkflow(wfp);
        }
        else if (wfp.SQLServer != null)
        {
            wf = new SQLServerWorkflow(wfp);
        }
        else
        {
            wf = new Workflow(wfp);
        }

        wf.OnLogMessage = this.OnLogMessage;
        wf.OnProgress   = this.OnProgress;

        seqNo = 0;
        OnProgress("Execute", "Starting", StatusType.Running, startInfo.InstanceId, seqNo++);
        wf.ExecuteAction(startInfo);

        return(new ExecuteResult()
        {
            Status = StatusType.Complete
        });
    }
    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);
    }
Esempio n. 8
0
        public Workflow Initialize(ref WorkflowParameters wfp, HandlerStartInfo startInfo)
        {
            _startInfo = startInfo;
            ((WorkflowParameters)wfp).InitIsValid();
            ((WorkflowParameters)wfp).PackageAdapterInstanceId = _startInfo.InstanceId + "";
            ((WorkflowParameters)wfp).RequestNumber            = _startInfo.RequestNumber;

            return(this);
        }
Esempio n. 9
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);
    }
Esempio n. 10
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        MockAdHandlerParameters parms = DeserializeOrNew <MockAdHandlerParameters>(startInfo.Parameters);


        OnProgress("Execute", StatusType.Success.ToString(), StatusType.Success, startInfo.InstanceId, Int32.MaxValue);

        return(new ExecuteResult()
        {
            Status = StatusType.Success, ExitData = parms
        });
    }
Esempio n. 11
0
 public EchoHandlerResult(HandlerStartInfo hsi, string config)
 {
     InstanceId       = hsi.InstanceId;
     IsDryRun         = hsi.IsDryRun;
     RequestUser      = hsi.RequestUser;
     RequestNumber    = hsi.RequestNumber;
     ParentExitData   = hsi.ParentExitData;
     Parameters       = hsi.Parameters;
     RunAs            = hsi.RunAs;
     Config           = config;
     CurrentPrincipal = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
 }
Esempio n. 12
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        EchoHandlerResult r      = new EchoHandlerResult(startInfo, _config);
        ExecuteResult     result = new ExecuteResult()
        {
            Status   = StatusType.Complete,
            ExitData = r
        };

        OnProgress("Execute", result.ExitData.ToString(), result.Status, startInfo.InstanceId, Int32.MaxValue);

        return(result);
    }
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        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.");
        }

        if (startInfo.Parameters != null)
        {
            parameters = this.DeserializeOrDefault <ScheduledTaskHandlerParameters>(startInfo.Parameters);
        }

        if (config.RunSequential)
        {
            foreach (ScheduledTask task in parameters.Tasks)
            {
                ProcessServiceRequest(config.Action, task, config.Timeout);
            }
        }
        else
        {
            Parallel.ForEach(parameters.Tasks, task =>
            {
                ProcessServiceRequest(config.Action, task, config.Timeout);
            });
        }

        switch (config.OutputType)
        {
        case OutputTypeType.Xml:
            result.ExitData = results.ToXml(config.PrettyPrint);
            break;

        case OutputTypeType.Yaml:
            result.ExitData = results.ToYaml();
            break;

        case OutputTypeType.Json:
            result.ExitData = results.ToJson(config.PrettyPrint);
            break;
        }

        OnLogMessage("Results", result.ExitData?.ToString());

        return(result);
    }
Esempio n. 14
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        int        seq = 1;
        StatusType st  = StatusType.Failed;

        try
        {
            Dictionary <object, object> p = Synapse.Core.Utilities.YamlHelpers.Deserialize(startInfo.Parameters);
            st = (StatusType)Enum.Parse(typeof(StatusType), p.Values.ElementAt(0).ToString());
        }
        catch { }

        string x = $"{startInfo.ParentExitData}";

        OnLogMessage("FooExecute", $"   - [[id]:[{startInfo.InstanceId}]] -   ----------   {startInfo.ParentExitData}   ---------- working ----------");

        System.Threading.Thread.Sleep(3000);
        //Int64 j = 0;
        //for( Int64 i = 0; i < 2000000000; i++ )
        //    j = i - 1;

        bool cancel = OnProgress("FooExecute", getMsg(StatusType.Initializing, startInfo), StatusType.Initializing, startInfo.InstanceId, seq++);

        OnLogMessage("FooExecute", $"   - [[id]:[{startInfo.InstanceId}]] -   ----------   loop complete   ---------- working ----------");

        if (!cancel)
        {
            OnProgress("FooExecute", getMsg(StatusType.Running, startInfo), StatusType.Running, startInfo.InstanceId, seq++);
            if (!startInfo.IsDryRun)
            {
                OnProgress("FooExecute", "...Progress...", StatusType.Running, startInfo.InstanceId, seq++);
            }
            //throw new Exception( "quitting" );
            OnProgress("FooExecute", "Finished", st, startInfo.InstanceId, seq++);
            OnLogMessage("FooExecute", $"Finished   - [[id]:[{startInfo.InstanceId}]] -");
        }
        else
        {
            st = StatusType.Cancelled;
            OnProgress("FooExecute", "Cancelled", st, startInfo.InstanceId, seq++);
            OnLogMessage("FooExecute", $"Cancelled   - [[id]:[{startInfo.InstanceId}]] -");
        }

        WriteFile("FooHandler", $"parms:{startInfo.Parameters}\r\nstatus:{st}\r\n-->CurrentPrincipal:{System.Security.Principal.WindowsIdentity.GetCurrent().Name}");
        return(new ExecuteResult()
        {
            Status = st, ExitData = "foo"
        });
    }
Esempio n. 15
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        string message;
        string xslt = "";

        try
        {
            message = "Deserializing incoming request...";
            UpdateProgress(message, StatusType.Initializing);
            Ec2Request parms = DeserializeOrNew <Ec2Request>(startInfo.Parameters);

            message = "Processing request...";
            UpdateProgress(message, StatusType.Running);
            ValidateRequest(parms);
            xslt = parms.Xslt;
            GetFilteredInstances(parms);

            message = "Querying against AWS has been processed" + (_encounteredFailure ? " with error" : "") + ".";
            UpdateProgress(message, _encounteredFailure ? StatusType.CompletedWithErrors : StatusType.Success);
            _response.Summary  = message;
            _response.ExitCode = _encounteredFailure ? -1 : 0;
        }
        catch (Exception ex)
        {
            UpdateProgress(ex.Message, StatusType.Failed);
            _encounteredFailure = true;
            _response.Summary   = ex.Message;
            _response.ExitCode  = -1;
        }
        finally
        {
            message = "Serializing response...";
            UpdateProgress(message);
            try
            {
                string xmlResponse    = Utilities.SerializeXmlResponse(_response);
                string transformedXml = Utilities.TransformXml(xmlResponse, xslt);
                string serializedData = Utilities.SerializeTargetFormat(transformedXml, _returnFormat);
                _result.ExitData = serializedData;
            }
            catch (Exception ex)
            {
                _result.ExitData = ex.Message;
            }
        }

        return(_result);
    }
Esempio n. 16
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        EmptyHandlerParameters parms = DeserializeOrNew <EmptyHandlerParameters>(startInfo.Parameters);

        if (parms.SleepMilliseconds > 0)
        {
            OnProgress("Execute", $"Sleeping for {parms.SleepMilliseconds}", StatusType.Waiting, startInfo.InstanceId, 1);
            System.Threading.Thread.Sleep(parms.SleepMilliseconds);
        }

        OnProgress("Execute", parms.ReturnStatus.ToString(), parms.ReturnStatus, startInfo.InstanceId, Int32.MaxValue);

        return(new ExecuteResult()
        {
            Status = parms.ReturnStatus, ExitData = parms.ExitData
        });
    }
Esempio n. 17
0
        public void ExecuteAction(HandlerStartInfo startInfo)
        {
            string context = "ExecuteAction";

            _startInfo = startInfo;

            string msg = Utils.GetHeaderMessage(string.Format("Entering Main Workflow."));

            if (OnStepStarting(context, msg))
            {
                return;
            }

            OnStepProgress(context, Utils.CompressXml(startInfo.Parameters));
            Stopwatch clock = new Stopwatch();

            clock.Start();

            Exception ex = null;

            try
            {
                bool isValid = ValidateParameters();

                if (isValid)
                {
                    RunMainWorkflow(startInfo.IsDryRun);
                }
                else
                {
                    OnStepProgress(context, "Package Validation Failed");
                    throw new Exception("Package Validation Failed");
                }
            }
            catch (Exception exception)
            {
                ex = exception;
            }

            bool ok = ex == null;

            msg = Utils.GetHeaderMessage(string.Format("End Main Workflow: {0}, Total Execution Time: {1}",
                                                       ok ? "Complete." : "One or more steps failed.", clock.ElapsedSeconds()));
//            OnStepFinished(context, msg, ok ? PackageStatus.Complete : PackageStatus.Failed, int.MaxValue, 0, ex);
            OnProgress(context, msg, ok ? StatusType.Complete : StatusType.Failed, _startInfo.InstanceId, int.MaxValue, false, ex);
        }
Esempio n. 18
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        string message;

        try
        {
            message = "Deserializing incoming request...";
            UpdateProgress(message, StatusType.Initializing);
            string           inputParameters = startInfo.Parameters;
            AwsS3FileRequest parms           = DeserializeOrNew <AwsS3FileRequest>(inputParameters);

            message = "Processing request...";
            UpdateProgress(message, StatusType.Running);

            if (parms != null)
            {
                if (string.IsNullOrWhiteSpace(parms.Uri))
                {
                }
            }
            //            ValidateRequest( parms );
            //            xslt = parms.Xslt;
            //            GetFilteredInstances( parms );
            //
            //            message = "Querying against AWS has been processed" + (_encounteredFailure ? " with error" : "") + ".";
            //            UpdateProgress( message, _encounteredFailure ? StatusType.CompletedWithErrors : StatusType.Success );
            //            _response.Summary = message;
            //            _response.ExitCode = _encounteredFailure ? -1 : 0;

            // AmazonS3Client s3Client = new AmazonS3Client(parms.AccessKey, parms.SecretKey, RegionEndpoint.USEast2 );
            //            var fileStream = s3Client.GetObjectStream("wu2-p3-0392-synapse-001", "Active Directory Role Based Management.pdf");
            //            s3Client.CopyObjectToLocal( "wu2-p3-0392-synapse-001", "Active Directory Role Based Management.pdf", "c:\\temp");
        }
        catch (Exception)
        {
//            UpdateProgress( ex.Message, StatusType.Failed );
//            _encounteredFailure = true;
//            _response.Summary = ex.Message;
//            _response.ExitCode = -1;
        }

        return(null);
    }
Esempio n. 19
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        try
        {
            UpdateProgress("Parsing incoming request...", StatusType.Running);
            _request = DeserializeOrDefault <UserRequest>(startInfo.Parameters);

            UpdateProgress("Executing request" + (startInfo.IsDryRun ? " in dry run mode..." : "..."), StatusType.Running);
            if (ValidateRequest(_request))
            {
                if (!startInfo.IsDryRun)
                {
                    _response = RunSsmCommand(_request, _config).Result;
                    UpdateProgress("Execution is completed.", StatusType.Complete, int.MaxValue);
                    if (_response == null)
                    {
                        _response = new SsmCommandResponse
                        {
                            Status = "Failed"
                        };
                    }
                    _response.Summary = _progressMessage;
                }
                else
                {
                    UpdateProgress("Dry run execution is completed.", StatusType.Complete, int.MaxValue);
                }
            }
        }
        catch (Exception ex)
        {
            string errorMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
            UpdateProgress($"Execution has been aborted due to: {errorMessage}", StatusType.Failed, int.MaxValue, LogLevel.Error, ex);
            _response = new SsmCommandResponse()
            {
                Status  = "Failed",
                Summary = _progressMessage
            };
        }

        _result.ExitData = _response;
        return(_result);
    }
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = new ExecuteResult
        {
            Status = StatusType.Success
        };

        _isDryRun = startInfo.IsDryRun;

        if( startInfo.Parameters != null )
            _parameters = this.DeserializeOrDefault<ServiceHandlerParameters>( startInfo.Parameters );


        if( _config.RunSequential )
            foreach( Service service in _parameters.Services )
                ProcessServiceRequest( _config.Action, service, _config.Timeout );
        else
            Parallel.ForEach( _parameters.Services,
                service => ProcessServiceRequest( _config.Action, service, _config.Timeout ) );


        switch( _config.OutputType )
        {
            case OutputTypeType.Xml:
            {
                result.ExitData = _results.ToXml( _config.PrettyPrint );
                break;
            }
            case OutputTypeType.Yaml:
            {
                result.ExitData = _results.ToYaml();
                break;
            }
            case OutputTypeType.Json:
            {
                result.ExitData = _results.ToJson( _config.PrettyPrint );
                break;
            }
        }

        OnLogMessage( "Results", result.ExitData?.ToString() );
        return result;
    }
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        XmlSerializer    ser    = new XmlSerializer(typeof(WinCoreContainer));
        WinCoreContainer wfp    = new WinCoreContainer();
        TextReader       reader = new StringReader(startInfo.Parameters);

        wfp = (WinCoreContainer)ser.Deserialize(reader);

        Workflow wf = new Workflow(wfp);

        wf.OnLogMessage = this.OnLogMessage;
        wf.OnProgress   = this.OnProgress;

        wf.ExecuteAction(startInfo);

        return(new ExecuteResult()
        {
            Status = StatusType.Complete
        });
    }
Esempio n. 22
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        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.");
        }

        if (startInfo.Parameters != null)
        {
            parameters = this.DeserializeOrDefault <HandlerParameters>(startInfo.Parameters);
        }

        OdbcDatabaseEngine db = new OdbcDatabaseEngine(config, parameters, Logger);

        result.ExitData = db.ExecuteCommand(startInfo.IsDryRun);

        return(result);
    }
Esempio n. 23
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        XmlSerializer      ser    = new XmlSerializer(typeof(WorkflowParameters));
        WorkflowParameters wfp    = new WorkflowParameters();
        TextReader         reader = new StringReader(startInfo.Parameters);

        wfp = (WorkflowParameters)ser.Deserialize(reader);

        Workflow wf = new Workflow(wfp)
        {
            OnLogMessage = this.OnLogMessage,
            OnProgress   = this.OnProgress
        };

        seqNo = 0;
        OnProgress("Execute", "Starting", StatusType.Running, startInfo.InstanceId, seqNo++);
        wf.Initialize(ref wfp, startInfo);
        wf.ExecuteAction();

        return(new ExecuteResult()
        {
            Status = StatusType.Complete
        });
    }
Esempio n. 24
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        int          sequenceNumber = 0;
        const string context        = "Execute";

        try
        {
            _mainProgressMsg = "Processing client request...";
            OnProgress(context, _mainProgressMsg, _result.Status, sequenceNumber);
            ClientRequest parms = DeserializeOrNew <ClientRequest>(startInfo.Parameters);

            _mainProgressMsg = "Validating request...";
            _result.Status   = StatusType.Running;
            ++sequenceNumber;
            OnProgress(context, _mainProgressMsg, _result.Status, sequenceNumber);

            ValidateClientRequest(parms);

            RestClient client = new RestClient(parms.Url);
//            client.Proxy = new WebProxy("http://127.0.0.1:8888");

            switch (parms.Authentication.ToUpper())
            {
            case "BASIC":
                client.Authenticator = new HttpBasicAuthenticator(parms.Username, parms.Password);
                break;

            case "DIGEST":
                client.Authenticator = new DigestAuthenticator(parms.Username, parms.Password);
                break;

            case "NTLM":
                if (string.IsNullOrWhiteSpace(parms.Username) && string.IsNullOrWhiteSpace(parms.Password) && string.IsNullOrWhiteSpace(parms.Domain))
                {
                    throw new Exception("Username, password or domain cannot be null.");
                }
                else
                {
                    client.Authenticator = new NtlmAuthenticator(new NetworkCredential(parms.Username, parms.Password, parms.Domain));
                }
                break;

            case "OAUTH1":
                client.Authenticator = new OAuth1Authenticator();
                break;

            case "OAUTH2":
                client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator("xxx", "yyy");
                break;

            case "NONE":
                break;

            default:
                throw new Exception("Authentication specified is invalid or not supported.");
            }

            bool isValidMethod = Enum.TryParse(parms.Method.ToUpper(), out Method method);
            if (isValidMethod)
            {
                RestRequest request = new RestRequest(method);
                if (method == Method.POST || method == Method.PUT)
                {
                    if (string.IsNullOrWhiteSpace(parms.ContentType))
                    {
                        throw new Exception("Content type cannot be null for POST and PUT method.");
                    }
                    request.AddParameter(parms.ContentType, parms.Body, ParameterType.RequestBody);
                }
                if (!startInfo.IsDryRun)
                {
                    IRestResponse response = client.Execute(request);
                    if (response.IsSuccessful)
                    {
                        _result.ExitData = response.Content;
                        _result.ExitCode = 0;
                    }
                    else
                    {
                        _result.ExitData = response.Content;
                        _result.ExitCode = -1;
                    }
                    _mainProgressMsg = response.StatusDescription;
                }
            }
            else
            {
                throw new Exception($"'{parms.Method}' is not a valid HTTP method.");
            }

            _mainProgressMsg = startInfo.IsDryRun ? "Dry run execution is completed." : $"Execution is completed. Server Status: {_mainProgressMsg}";
            _result.Status   = StatusType.Complete;
        }
        catch (Exception ex)
        {
            _mainProgressMsg = $"Execution has been aborted due to: {ex.Message}";
            OnLogMessage(context, _mainProgressMsg, LogLevel.Error);
            _result.Status   = StatusType.Failed;
            _result.ExitCode = -1;
        }

        _result.Message = _mainProgressMsg;
        OnProgress(context, _mainProgressMsg, _result.Status, int.MaxValue);

        return(_result);
    }
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        int           cheapSequence = 0;
        const string  __context     = "Execute";
        ExecuteResult result        = new ExecuteResult()
        {
            Status   = StatusType.Complete,
            Sequence = int.MaxValue
        };
        string    msg = "Complete";
        Exception exc = null;

        this.startInfo = startInfo;
        requestUser    = WhoAmI();
        isDryRun       = startInfo.IsDryRun;

        try
        {
            //deserialize the Parameters from the Action declaration
            ActiveDirectoryHandlerParameters parameters = YamlHelpers.Deserialize <ActiveDirectoryHandlerParameters>(startInfo.Parameters);

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

            //TODO : if IsDryRun == true, test if ConnectionString is valid and works.
            if (startInfo.IsDryRun)
            {
                OnProgress(__context, "Attempting connection", sequence: cheapSequence++);


                result.ExitData = "Success";
                result.Message  = msg =
                    $"Connection test successful!";

                throw new NotImplementedException("Dry Run Functionality Has Not Yet Been Implemented.");
            }
            else
            {
                switch (config.Action)
                {
                case ActionType.Get:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessGet);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessGet);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessGet);
                    break;

                case ActionType.Create:
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessCreate);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessCreate);
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessCreate);
                    break;

                case ActionType.Modify:
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessModify);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessModify);
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessModify);
                    break;

                case ActionType.Delete:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessDelete);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessDelete);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessDelete);
                    break;

                case ActionType.AddToGroup:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessGroupAdd);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessGroupAdd);
                    break;

                case ActionType.RemoveFromGroup:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessGroupRemove);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessGroupRemove);
                    break;

                case ActionType.AddAccessRule:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessAccessRules);
                    break;

                case ActionType.RemoveAccessRule:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessAccessRules);
                    break;

                case ActionType.SetAccessRule:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessAccessRules);
                    break;

                case ActionType.PurgeAccessRules:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessAccessRules);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessAccessRules);
                    break;

                case ActionType.AddRole:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessRoles);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessRoles);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessRoles);
                    break;

                case ActionType.RemoveRole:
                    ProcessActiveDirectoryObjects(parameters.Users, ProcessRoles);
                    ProcessActiveDirectoryObjects(parameters.Groups, ProcessRoles);
                    ProcessActiveDirectoryObjects(parameters.OrganizationalUnits, ProcessRoles);
                    break;

                case ActionType.Search:
                    ProcessSearchRequests(parameters.SearchRequests);
                    break;

                default:
                    throw new AdException($"Unknown Action {config.Action} Specified", AdStatusType.NotSupported);
                }
            }
        }
        //something wnet wrong: hand-back the Exception and mark the execution as Failed
        catch (Exception ex)
        {
            exc             = ex;
            result.Status   = StatusType.Failed;
            result.ExitData = msg =
                ex.Message + " | " + ex.InnerException?.Message;
        }

        if (string.IsNullOrWhiteSpace(result.ExitData?.ToString()))
        {
            result.ExitData = results.Serialize(config.OutputType, config.PrettyPrint);
        }

        if (!config.SuppressOutput)
        {
            OnProgress(__context, result.ExitData?.ToString(), result.Status, sequence: cheapSequence++, ex: exc);
        }

        //final runtime notification, return sequence=Int32.MaxValue by convention to supercede any other status message
        OnProgress(__context, msg, result.Status, sequence: int.MaxValue, ex: exc);

        return(result);
    }
Esempio n. 26
0
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = new ExecuteResult()
        {
            Status = StatusType.Complete
        };
        string    msg       = string.Empty;
        Exception exception = null;
        object    exitData  = null;

        SimpleUriHandlerParameters parms = DeserializeOrNew <SimpleUriHandlerParameters>(startInfo.Parameters);

        OnProgress("Execute", $"Beginning fetch for {parms.Uri}.", StatusType.Running, startInfo.InstanceId, 1);

        try
        {
            switch (parms.ParsedUri.Scheme)
            {
            case "http":
            case "https":
            {
                exitData = GetHttpUri(parms.Uri).Result;
                break;
            }

            case "file":
            {
                exitData = GetFileUri(parms.Uri);
                break;
            }

            case "s3":
            case "blob":
            default:
            {
                throw new NotSupportedException($"URI scheme {parms.ParsedUri.Scheme} is not supported.");
            }
            }

            exitData = FormatData(exitData, parms.Format);

            if (parms.HasMerge)
            {
                MergeData(ref exitData, parms.Merge, parms.Format);
            }

            result.ExitData = exitData;

            msg = $"Successfully executed HttpClient.Get( {parms.Uri} ).";
        }
        catch (Exception ex)
        {
            result.Status   = StatusType.Failed;
            result.ExitData = msg = ex.Message;
            exception       = ex;
        }

        OnProgress("Execute", msg, result.Status, startInfo.InstanceId, Int32.MaxValue, false, exception);

        return(result);
    }
Esempio n. 27
0
        /// <summary>
        /// Executes the main workflow.
        /// </summary>
        public void ExecuteAction(HandlerStartInfo startInfo)
        {
            string context = "ExecuteAction";

            _startInfo = startInfo;

            string msg = Utils.GetHeaderMessage(string.Format("Entering Main Workflow."));

            if (OnStepStarting(context, msg))
            {
                return;
            }

            OnStepProgress("ExecuteAction", Utils.CompressXml(startInfo.Parameters));

            Stopwatch clock = new Stopwatch();

            clock.Start();

            IProcessState state = new ServiceConfig();

            Exception ex = null;

            try
            {
                if (ValidateParameters())
                {
                    switch (_wfp.TargetType)
                    {
                    case ServiceType.Service:
                    {
                        state = ManageService(startInfo.IsDryRun);
                        break;
                    }

                    case ServiceType.AppPool:
                    {
                        state = ManageAppPool(startInfo.IsDryRun);
                        break;
                    }

                    case ServiceType.ScheduledTask:
                    {
                        state = ManageScheduledTask(startInfo.IsDryRun);
                        break;
                    }
                    }
                }
                else
                {
                    throw new Exception("Could not validate parameters.");
                }
            }
            catch (Exception exception)
            {
                ex = exception;
            }

            if (_wfp.IsValid)
            {
                OnStepProgress(context, "\r\n\r\n" + state.ToXml(true) + "\r\n");
            }

            bool ok = ex == null;

            OnProgress(context, state.State, ok ? StatusType.Complete : StatusType.Failed, _startInfo.InstanceId, int.MaxValue, false, ex);
        }
    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);
    }
Esempio n. 29
0
    public override ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        int         sequenceNumber = 0;
        string      context        = "Execute";
        DnsResponse response       = new DnsResponse
        {
            Results = new List <ActionResult>()
        };

        try
        {
            _mainProgressMsg = "Deserializing incoming request...";
            _result.Status   = StatusType.Initializing;
            ++sequenceNumber;
            OnProgress(context, _mainProgressMsg, _result.Status, sequenceNumber);
            OnLogMessage(context, _subProgressMsg);
            DnsRequest parms = DeserializeOrNew <DnsRequest>(startInfo.Parameters);


            _mainProgressMsg = "Processing individual child request...";
            _result.Status   = StatusType.Running;
            ++sequenceNumber;
            OnProgress(context, _mainProgressMsg, _result.Status, sequenceNumber);

            if (parms?.DnsActions != null)
            {
                foreach (DnsActionDetail request in parms.DnsActions)
                {
                    bool subTaskSucceed = false;
                    try
                    {
                        _subProgressMsg = "Verifying child request parameters...";
                        OnLogMessage(context, _subProgressMsg);
                        OnLogMessage(context, request.ToString());

                        if (ValidateActionParameters(request))
                        {
                            _subProgressMsg = "Executing request" + (startInfo.IsDryRun ? " in dry run mode..." : "...");
                            OnLogMessage(context, _subProgressMsg);
                            subTaskSucceed  = ExecuteDnsActions(request, _config, startInfo.IsDryRun);
                            _subProgressMsg = "Processed child request.";
                            OnLogMessage(context, _subProgressMsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        _subProgressMsg = ex.Message;
                        OnLogMessage(context, _subProgressMsg);
                        subTaskSucceed = false;
                    }
                    finally
                    {
                        response.Results.Add(new ActionResult()
                        {
                            Action     = request.Action,
                            RecordType = request.RecordType,
                            Hostname   = request.Hostname,
                            IpAddress  = request.IpAddress,
                            ExitCode   = subTaskSucceed ? 0 : -1,
                            Note       = _subProgressMsg
                        });
                    }
                }
                _result.Status = StatusType.Complete;
            }
            else
            {
                _result.Status   = StatusType.Failed;
                _mainProgressMsg = "No DNS action is found from the incoming request.";
                OnLogMessage(context, _mainProgressMsg, LogLevel.Error);
            }
        }
        catch (Exception ex)
        {
            _result.Status   = StatusType.Failed;
            _mainProgressMsg = $"Execution has been aborted due to: {ex.Message}";
            OnLogMessage(context, _mainProgressMsg, LogLevel.Error);
        }

        _mainProgressMsg = startInfo.IsDryRun ? "Dry run execution is completed." : "Execution is completed.";
        response.Summary = _mainProgressMsg;
        _result.ExitData = JsonConvert.SerializeObject(response);

        OnProgress(context, _mainProgressMsg, _result.Status, int.MaxValue);

        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);
    }