Ejemplo n.º 1
0
        private async Task <IActionResult> JsonCancelJobAsync <TId>()
        {
            var rawIds = Request.BodyAsJsonObject <TId[]>();
            var ids    = rawIds.ConvertAll(x => Convert.ToInt32(x));

            if (ids != null)
            {
                int numDeleted = 0;
                foreach (var jobId in ids)
                {
                    var job = await FindJobAsync(jobId);

                    if (job.CanBeCancelled)
                    {
                        Backgrounder.ChangeState(jobId.ToString(), new CancelledState());
                        numDeleted++;
                    }
                }
                if (numDeleted > 0)
                {
                    return(NoContent());
                }
            }
            return(NoContent());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Changes state of a job with the specified <paramref name="jobId"/>
        /// to the <see cref="EnqueuedState"/>. If <paramref name="fromState"/> value
        /// is not null, state change will be performed only if the current state name
        /// of a job equal to the given value.
        /// </summary>
        ///
        /// <param name="client">An instance of <see cref="IBackgroundJobClient"/> implementation.</param>
        /// <param name="jobId">Identifier of job, whose state is being changed.</param>
        /// <param name="fromState">Current state assertion, or null if unneeded.</param>
        /// <param name="queueName">The name of the queue to place the job in. This value overrides <see cref="QueueAttribute"/>.</param>
        /// <returns>True, if state change succeeded, otherwise false.</returns>
        public static bool Requeue(
            [NotNull] this IBackgroundJobClient client,
            [NotNull] string jobId,
            [CanBeNull] string fromState = null,
            [CanBeNull] string queueName = null)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            var state = new EnqueuedState();

            if (queueName != null)
            {
                state.Queue = queueName;
            }
            else
            {
                var job = JobStorage.Current.GetConnection().GetJobData(jobId)?.Job;
                if (job != null)
                {
                    state.Queue = job.QueueName;
                }
            }

            return(client.ChangeState(jobId, state, fromState));
        }
Ejemplo n.º 3
0
        public ActionResult SetFailed(string id)
        {
            var failedState = new FailedState(new Exception("Cambiando a fallida, provocado a proposito"));

            _backgroundJobClient.ChangeState(id, failedState);

            return(Ok());
        }
 /// <summary>
 /// Changes state of a job with the given <paramref name="jobId"/> to
 /// the specified one.
 /// </summary>
 ///
 /// <param name="client">An instance of <see cref="IBackgroundJobClient"/> implementation.</param>
 /// <param name="jobId">A job, whose state is being changed.</param>
 /// <param name="state">New state for a job.</param>
 /// <returns>True, if state change succeeded, otherwise false.</returns>
 public static bool ChangeState(this IBackgroundJobClient client, string jobId, IState state)
 {
     if (client == null)
     {
         throw new ArgumentNullException("client");
     }
     return(client.ChangeState(jobId, state, null));
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Changes state of a job with the given <paramref name="jobId"/> to
 /// the specified one.
 /// </summary>
 ///
 /// <param name="client">An instance of <see cref="IBackgroundJobClient"/> implementation.</param>
 /// <param name="jobId">A job, whose state is being changed.</param>
 /// <param name="state">New state for a job.</param>
 /// <returns>True, if state change succeeded, otherwise false.</returns>
 public static bool ChangeState(
     [NotNull] this IBackgroundJobClient client,
     [NotNull] string jobId,
     [NotNull] IState state)
 {
     if (client == null)
     {
         throw new ArgumentNullException(nameof(client));
     }
     return(client.ChangeState(jobId, state, null));
 }
        /// <summary>
        /// Changes state of a job with the specified <paramref name="jobId"/>
        /// to the <see cref="EnqueuedState"/>. If <paramref name="fromState"/> value
        /// is not null, state change will be performed only if the current state name
        /// of a job equal to the given value.
        /// </summary>
        ///
        /// <param name="client">An instance of <see cref="IBackgroundJobClient"/> implementation.</param>
        /// <param name="jobId">Identifier of job, whose state is being changed.</param>
        /// <param name="fromState">Current state assertion, or null if unneeded.</param>
        /// <returns>True, if state change succeeded, otherwise false.</returns>
        public static bool Requeue(this IBackgroundJobClient client, string jobId, string fromState)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            var state = new EnqueuedState();

            return(client.ChangeState(jobId, state, fromState));
        }
Ejemplo n.º 7
0
        public string Build()
        {
            try
            {
                // CREATING
                _buildAtom(this);

                // CREATED
                CreateAtomState();

                // RUN
                _client.ChangeState(_atomId, _initialState);
            }
            catch
            {
                // FULL CLEANUP IN CASE OF FAIL
                foreach (var createdJobId in _createdSubAtoms)
                {
                    _client.Delete(createdJobId.Key);
                }

                using (var connection = _jobStorage.GetJobStorageConnection())
                {
                    using var tr = connection.CreateJobStorageTransaction();
                    tr.RemoveSet(Atom.GenerateSubAtomKeys(_atomId));
                    var atomRemainingKeys = Atom.GenerateSubAtomRemainingKeys(_atomId);
                    foreach (var activeSubatoms in _createdSubAtoms.Where(x => !x.Value.IsFinal))
                    {
                        tr.RemoveFromSet(atomRemainingKeys, activeSubatoms.Key);
                    }
                    tr.Commit();
                }

                _client.Delete(_atomId);
                throw;
            }

            return(_atomId);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Changes state of a job with the specified <paramref name="jobId"/>
        /// to the <see cref="DeletedState"/>. If <paramref name="fromState"/> value
        /// is not null, state change will be performed only if the current state name
        /// of a job equal to the given value.
        /// </summary>
        ///
        /// <remarks>
        /// The job is not actually being deleted, this method changes only
        /// its state.
        ///
        /// This operation does not provides guarantee that the job will not be
        /// performed. If you deleting a job that is performing right now, it
        /// will be performed anyway, despite of this call.
        ///
        /// The method returns result of a state transition. It can be false
        /// if a job was expired, its method does not exist or there was an
        /// exception during the state change process.
        /// </remarks>
        ///
        /// <param name="client">An instance of <see cref="IBackgroundJobClient"/> implementation.</param>
        /// <param name="jobId">Identifier of job, whose state is being changed.</param>
        /// <param name="fromState">Current state assertion, or null if unneeded.</param>
        /// <returns>True, if state change succeeded, otherwise false.</returns>
        public static bool Delete(
            [NotNull] this IBackgroundJobClient client,
            [NotNull] string jobId,
            [CanBeNull] string fromState)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            var state = new DeletedState();

            return(client.ChangeState(jobId, state, fromState));
        }
Ejemplo n.º 9
0
        public async Task <bool> RunNow(int userjobId)
        {
            bool ret = false;

            if (!await IsAlreadyRunning(userjobId))
            {
                var record = await _dbService.GetBaseData(userjobId);

                if (record != null)
                {
                    if (record.HfJobId != null)
                    {
                        if (record.IsRecurringJob())
                        {
                            _logger.LogInformation("Manually triggering {t} userJobId {i}", record.JobType.ToString(), userjobId);
                            _recClient.Trigger(record.HfJobId);
                            ret = true;
                        }
                        else if (record.IsFireAndForgetOrScheduled())
                        {
                            _logger.LogInformation("Manually triggering {t} userJobId {i}", record.JobType.ToString(), userjobId);
                            _bgClient.ChangeState(record.HfJobId, new EnqueuedState());
                            ret = true;
                        }
                        else
                        {
                            throw new Exception($"Cannot manually run userJobId {userjobId}.Invalid JobType Detected.");
                        }
                    }
                    else
                    {
                        _logger.LogWarning("Cannot manually run userJobId {i}. Because HfJobId is null.", userjobId);
                    }
                }
                else
                {
                    _logger.LogWarning("Cannot manually run userJobId {i}. Because user job is not found.", userjobId);
                }
            }
            else
            {
                _logger.LogWarning("Cannot manually run userJobId {i}. Because it is already running.", userjobId);
            }

            return(ret);
        }
Ejemplo n.º 10
0
        private static void SetTriggerInternal(
            IBackgroundJobClient client,
            JobStorageConnection connection,
            string triggerName)
        {
            var triggerKey = GenerateTriggerKey(triggerName);
            var jobIds     = connection.GetAllItemsFromList(triggerKey);

            try
            {
                using var _ = connection.AcquireDistributedLock(triggerKey, TimeSpan.Zero);

                foreach (var jobId in jobIds)
                {
                    client.ChangeState(jobId, new EnqueuedState());
                }
            }
            catch (DistributedLockTimeoutException)
            {
                // Assume already run
            }
        }
Ejemplo n.º 11
0
        public string ResumeJob(IDSFDataObject dsfDataObject, string jobId, bool overrideVariables, string environment)
        {
            try
            {
                var monitoringApi = _jobStorage.GetMonitoringApi();
                var jobDetails    = monitoringApi.JobDetails(jobId);
                var currentState  = jobDetails.History.OrderBy(s => s.CreatedAt).LastOrDefault();

                if (currentState?.StateName != "Scheduled" && currentState?.StateName != "Failed")
                {
                    return(GlobalConstants.Failed);
                }

                var values = jobDetails.Job.Args[0] as Dictionary <string, StringBuilder>;
                values.TryGetValue("environment", out StringBuilder persistedEnvironment);
                var decryptEnvironment = persistedEnvironment.ToString().CanBeDecrypted() ? DpapiWrapper.Decrypt(persistedEnvironment.ToString()) : persistedEnvironment.ToString();
                if (overrideVariables)
                {
                    if (values.ContainsKey("environment"))
                    {
                        values["environment"] = new StringBuilder(environment);
                    }
                }
                else
                {
                    values["environment"] = new StringBuilder(decryptEnvironment);
                }
                values.TryGetValue("currentuserprincipal", out StringBuilder currentUserPrincipal);
                var decryptCurrentUserPrincipal = currentUserPrincipal.ToString().CanBeDecrypted() ? DpapiWrapper.Decrypt(currentUserPrincipal.ToString()) : currentUserPrincipal.ToString();
                if (values.ContainsKey("environment"))
                {
                    values["currentuserprincipal"] = new StringBuilder(decryptCurrentUserPrincipal);
                }
                var workflowResume = new WorkflowResume();
                var result         = workflowResume.Execute(values, null);
                var serializer     = new Dev2JsonSerializer();
                var executeMessage = serializer.Deserialize <ExecuteMessage>(result);
                if (executeMessage.HasError)
                {
                    var failedState = new FailedState(new Exception(executeMessage.Message?.ToString()));
                    _client.ChangeState(jobId, failedState, ScheduledState.StateName);
                    return(GlobalConstants.Failed);
                }

                values.TryGetValue("resourceID", out StringBuilder workflowId);
                values.TryGetValue("environment", out StringBuilder environments);
                values.TryGetValue("startActivityId", out StringBuilder startActivityId);
                values.TryGetValue("versionNumber", out StringBuilder versionNumber);
                values.TryGetValue("currentprincipal", out StringBuilder currentprincipal);

                _stateNotifier = dsfDataObject.StateNotifier;
                var audit = new Audit
                {
                    WorkflowID     = workflowId?.ToString(),
                    Environment    = environments?.ToString(),
                    VersionNumber  = versionNumber?.ToString(),
                    NextActivityId = startActivityId?.ToString(),
                    AuditDate      = DateTime.Now,
                    AuditType      = "LogResumeExecutionState",
                    LogLevel       = LogLevel.Info,
                    User           = currentprincipal?.ToString()
                };

                _stateNotifier?.LogAdditionalDetail(audit, nameof(ResumeJob));
                var manuallyResumedState = new ManuallyResumedState(environments?.ToString());

                _client.ChangeState(jobId, manuallyResumedState, currentState?.StateName);
                return(GlobalConstants.Success);
            }
            catch (Exception ex)
            {
                _stateNotifier?.LogExecuteException(ex, this);
                Dev2Logger.Error(nameof(ResumeJob), ex, GlobalConstants.WarewolfError);
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 12
0
 public bool ChangeState(string jobId, IState state, string expectedState)
 {
     return(_jobClient.ChangeState(jobId, state, expectedState));
 }