Exemplo n.º 1
0
        public async Task <JobExecutionResult <PingResponse> > ExecuteAsync(PingRequest input, CancellationToken cancel)
        {
            var output = new PingResponse();
            await Task.Delay(TimeSpan.FromSeconds(10), cancel);

            return(JobExecutionResult.Finished(output));
        }
Exemplo n.º 2
0
        public JobExecutionResult Execute()
        {
            JobExecutionResult executionResult;

            try
            {
                var isSuccess = ExecuteBuildPipeline(_executionContext);

                // on_success / on_failure only happens here, after we know the build status
                // they do intervene on build final status though
                isSuccess = isSuccess
                    ? Execute(_onSuccessStep, _executionContext)
                    : Execute(_onFailureStep, _executionContext);

                return(isSuccess
                    ? JobExecutionResult.CreateSuccess()
                    : JobExecutionResult.CreateFailure());
            }
            catch (SolutionNotFoundException)
            {
                executionResult = JobExecutionResult.CreateSolutionNotFound();
            }
            catch (Exception e)
            {
                executionResult = JobExecutionResult.CreateUnhandledException(e);
            }
            finally
            {
                // on_finish don't influence build final status so we just run it
                Execute(_onFinishStep, _executionContext);
            }

            return(executionResult);
        }
Exemplo n.º 3
0
        /// <summary>
        /// This timerjob will run simulate a short running job that optionally returns
        /// failures and recovery data.
        /// </summary>
        /// <param name="jobData">Ignored.</param>
        /// <param name="metaData">Ignored.</param>
        /// <returns>
        /// The method either takes between 2-5 seconds to return <see cref="JobResultStatus.Success"/> or
        /// randomly returns <see cref="JobResultStatus.Fail"/> or <see cref="JobResultStatus.FailRetry"/>.
        /// </returns>
        public JobExecutionResult Execute(string jobData, string metaData)
        {
            JobExecutionResult result = new JobExecutionResult();

            result.ResultStatus = JobResultStatus.Success;
            result.MetaData     = "";

            Random rnd    = new Random();
            int    random = rnd.Next(0, 100);

            if (random <= 10)
            {
                result.ResultStatus = JobResultStatus.Fail;
                result.ErrorMessage = "Random Error Margin : " + random;
                random = rnd.Next(0, 100);
                if (random <= 50)
                {
                    result.ResultStatus = JobResultStatus.FailRetry;
                    result.MetaData     = "Recovery Data Margin : " + random;
                }
            }
            else if (random <= 15)
            {
                throw new Exception("Exception with Error Margin : " + random);
            }
            else
            {
                System.Threading.Thread.Sleep(rnd.Next(2000, 5000));
            }

            return(result);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var instance = new Program();
            JobExecutionResult jobResult = instance.RunJob(jobName);

            switch (jobResult)
            {
            case JobExecutionResult.Succeeded:
                Console.WriteLine($"SQL Server Agent job, '{jobName}', ran successfully to completion.");
                break;

            case JobExecutionResult.FailedToStart:
                Console.WriteLine($"SQL Server Agent job, '{jobName}', failed to start.");
                break;

            case JobExecutionResult.FailedAfterStart:
                Console.WriteLine($"SQL Server Agent job, '{jobName}', started successfully, but encountered an error.");
                break;

            default:
                Console.WriteLine($"Unknown result from attempting to run SQL Server Agent job, '{jobName}'.");
                break;
            }

            Console.ReadLine();
            return;
        }
Exemplo n.º 5
0
        public JobExecutionResult WorkOn(Job job)
        {
            JobExecutionResult result = null;

            result = this.Channel.WorkOn(job);

            return(result);
        }
Exemplo n.º 6
0
        public JobExecutionResult Execute(string jobData, string metaData)
        {
            JobExecutionResult result = new JobExecutionResult {
                ResultStatus = JobResultStatus.Fail
            };

            try
            {
                WebRequestSettings settings = Utils.DeserializeObject <WebRequestSettings>(metaData);
                if (settings == null)
                {
                    throw new ArgumentException("Metadata does not contain a valid WebRequestSettings serialized object.");
                }
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(settings.Url);
                webRequest.Method = "GET";
                if (settings.UseDefaultCredentials)
                {
                    webRequest.UseDefaultCredentials = true;
                }
                else
                {
                    if (!settings.CredentialType.HasValue)
                    {
                        throw new ArgumentException("If UseDefaultCredentials == true, then CredentialType has to be specified");
                    }

                    webRequest.UseDefaultCredentials = false;
                    NetworkCredential networkCredential = new NetworkCredential(settings.Username, settings.Password);
                    if (!string.IsNullOrEmpty(settings.Domain))
                    {
                        networkCredential.Domain = settings.Domain;
                    }

                    CredentialCache credentialCache = new CredentialCache();
                    credentialCache.Add(webRequest.RequestUri, settings.CredentialType.Value.ToString(), networkCredential);
                    webRequest.Credentials = networkCredential;
                }

                JobBuilder.AddRequestHeaders(webRequest, settings.Headers);

                if (settings.TimeoutMilliseconds > 0)
                {
                    webRequest.Timeout = settings.TimeoutMilliseconds;
                }

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                if (webResponse.StatusCode == settings.ExpectedResponseCode)
                {
                    result.ResultStatus = JobResultStatus.Success;
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = Utils.GetExceptionMessage(ex);
            }

            return(result);
        }
Exemplo n.º 7
0
        public JobExecutionResult Execute(string jobData, string metaData)
        {
            JobExecutionResult result = new JobExecutionResult {
                MetaData = metaData, ResultStatus = JobResultStatus.Fail
            };

            MailMessage mailMessage = null;

            if (string.IsNullOrEmpty(jobData))
            {
                result.ErrorMessage = "JobData is not a valid SerializableMailMessageWrapper object.";
                return(result);
            }
            try
            {
                mailMessage = new SerializableMailMessageWrapper(jobData).GetBase();
            }
            catch (Exception ex)
            {
                result.ErrorMessage = "JobData is not a valid SerializableMailMessageWrapper object.\n\n" + Utils.GetExceptionMessage(ex);
                return(result);
            }

            MailSettings mailSettings = null;

            if (!string.IsNullOrEmpty(metaData))
            {
                try
                {
                    mailSettings = Utils.DeserializeObject <MailSettings>(metaData);
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = Utils.GetExceptionMessage(ex);
                    return(result);
                }
            }

            try
            {
                Execute(mailMessage, mailSettings);
                result.ResultStatus = JobResultStatus.Success;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = Utils.GetExceptionMessage(ex);
            }
            return(result);
        }
Exemplo n.º 8
0
 private static void TestExecutionResult(JobExecutionResult execResult, char jobName)
 {
     Assert.IsNotNull(execResult);
     Assert.AreEqual <char>(jobName, execResult.JobName);
     if (jobName == char.ToLower(jobName))
     {
         Assert.AreEqual <char>(jobName, execResult.JobName);
         Assert.IsFalse(execResult.IsSucceeded);
         Assert.IsNotNull(execResult.ErrorMassage);
     }
     else
     {
         Assert.IsTrue(execResult.IsSucceeded);
         Assert.IsNull(execResult.ErrorMassage);
         Assert.IsTrue(execResult.ExecutionTime.Ticks > 0);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Handles a job item.
        /// </summary>
        /// <param name="ctx">The underlying item context.</param>
        protected virtual void HandleJobItem(IForAllItemExecutionContext <IJob, DateTimeOffset> ctx)
        {
            List <Exception> occuredErrors = new List <Exception>();

            DateTimeOffset      completedAt;
            JobExecutionContext execCtx = new JobExecutionContext();

            try
            {
                execCtx.Job        = ctx.Item;
                execCtx.ResultVars = new Dictionary <string, object>(EqualityComparerFactory.CreateCaseInsensitiveStringComparer(true, true));
                execCtx.SyncRoot   = new object();
                execCtx.Time       = ctx.State;

                execCtx.Job
                .Execute(execCtx);

                completedAt = AppTime.Now;
            }
            catch (Exception ex)
            {
                completedAt = AppTime.Now;

                AggregateException aggEx = ex as AggregateException;
                if (aggEx != null)
                {
                    occuredErrors.AddRange(CollectionHelper.OfType <Exception>(aggEx.InnerExceptions));
                }
                else
                {
                    occuredErrors.Add(ex);
                }
            }

            JobExecutionResult result = new JobExecutionResult();

            result.Context = execCtx;
            result.Errors  = occuredErrors.ToArray();
            result.Vars    = new TMReadOnlyDictionary <string, object>(execCtx.ResultVars);
            result.Time    = completedAt;

            this.RaiseEventHandler(this.Executed,
                                   new JobExecutionResultEventArgs(result));
        }
Exemplo n.º 10
0
        public JobExecutionResult Execute(string jobData, string metaData)
        {
            JobExecutionResult result = new JobExecutionResult {
                ResultStatus = JobResultStatus.Fail, ErrorMessage = "Initialization Error.", MetaData = metaData
            };
            CompositeBasicHttpCallbackJobMetaData compositeCallbackJobData = null;
            BasicHttpCallbackJobMetaData          basicCallbackJobData     = null;

            try
            {
                if (string.IsNullOrEmpty(metaData))
                {
                    throw new ArgumentException("MetaData does not contain valid data.");
                }
                if (metaData.Contains("<CompositeBasicHttpCallbackJobMetaData "))
                {
                    compositeCallbackJobData = Utils.DeserializeObject <CompositeBasicHttpCallbackJobMetaData>(metaData);
                }
                else if (metaData.Contains("<BasicHttpCallbackJobMetaData "))
                {
                    basicCallbackJobData = Utils.DeserializeObject <BasicHttpCallbackJobMetaData>(metaData);
                }
                else
                {
                    throw new ArgumentException("MetaData does not contain valid data.");
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = Utils.GetExceptionMessage(ex);
            }
            if (compositeCallbackJobData != null)
            {
                result = Execute(jobData, compositeCallbackJobData);
            }
            else if (basicCallbackJobData != null)
            {
                result = Execute(jobData, basicCallbackJobData);
            }

            return(result);
        }
        public async Task <JobExecutionResult> ProcessSingleJob(
            TJobKey jobId,
            IJobMetadata jobMetadata,
            TSchedulerKey schedluerId,
            CancellationToken cancellationToken)
        {
            if (!await this.TryCaptureExecutionThread(cancellationToken).ConfigureAwait(false))
            {
                return(JobExecutionResult.NotStarted);
            }

            try
            {
                if (!await this.TrySetJobOwner(jobId, schedluerId).ConfigureAwait(false))
                {
                    return(JobExecutionResult.NotStarted);
                }

                JobExecutionResult result = JobExecutionResult.Failed;
                try
                {
                    this.logger.LogInformation("Starting job {0} execution at scheduler {1}", jobId, schedluerId);
                    result = await this.ExecuteJob(jobMetadata, cancellationToken).ConfigureAwait(false);

                    this.logger.LogInformation("Job {0} execution completed: {1}", jobId, result);
                    return(result);
                }
                finally
                {
                    await this.SetJobExecutionResult(jobId, jobMetadata, result).ConfigureAwait(false);
                }
            }
            finally
            {
                this.syncHelper.Release();
            }
        }
Exemplo n.º 12
0
        private JobExecutionResult Execute(string jobData, BasicHttpCallbackJobMetaData callbackJobData)
        {
            JobExecutionResult result = new JobExecutionResult();

            BasicHttpBinding binding = new BasicHttpBinding(callbackJobData.SecurityMode);

            binding.MaxReceivedMessageSize = callbackJobData.MessageSize;
            binding.ReaderQuotas.MaxStringContentLength = callbackJobData.MessageSize;
            binding.MaxBufferSize  = callbackJobData.MessageSize;
            binding.ReceiveTimeout = TimeSpan.FromMilliseconds(callbackJobData.TimeoutMilliseconds);
            binding.SendTimeout    = TimeSpan.FromMilliseconds(callbackJobData.TimeoutMilliseconds);
            binding.Security.Transport.ClientCredentialType = callbackJobData.TransportCredentialType;
            if (callbackJobData.MessageCredentialType.HasValue)
            {
                binding.Security.Message.ClientCredentialType = callbackJobData.MessageCredentialType.Value;
            }

            //This convoluted bit is used to ensure SSL (transport security) certificates are only ignored for urls where the job has it specified.
            if (callbackJobData.IgnoreCertificateErrors)
            {
                //The logic is not foolproof.  If you have 2 requests at the same time to the same host with different IgnoreCertificateErrors settings, the first one in will win.
                //The fix is to not use different settings for IgnoreCertificateErrors when calling the same host.
                lock (IgnoreSSLCertificatesForUriList)
                {
                    if (!IgnoreSSLCertificatesForUriList.ContainsKey(callbackJobData.CallbackUrl))
                    {
                        IgnoreSSLCertificatesForUriList.Add(callbackJobData.CallbackUrl, 1);
                    }
                    else
                    {
                        //Store a counter for how many times this url has been called with the ignore bit set.
                        IgnoreSSLCertificatesForUriList[callbackJobData.CallbackUrl]++;
                    }
                }
            }

            EndpointAddress endpoint = new EndpointAddress(callbackJobData.CallbackUrl);

            Response response = null;

            switch (callbackJobData.ContractType)
            {
            case ContractType.Basic:
                ChannelFactory <IBasicJobCallback> channelFactory = new ChannelFactory <IBasicJobCallback>(binding, endpoint);

                if (callbackJobData.IgnoreCertificateErrors)
                {
                    //Ignore X509 certs for message security
                    channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                    channelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
                }

                if (!string.IsNullOrEmpty(callbackJobData.Username) && !string.IsNullOrEmpty(callbackJobData.Password))
                {
                    //Event though Credentials and Credentials.Windows is used for different authentication mechanisms, it works just setting all like this
                    channelFactory.Credentials.UserName.UserName = callbackJobData.Username;
                    channelFactory.Credentials.UserName.Password = callbackJobData.Password;
                    channelFactory.Credentials.Windows.ClientCredential.Domain   = callbackJobData.Domain;
                    channelFactory.Credentials.Windows.ClientCredential.UserName = callbackJobData.Username;
                    channelFactory.Credentials.Windows.ClientCredential.Password = callbackJobData.Password;
                }

                IBasicJobCallback basicJobCallbackService = channelFactory.CreateChannel();
                try
                {
                    response = basicJobCallbackService.Execute(new BasicJobCallbackRequest {
                        Data = jobData, MetaData = callbackJobData.MetaData
                    });
                }
                catch
                {
                    throw;
                }
                finally
                {
                    try
                    {
                        channelFactory.Close();
                    }
                    catch { }
                }
                break;

            case ContractType.Composite:
                ChannelFactory <ICompositeJobCallback> compositeChannelFactory = new ChannelFactory <ICompositeJobCallback>(binding, endpoint);

                if (callbackJobData.IgnoreCertificateErrors)
                {
                    //Ignore X509 certs for message security
                    compositeChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                    compositeChannelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode            = X509RevocationMode.NoCheck;
                }

                if (!string.IsNullOrEmpty(callbackJobData.Username) && !string.IsNullOrEmpty(callbackJobData.Password))
                {
                    //Event though Credentials and Credentials.Windows is used for different authentication mechanisms, it works just setting all like this
                    compositeChannelFactory.Credentials.UserName.UserName = callbackJobData.Username;
                    compositeChannelFactory.Credentials.UserName.Password = callbackJobData.Password;
                    compositeChannelFactory.Credentials.Windows.ClientCredential.Domain   = callbackJobData.Domain;
                    compositeChannelFactory.Credentials.Windows.ClientCredential.UserName = callbackJobData.Username;
                    compositeChannelFactory.Credentials.Windows.ClientCredential.Password = callbackJobData.Password;
                }

                CompositeBasicHttpCallbackJobMetaData metaData = (CompositeBasicHttpCallbackJobMetaData)callbackJobData;

                ICompositeJobCallback compositeJobCallbackService = compositeChannelFactory.CreateChannel();
                try
                {
                    response = compositeJobCallbackService.Execute(new CompositeBasicJobCallbackRequest {
                        Data = jobData, MetaData = metaData.MetaData, MethodName = metaData.MethodName
                    });
                }
                catch
                {
                    throw;
                }
                finally
                {
                    try
                    {
                        compositeChannelFactory.Close();
                    }
                    catch { }
                }
                break;
            }

            if (response != null)
            {
                if (response.Result != null)
                {
                    callbackJobData.MetaData = response.Result.MetaData;
                    if (callbackJobData.ContractType == ContractType.Basic)
                    {
                        result.MetaData = callbackJobData.Serialize();
                    }
                    else
                    {
                        result.MetaData = ((CompositeBasicHttpCallbackJobMetaData)callbackJobData).Serialize();
                    }
                }
                else
                {
                    if (callbackJobData.ContractType == ContractType.Basic)
                    {
                        result.MetaData = callbackJobData.Serialize();
                    }
                    else
                    {
                        result.MetaData = ((CompositeBasicHttpCallbackJobMetaData)callbackJobData).Serialize();
                    }
                    result.ResultStatus = JobResultStatus.Fail;
                    result.ErrorMessage = "Response.Result was null.";
                }

                if (response.Exception != null)
                {
                    Exception ex = response.Exception.GetBase();
                    result.ResultStatus = JobResultStatus.Fail;
                    result.ErrorMessage = Utils.GetExceptionMessage(ex);
                }
                else
                {
                    result.ResultStatus = response.Result.ResultStatus;
                    result.ErrorMessage = response.Result.ErrorMessage;
                }
            }

            return(result);
        }
        private async Task SetJobExecutionResult(TJobKey jobId, IJobMetadata jobMetadata, JobExecutionResult jobExecutionResult)
        {
            try
            {
                await this.jobStore.FinalizeJob(jobId, jobMetadata, jobExecutionResult).ConfigureAwait(false);

                this.logger.LogTrace("Job {0} state cleared", jobId);
            }
            catch (ConcurrencyException ex)
            {
                this.logger.LogWarning(ex, "Somebody has already updated job {0}: {1}", jobId, ex.Message);
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Clearing job {0} state failed unexpectedly: {1}", jobId, ex.Message);
            }
        }
Exemplo n.º 14
0
 protected void EnsureCorrelationIsValid(TJob job, JobExecutionResult result)
 {
     Ensure.That(result.CorrelationId)
     .WithMessage("The CorrelationId on the job result does not match the CorrelationId of the original job.")
     .Is(job.CorrelationId);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Executes the job specified in the job context and updates the jobstore accordingly.
        /// </summary>
        /// <param name="jobContext">The job context.</param>
        public void ExecuteJob(JobContext jobContext)
        {
            if (jobContext == null)
            {
                throw new ArgumentNullException("jobContext");
            }
            if (jobContext.JobInstance == null)
            {
                throw new ArgumentNullException("jobContext.JobInstance");
            }
            if (jobContext.JobData == null)
            {
                throw new ArgumentNullException("jobContext.JobData");
            }
            if (jobContext.JobManager == null)
            {
                throw new ArgumentNullException("jobContext.JobManager");
            }
            if (!(jobContext.JobInstance is IJob))
            {
                throw new ArgumentException("BackgroundJobExecutor : jobContext.JobInstance must be of type IJob");
            }

            IJob        backgroundJob = (IJob)jobContext.JobInstance;
            IJobManager jobManager    = jobContext.JobManager;
            JobData     jobData       = jobContext.JobData;
            ILog        logger        = jobContext.JobManager.Logger;

            Debug.WriteLine(DateTime.Now.ToString("dd/mm/yyyy HH:mm:ss:fffffff") + " : " + jobContext.JobData.Id + " start execution.");

            try
            {
                jobData.LastStartTime    = DateTime.Now;
                jobData.LastEndTime      = null;
                jobData.LastErrorMessage = null;
                jobData.Status           = JobStatus.Executing;
                jobManager.JobStore.UpdateJob(jobData);
                JobExecutionResult returnValue = backgroundJob.Execute(jobContext.JobData.Data, jobContext.JobData.MetaData);
                if (returnValue == null)
                {
                    throw new ArgumentException("Execute(string jobData, string recoveryData) for job '" + jobContext.JobData.Id + "' returned null.");
                }
                jobData.LastEndTime = DateTime.Now;
                switch (returnValue.ResultStatus)
                {
                case JobResultStatus.Success:
                    jobData.Status = JobStatus.Done;
                    break;

                case JobResultStatus.FailAutoRetry:
                    jobData.Status = JobStatus.FailAutoRetry;
                    break;

                case JobResultStatus.FailRetry:
                    jobData.Status = JobStatus.FailRetry;
                    break;

                default:
                    jobData.Status = JobStatus.Fail;
                    break;
                }
                jobData.LastErrorMessage = (!string.IsNullOrEmpty(returnValue.ErrorMessage) ? returnValue.ErrorMessage : null);
                if (returnValue.MetaData != null && jobData.MetaData != returnValue.MetaData)
                {
                    jobData.MetaData = returnValue.MetaData;
                }
                jobData.NextStartTime = null;
                jobManager.JobStore.UpdateJob(jobData);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = Helpers.Utils.GetExceptionMessage(ex);
                jobData.Status           = JobStatus.Fail;
                jobData.LastErrorMessage = message;
                jobData.LastEndTime      = DateTime.Now;
                jobManager.JobStore.UpdateJob(jobData);
            }

            JobExecutionHistory history = null;

            try
            {
                if (!jobData.SuppressHistory && jobData.Status != JobStatus.Ready)                 //Status check added for the extreme case where the thread was aborted
                {
                    history = jobManager.JobStore.CreateJobExecutionHistory(jobData);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Could not create job execution history record.", ex);
            }

            if (jobData.Status != JobStatus.Done)
            {
                jobManager.JobStore.CreateAlert(jobData.Id, (history != null ? (long?)history.Id : null), jobData.LastErrorMessage);
            }

            Debug.WriteLine(DateTime.Now.ToString("dd/mm/yyyy HH:mm:ss:fffffff") + " : " + jobContext.JobData.Id + " end execution.");

            if (jobData.DeleteWhenDone && jobData.Status == JobStatus.Done)
            {
                try
                {
                    jobManager.JobStore.DeleteJob(jobData);
                    return;
                }
                catch (Exception ex)
                {
                    logger.Error("Could not delete job that was set to 'DeleteWhenDone'.", ex);
                }
            }

            if (jobData.Status == JobStatus.FailAutoRetry)
            {
                try
                {
                    jobManager.JobStore.SetJobStatuses(new long[] { jobData.Id }, jobData.Status, JobStatus.Ready);
                }
                catch (Exception ex)
                {
                    logger.Error("Could not set job to ready after FailAutoRetry result.", ex);
                }
            }

            if (jobData.Schedule != null)
            {
                try
                {
                    jobData.NextStartTime = jobData.Schedule.GetNextOccurrence(jobData.LastStartTime ?? jobData.Schedule.StartDateTime);
                    jobManager.JobStore.UpdateJob(jobData);
                    jobManager.JobStore.SetJobStatuses(new long[] { jobData.Id }, jobData.Status, JobStatus.Scheduled);
                }
                catch (Exception ex)
                {
                    logger.Error("Could not set job to ready for next scheduled execution.", ex);
                }
            }
        }