Beispiel #1
0
        private static Job initiateRunbookJob(OrchestratorApi sma, String runbookName, List <NameValuePair> runbookParameters)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
                delegate
            {
                return(true);
            });
            List <string> parameterNames = new List <string>();
            var           runbook        = (from rb in sma.Runbooks
                                            where rb.RunbookName == runbookName
                                            select rb).AsEnumerable().FirstOrDefault();

            if (runbook == null)
            {
                var msg = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", refStrings.RunbookNotFound, runbookName);
                throw new Exception(msg);
            }

            OperationParameter operationParameters = new BodyOperationParameter(refStrings.JobParameterName, runbookParameters);
            string             uri = string.Concat(sma.Runbooks, string.Format("(guid'{0}')/{1}", runbook.RunbookID, refStrings.StartRunbookActionName));
            Uri uriSMA             = new Uri(uri, UriKind.Absolute);

            // Create the job
            var jobIdValue = sma.Execute <Guid>(uriSMA, refStrings.HttpPost, true, operationParameters) as QueryOperationResponse <Guid>;
            var jobId      = jobIdValue.Single();

            var job = sma.Jobs.Where(j => j.JobID == jobId).AsEnumerable().FirstOrDefault();

            if (job == null)
            {
                throw new Exception(refStrings.JobNotStarted);
            }
            return(job);
        }
Beispiel #2
0
        /// <summary>
        /// Start Runbook with the the given Runbook and list of NameValuepair parameters
        /// </summary>
        /// <param name="runbook"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private RunbookJob StartRunBook(Runbook runbook, List <NameValuePair> parameters)
        {
            //try
            //{
            IgnoreCertificate();

            #region Setting up parameters for runbook



            OperationParameter operationParameters = new BodyOperationParameter(JobParameterName, parameters);


            #endregion Setting up parameters for runbook

            ValidateParameters(runbook, parameters);

            #region Create runbook job
            // Format the uri
            var uri    = string.Concat(api.Runbooks, string.Format("(guid'{0}')/{1}", runbook.RunbookID, StartRunbookActionName));
            var uriSMA = new Uri(uri, UriKind.Absolute);



            var jobIdValue = api.Execute <Guid>(uriSMA, HttpPost, true, operationParameters) as QueryOperationResponse <Guid>;


            var jobId = jobIdValue.Single();

            var job = api.Jobs.Where(j => j.JobID == jobId).First();
            if (job == null)
            {
                return(new RunbookJob {
                    OutputMessage = "Job not started!"
                });
            }
            else
            {
                return(new RunbookJob {
                    Id = jobId, OutputMessage = String.Format("Job Started. JobID: {0}, JobStatus: {1}", jobId, job.JobStatus)
                });
            }
            #endregion Create runbook job


            //  }

            //catch (DataServiceQueryException ex)
            //{
            //    throw new ApplicationException("Error starting runbook.", ex);

            //}
        }
        private bool CreateRunbookJob(OperationParameter operationParameters, out string errorStr)
        {
            try
            {
                string uri    = string.Concat(orchestratorApi.Runbooks, string.Format("(guid'{0}')/{1}", runbookId, "Start"));
                Uri    uriSMA = new Uri(uri, UriKind.Absolute);

                var jobIdValue = orchestratorApi.Execute <Guid>(uriSMA, "POST", true, operationParameters) as QueryOperationResponse <Guid>;
                jobIdValue.Single();
                errorStr = "";
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.InnerException.Message);
                Debug.WriteLine(ex.Message);
                errorStr = "Fejl: " + ex.InnerException.Message + " - " + ex.Message;
                return(false);
            }
        }
        private bool CreateRunbookJob(OperationParameter operationParameters, out string errorStr)
        {
            //System.IO.File.AppendAllText(@"C:\logs\adusercreation\service_log.txt", DateTime.Now + " - Starting runbook job " + Environment.NewLine);
            try
            {
                string uri    = string.Concat(orchestratorApi.Runbooks, string.Format("(guid'{0}')/{1}", runbookId, "Start"));
                Uri    uriSMA = new Uri(uri, UriKind.Absolute);

                var jobIdValue = orchestratorApi.Execute <Guid>(uriSMA, "POST", true, operationParameters) as QueryOperationResponse <Guid>;
                jobIdValue.Single();
                errorStr = "";
                //System.IO.File.AppendAllText(@"C:\logs\adusercreation\service_log.txt", DateTime.Now + " - finished runbook job " + Environment.NewLine);
                return(true);
            }
            catch (Exception ex)
            {
                errorStr = "Fejl: " + ex.InnerException.Message + " - " + ex.Message;
                return(false);
            }
        }
        public void ExecuteRunbook(string subscriptionId, OpsLogix.WAP.RunPowerShell.ApiClient.DataContracts.RunbookParameter rbParameter)
        {
            System.Configuration.ConnectionStringSettings url = System.Configuration.ConfigurationManager.ConnectionStrings["SMAUrl"];

            /*
             * var api = new OrchestratorApi(new Uri("https://sma.lab.local/00000000-0000-0000-0000-000000000000"));*/
            //var api = new OrchestratorApi(new Uri(url.ConnectionString));
            var api = new OrchestratorApi(new Uri(url.ConnectionString));

            ((DataServiceContext)api).Credentials = CredentialCache.DefaultCredentials;
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); });


            var runbook = api.Runbooks.Where(r => r.RunbookName == rbParameter.RunbookName).AsEnumerable().FirstOrDefault();

            if (runbook == null)
            {
                return;
            }


            var runbookParams = new List <NameValuePair>

            {
                new NameValuePair()
                {
                    Name = "Upn", Value = rbParameter.Upn
                },
                new NameValuePair()
                {
                    Name = "RunbookName", Value = rbParameter.RunbookName
                },
                new NameValuePair()
                {
                    Name = "SubscriptionId", Value = rbParameter.SubscriptionId
                },
                new NameValuePair()
                {
                    Name = "SelectedVmId", Value = rbParameter.SelectedVmId
                },
                new NameValuePair()
                {
                    Name = "ParamBool", Value = rbParameter.ParamBool
                },
                new NameValuePair()
                {
                    Name = "ParamString", Value = rbParameter.ParamString
                },
                new NameValuePair()
                {
                    Name = "ParamInt", Value = rbParameter.ParamInt
                },
                new NameValuePair()
                {
                    Name = "ParamDate", Value = rbParameter.ParamDate
                },
                new NameValuePair()
                {
                    Name = "ParamStringArray", Value = rbParameter.ParamStringArray
                }
            };



            OperationParameter operationParameters = new BodyOperationParameter("parameters", runbookParams);
            var uriSma     = new Uri(string.Concat(api.Runbooks, string.Format("(guid'{0}')/{1}", runbook.RunbookID, "Start")), UriKind.Absolute);
            var jobIdValue = api.Execute <Guid>(uriSma, "POST", true, operationParameters) as QueryOperationResponse <Guid>;

            if (jobIdValue == null)
            {
                return;
            }


            var jobId = jobIdValue.Single();

            Task.Factory.StartNew(() => QueryJobCompletion(jobId));
        }
        public void TestRunbook()
        {
#if !DEBUG
            try
            {
#endif
            Connect();
            View.Save();

            var runbook = ActiveRunbook == null ? null : api.Runbooks.Where(x => x.RunbookID == ActiveRunbook.Id).First();
            var path    = View.ActiveFile;

            RunbookVersion runbookVersion;
            if (runbook == null)
            {
                runbookVersion          = new RunbookVersion();
                runbookVersion.TenantID = new Guid("00000000-0000-0000-0000-000000000000");
                runbookVersion.IsDraft  = true;
                api.AddToRunbookVersions(runbookVersion);
            }
            else
            {
                runbookVersion = api.RunbookVersions.Where(x => x.RunbookVersionID == runbook.DraftRunbookVersionID && x.IsDraft).FirstOrDefault();
            }

            var baseStream = new StreamReader(path, Encoding.UTF8).BaseStream;
            ((DataServiceContext)api).SetSaveStream(runbookVersion, baseStream, true, "application/octet-stream", string.Empty);
            var response = api.SaveChanges().FirstOrDefault() as ChangeOperationResponse;

            if (runbook == null && response != null)
            {
                api.Execute <RunbookVersion>(((EntityDescriptor)response.Descriptor).EditLink).Count();
                runbook = api.Runbooks.Where(x => x.RunbookID == runbookVersion.RunbookID).First();

                RefreshRunbooks();
                ActiveRunbook        = Runbooks.First(x => x.Id == runbook.RunbookID);
                activeRunbooks[path] = runbook.RunbookID;
            }

            var parameters = RunbookParameters == null ? new List <NameValuePair>() : RunbookParameters.Where(x => !string.IsNullOrEmpty(x.Value)).Select(x => new NameValuePair {
                Name = x.Name, Value = SerializeValue(x)
            }).ToList();

            var result = runbook.TestRunbook(api, parameters);
            Job job;
            short?errors  = 0;
            var exception = "";

            while (!(job = api.Jobs.Where(x => x.JobID == result).First()).EndTime.HasValue)
            {
                if (job.JobStatus == "Suspended")
                {
                    errors    = job.ErrorCount;
                    exception = job.JobException;
                    job.Stop(api);
                }

                Thread.Sleep(1000);
            }

            if (job.JobStatus != "Stopped")
            {
                errors    = job.ErrorCount;
                exception = job.JobException;
            }

            var output = QueryHelpers.GetJobOutput(api, job);

            var message = string.Format("#### Started: {0} - Finished: {1} - Status: {2} - Errors: {5} ####\r\nError: {4}\r\nOutput: {3}\r\n########\r\n", job.StartTime, job.EndTime, job.JobStatus, output, exception, errors);
            AppendOutput(message);
#if !DEBUG
        }

        catch (Exception ex)
        {
            MessageBox.Show(GetErrorMessage(ex), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }
#endif
        }